r/GoogleAppsScript • u/VAer1 • 6d ago
Resolved SpreadsheetApp.openById related issue
Previous post: https://www.reddit.com/r/GoogleAppsScript/comments/1xzjvlk/how_to_call_a_function_from_another_project_when/
I previously used the following code:
ss = SpreadsheetApp.getActiveSpreadsheet();
However, I have now changed it to:
ss = SpreadsheetApp.openById("1iD........Yq8");
The reason for this change is that I need to call the function (reason: above post).
I have an onOpen() function. Previously when I opened the sheet for first time, it worked correctly with SpreadsheetApp.getActiveSpreadsheet(), but it seems to fail when I use SpreadsheetApp.openById() instead.
Interestingly, if the spreadsheet is already open and I manually run the onOpen() function, it works without any issues.
I'm not entirely sure what is causing this behavior, it seems onOpen does not work well with SpreadsheetApp.openById. Could it be a timing issue, where the spreadsheet ID or access to the spreadsheet is not yet available when onOpen() first runs?
Is there a way to work around this issue?
Edit: I solved it by changing onOpen to a different name handleOpen, then create a trigger to run handleOpen when opening the sheet.


4
u/marcnotmark925 6d ago
Simple Triggers are not allowed to run code that requires auth scopes.
1
u/BewareTheGiant 6d ago
The issue is probably, as the error indicates, related to the permissions. You probably have a narrow scope only to the current sheet, which is why
getActiveSpreadsheet()andonOpen()work.openById, however, requires access to all your spreadsheets, because it isn't checking whether the id you are passing is the id the script is attached to