Suppose you have two sheets, say "Boys" and "Girls", and two corresponding .gs files "Boys.gs" and "Girls.gs".
In Boys.gs, we've declared a variable classID
to be the value located in cell B7
of the sheet "Boys":
var app = SpreadsheetApp;
var activeSheet = app.getActiveSpreadsheet(); //Get current active spreadsheet
var sheetBoys = activeSheet.getSheetByName('Boys');
var classID = sheetBoys.getRange('B7');
In Girls.gs, we also want to declare the variable classID
, but now we want it to be the value located in cell B9
of the sheet "Girls":
var app = SpreadsheetApp;
var activeSheet = app.getActiveSpreadsheet(); //Get current active spreadsheet
var sheetGirls = activeSheet.getSheetByName('Girls');
var classID = sheetGirls.getRange('B9');
Both Boys.gs and Girls.gs contain multiple functions that utilize classID
.
Objective
I'd like to use the variable classID
defined in Boys.gs across all functions in Boys.gs. Similarly, I'd like to use the variable classID
defined in Girls.gs across all functions in Girls.gs.
Issue
I currently have to define classID
repeatedly in every Boys.gs and/or Girls.gs function which uses it. If I define it outside of the functions, then I have two definitions across the two different files.
Of Note: As far as I understand, I can't nest the functions on each .gs inside a master function because I have tied specific functions to specific "buttons" in the spreadsheet, as well as to OnEdit and OnOpen functions.
Is there a way to define the variable to be used only within the functions on the given .gs file?
CodePudding user response:
There's no script-file level scope for variables declared in Apps Script. Therefore, there's no way to define a variable to be used only within the function on a given .gs
file. Any variable defined outside of a function will be accessible to any function in any of the .gs
files in your project.
Therefore, if you don't want to declare the variable inside every function, I'd just declare two different variables (in the example you provided, something like boysClassID
and girlsClassID
). Any workaround I can think of (for example, the use of PropertiesService, as mentioned in comments) seems more of a mess than this, as long as the number of these variables is kept relatively low.