Xinrui Zhou
Xinrui Zhou

Reputation: 21

Dynamically Create Functions

Background: I want to create a quick way to navigate between sheets in Google Sheets.

My initial approach was to create a Table of Contents page, listing all sheet names with hyperlinks. While this method works, there's one thing I don't like: clicking on a sheet name doesn't immediately jump to it. Instead, I have to hover over the link first and then click it, which feels inconvenient.

So, I decided to try a different approach: adding a custom "Sheets" menu to the toolbar, which would display a dropdown list of all sheets. Clicking on any sheet name should take me directly to that sheet.(This should work similar with the built in google sheets tab manager on the left side of all sheet tabs)

The Problem: My idea was to dynamically create a set of functions, each corresponding to a sheet. When a menu item is clicked, it would call the corresponding function to navigate to that sheet.

However, after writing the code, I realized that Google Apps Script doesn’t seem to support dynamically creating functions this way, so the script doesn’t work as expected.

function onOpen() {
      var ui = SpreadsheetApp.getUi();
      var menu = ui.createMenu("Sheets");
    
      var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
      sheets.forEach(sheet => {
        var sheetName = sheet.getName();
        menu.addItem(sheetName, "goToSheet_" + sheetName.replace(/\W/g, "_"));
      });
    
      menu.addToUi();
      
      createNavigationFunctions(sheets); 
    }
    
    function createNavigationFunctions(sheets) {
      sheets.forEach(sheet => {
        var sheetName = sheet.getName();
        var safeName = sheetName.replace(/\W/g, "_"); 
    
        globalThis["goToSheet_" + safeName] = function() {
          var ss = SpreadsheetApp.getActiveSpreadsheet();
          var targetSheet = ss.getSheetByName(sheetName);
          if (targetSheet) {
            ss.setActiveSheet(targetSheet);
          }
        };
      });
    }

Need Help: It looks like Google Apps Script doesn’t allow dynamically defining functions this way, which means the menu is created, but clicking a sheet name says the

script function does not found.

I want this to work just like the built-in tab manager in Google Sheets, but as a dropdown menu in the toolbar and displaying more sheets. Is there a better way to implement this? Looking for a cleaner, working solution. Any help would be much appreciated!

Upvotes: 2

Views: 30

Answers (0)

Related Questions