I am trying to add in links to a menu in Google sheets using Google Script (JavaScript), based on some criteria. Google's API template for adding menu items is below:
addItem(caption, functionName)
The functionName
parameter can't itself take input parameters, and since I have a variable number of worksheets within my document, I am trying to generate arbitrary number functions in a for loop, so that they may be available without needing any input parameters:
function createGotoMenuFunctions(scope) {
var ss = SpreadsheetApp.getActive();
var sheets = ss.getSheets();
for (var s=0; s<sheets.length; s++){
var sht = sheets[s];
var shtName = sht.getName();
var funcName = 'goto' + shtName.replace(/\s/g, '_') + 'menu';
scope[funcName] = function() {
ss.setActiveSheet(sht);
}
}
}
createGotoMenuFunctions(this); //global scope
This creates a set of functions for each sheet named (for example) gotoSheet1menu()
, gotoSheet2menu()
, gotoSheet3menu()
. However, when I call any of the functions, they all activate the last sheet. For example, if I call gotoSheet1menu()
, it activates Sheet3. I believe this is due to ss
and sht
getting passed by reference instead of by value. Is there some way to fix this?