Because you are calling the function from a spreadsheet trigger, instead of using SpreadsheetApp.openById(id)
to get the active sheet, you should use the event object.
To learn about the event objects in Google Apps Script, go to https://developers.google.com/apps-script/guides/triggers/events
All the Spreadsheet event objects have a source
property that returns the Class Spreadsheet object corresponding to the active spreadsheet.
The Edit event object also includes the range
property corresponding to the edited range.
Using the on-edit installable trigger, use the range
property with the getSheet()
method.
function respondToEdit(e){
const sheet = e?.range.getSheet();
console.log(sheet?.getName() ?? 'Remember, this should be called by a on edit trigger');
}
NOTES
null
will be assigned to e
when the function is run by clicking the Run button. Because of this, I use ?.
, ??
and a custom message to handle accidental executions.
You might try to use source
instead of range
, but in such case, use getActiveSheet()
. Theoretically, this should work too. I feel more confident about using the edit method because it is only triggered by edit events, while other events might start the change method and require more complex handling.
SpreadsheetApp.openById(id)
is unaware of the trigger / execution context other than the authorization to be executed; it gets an independent spreadsheet instance without the user selection information to return the first cell as the active range. Hence, the first sheet is returned as the active sheet, no matter how this method was called.
SpreadSheet
as a reserved name, so you should explain what it is. It's a common practice to include sample code, usually referred to as minimal complete example or minimal complete and verifiable example (mcve) as text, the textual error message, / logs.openById(id)
instead ofgetActiveSpreadsheet()
or why you are not usinggetActiveSheet()
if what you are looking is to get the the active sheet.