google-sheetsgoogle-apps-script

Google apps script Selecting sheets from dynamic menu in google sheets


I have a spreadsheet with very big amount of sheets and it's now hard to find the right sheet in sheet list at the bottom. I'd like to use script that generates menu with list of sheets (1 menu item = 1 sheet) in this spreadsheet. And so that clicking on this menu item changes active sheet to the selected sheet

I tried to google it, but I've only found ways to manually create link to each sheet and I don't understand how to make a dynamic number of menu items with links on every sheet. I would be glad of your help.


Solution

  • Dynamically changed active sheet

    To achieve the ability to dynamically set the active sheet in a spreadsheet file by, you can implement a an apps script program that contains a drop down menu that contains all the sheet names in the spreadsheet and upon selecting an item in the dropdown, the corresponding sheet will be activated.

    The script below uses apps scripts onOpen and OnEdit simple triggers. Upon opening the Spreadsheet, the script will create a dropdown menu on sheet named “Menu” you can then select an option(a sheet name) and that sheet name will be activated.

    Script

    function onOpen(e) {
      var ss = e.source;
      let sheets = ss.getSheets();
      let sheetNames = sheets.map(sheet => sheet.getName());
    
      var cell = ss.getSheetByName("Menu").getRange("A1");
      var rule = SpreadsheetApp.newDataValidation().requireValueInList(sheetNames).build();
      cell.setDataValidation(rule);
    }
    
    function onEdit(e) {
      var ss = e.source;
      var cell = ss.getRange("A1");
      var selectedSheetName = cell.getValue();
    
      var sheetNames = ss.getSheets().map(sheet => sheet.getName());
      if (sheetNames.includes(selectedSheetName)) {
        ss.setActiveSheet(ss.getSheetByName(selectedSheetName));
      } else {
        Logger.log("Invalid sheet name selected: " + selectedSheetName);
      }
    }
    

    Output Output

    References: apps script data validation, apps script triggers