r/GoogleAppsScript • u/VAer1 • 6d ago
Resolved How to call a function from another project when including some code like getActiveSpreadsheet()?
This is a follow-up question to the post above, but since it's a different question, I'm creating a new post.
S2GoogleScript is script embedded in a Google Spreadsheet, and it uses getActiveSpreadsheet(). How should I modify the code so that it can be called correctly from another project?
Before I consolidated 15 triggers under a single main trigger, each trigger worked independently without any issues. However, now I get an error when one project calls a function from another.
What is the proper way to handle this?
Edit: I solved it by using
const ss = SpreadsheetApp.openById

3
u/Aquaductswag 6d ago
When you call S2GoogleScript as a library, its code runs in the context of the calling project, not the spreadsheet it is bound to. So getActiveSpreadsheet() no longer means "my sheet". From a time-driven trigger in a project with no container it returns null, and the next .getSheetByName() throws.
If line 2 of globalvariable.gs is something like
const ss = SpreadsheetApp.getActiveSpreadsheet();, that runs as soon as the library loads, which is why it fails before your function even starts.Fix: open the file by ID instead.
Do that in every library, and pass the ID in as a parameter if one function needs to work on different files. openById works the same whether it is called directly, from a trigger or from another project.
1
u/DrMorris 6d ago
We need to see whats on row 2 of globalvariable.gs guessing thats one of the libraries.