The onOpen(e)
function is a simple trigger that will run automatically each time the spreadsheet is opened. In that context, API methods that require authorization are not available.
When a script function is called by the spreadsheet, globals get evaluated before the function runs. In the onOpen(e)
context, SpreadsheetApp.openById()
will error out because of the lacking authorization, and onOpen(e)
never gets the chance to run.
One way to solve this is to put your globals inside a function, say getSettings_()
, that returns an object that contains the often used variables, and call it from the functions that use those values. It could be something like this:
let settings;
function getSettings_() {
if (settings) {
return settings;
}
settings = {
elLibro: SpreadsheetApp.openById("1pfbd7oziXmBTsOh5RhfvhsjW5wU6QF9suN7SNrE8rew"),
laHoja: elLibro.getSheetByName("Cuotas"),
laHojaTablaFinal: elLibro.getSheetByName("Tabla final"),
};
return settings;
}
function someFunction(someParameter) {
const settings = getSettings_();
const someValue = settings.laHoja.getRange('A1');
console.log(someValue);
}
function onOpen(e) {
// ... does not call getSettings_()
// ...
}
This pattern has the benefit that functions that require those globals can get them easily, while functions that do not require those globals do not need to get them and will thus run faster.
The values in settings
are only set once. When multiple functions call getSettings_()
in turn, the first call fills the settings
object, and subsequent calls just get a reference to that same copy of the object. Possible runtime modifications to settings
are seen by all functions within the same runtime instance.