I'm trying to understand when to use getActiveSpreadsheet()
.
I've seen numerous examples:
var ss = SpreadsheetApp.getActiveSheet();
But I've also seen:
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
Is the active spreadsheet implied in some circumstances?
The active sheet in a spreadsheet is the sheet that is being displayed in the spreadsheet UI.
Get the Current Sheet Name in a CellClick the Tools option in the menu. In the options that show up, click on Script editor. This will open the back end Apps Script editor in Google Sheets. In the Code.gs window, delete the default text and paste the above script code.
To get the name of the currently active sheet, we need to first get a reference to the spreadsheet. Then we use the getActiveSheet() method of the Spreadsheet object to get the sheet that is active. Finally, we use the getName() method of the Sheet object to get its name.
Yes, it is implied. The reference for SpreadsheetApp states:
getActiveSheet()
Gets the active sheet in a spreadsheet. The active sheet in a spreadsheet is the sheet that is being displayed in the spreadsheet UI.
Including the getActiveSpreadsheet() is probably often done because the getting of a spreadsheet is needed for other sheets and methods and it keeps the command flow consistent when done everywhere.
getActiveSpreadsheet()
is a method used by container-bound script.
A script is bound to a Google Sheets, Docs or Forms file if it was created from that document rather than as a standalone script. The file a bound script is attached to is referred to as a "container". Bound scripts generally behave like standalone scripts except that they do not appear in Google Drive, they cannot be detached from the file they are bound to, and they gain a few special privileges over the parent file.
getActiveSpreadsheet()
, getActiveDocument()
, and getActiveForm()
allow bound scripts to refer to their parent file without referring to the file's ID.
In Google Sheets, getActiveSheet()
, getActiveRange()
, and getActiveCell()
let the script determine the user's current sheet, selected range of cells, or selected individual cell. setActiveSheet(sheet)
and setActiveRange(range)
let the script change those selections.
Taken from https://developers.google.com/apps-script/guides/bound
getActiveSheet() is usefull when you are working with one sheet in the active spreadsheet.
You would use getActiveSpreadsheet() when you need to use other methods for example getSheets() would get all the sheets and you can access them as an array. Or if you wish to work with the spreadsheet as opposed to the sheet itself.
A good example would be the methods available to the spreadsheet class which would not be available for the sheet class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With