When to use getActiveSpreadsheet? - google-apps-script

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?

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

Related

ActiveSheet().getName() returns different results. Could somebody explain why? [duplicate]

I guess this question is the most similar to my current question. But basically, I have a google sheets file that has several sheets along the bottom. I would like for the user to execute this script on whatever sheet they have open at the time.
And like the previous question said according to this documentation, the active sheet is the one that is being displayed in the spreadsheet UI. I assume this means if I have the google sheets file open in another tab, that the sheet currently selected and viewable by me is intended to be the active sheet.
However, the actual active sheet returned is always the leftmost sheet along the bottom tabs. I've confirmed it by switching the order of the sheets. So no matter what sheet I actually have open and visible in the UI, it always gets the leftmost sheet. Here is the line that gets it.
var Sheet = SpreadsheetApp.openById("redactedid").getActiveSheet()
Is this a known error with App Script? Or is the documentation wrong? If it is, is there a workaround for getting the currently open sheet in the UI? I don't want anyone to have to hardcode a sheetname in the code as the file is constantly changing and sheets are being added.
Notes:
To use getActiveSheet() or any active object, the calling
Script must be bound to the Spreadsheet
Script function should be invoked from menu or button or macro keyboard shortcuts and NOT from webapp or API( Script editor also works, but not preferred).
Spreadsheet must be open/visible in the user interface/browser preferably in the active/currently selected window.
All previous calls to get objects must have used active. For eg, To get active range, You should have first got active spreadsheet => active sheet => active range(the chain of active objects). If any of the calls is not to the active object(say if you used getSheetByName() instead of getActiveSheet() in the middle step), the final call is likely to default to the default object(First sheet A1).
Solution:
Here, To get Spreadsheet, use SpreadsheetApp.getActive() instead of SpreadsheetApp.openById(), So that getActiveSheet() will be under the chain of active objects.
Snippet:
const sheet = SpreadsheetApp.getActive().getActiveSheet();
It's known that the getActiveSheet method returns the first sheet when used with an spreadsheet that is not the active spreadsheet.
The active spreadsheet is retrieved by using getActiveSpreadsheet. I only works on scripts bounded to an spreadsheet and in G Suite Editors add-on for spreadsheets.
In the the same way, getCurrentCell and getActiveRange returns A1 when corresponding sheet is not an active sheet (meaning it's not a sheet from an active spreadsheet)
Resources
https://developers.google.com/apps-script/guides/sheets
Related
Google Apps Script, select a sheet - Sets values in first sheet tab - not a specific sheet tab
All the points in the accepted solution are all true, but sometimes your spreadsheet looses some connection to something on Google's back end or the cache gets corrupted, who knows. The fix is to close the all tabs for the worksheet, editor, triggers, executions -- whichever ones you have open for that spreadsheet, close them. Reopen the spreadsheet. Start again. It's fine now.

Cannot read property 'getSheetByName' of null

function sortResponses() {
var Sheets = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Fall 01")
sheet.sort(3, false);
}
I have a Sheet called Fall 01 in my google Sheets, where I explicĂ­tly had to give the script access to, but it won't open, what am I missing?
Explanation/Issue:
The issue is that you have a standalone script which therefore is not bound to a google spreadsheet and as a result SpreadsheetApp.getActiveSpreadsheet() returns null.
Solutions:
There are two ways you can follow:
Solution 1:
Use SpreadsheetApp.openById(id) or SpreadsheetApp.openByUrl(url):
var Sheets = SpreadsheetApp.openById("Put your Spreadsheet ID").getSheetByName("Fall 01");
or
var Sheets = SpreadsheetApp.openByUrl("Put your Spreadsheet URL").getSheetByName("Fall 01");
Solution 2:
Go to the spreadsheet file that you want to work with and click on Tools => Script editor on the top menu of the spreadsheet file and put your current code there.
Please Note
If this is your only code, sheet is not defined, therefore you will get another error down the road. You most likely want to replace sheet with Sheets or the other way around. Be careful with this.

Google App Script getActiveSheet returns leftmost sheet, not active sheet

I guess this question is the most similar to my current question. But basically, I have a google sheets file that has several sheets along the bottom. I would like for the user to execute this script on whatever sheet they have open at the time.
And like the previous question said according to this documentation, the active sheet is the one that is being displayed in the spreadsheet UI. I assume this means if I have the google sheets file open in another tab, that the sheet currently selected and viewable by me is intended to be the active sheet.
However, the actual active sheet returned is always the leftmost sheet along the bottom tabs. I've confirmed it by switching the order of the sheets. So no matter what sheet I actually have open and visible in the UI, it always gets the leftmost sheet. Here is the line that gets it.
var Sheet = SpreadsheetApp.openById("redactedid").getActiveSheet()
Is this a known error with App Script? Or is the documentation wrong? If it is, is there a workaround for getting the currently open sheet in the UI? I don't want anyone to have to hardcode a sheetname in the code as the file is constantly changing and sheets are being added.
Notes:
To use getActiveSheet() or any active object, the calling
Script must be bound to the Spreadsheet
Script function should be invoked from menu or button or macro keyboard shortcuts and NOT from webapp or API( Script editor also works, but not preferred).
Spreadsheet must be open/visible in the user interface/browser preferably in the active/currently selected window.
All previous calls to get objects must have used active. For eg, To get active range, You should have first got active spreadsheet => active sheet => active range(the chain of active objects). If any of the calls is not to the active object(say if you used getSheetByName() instead of getActiveSheet() in the middle step), the final call is likely to default to the default object(First sheet A1).
Solution:
Here, To get Spreadsheet, use SpreadsheetApp.getActive() instead of SpreadsheetApp.openById(), So that getActiveSheet() will be under the chain of active objects.
Snippet:
const sheet = SpreadsheetApp.getActive().getActiveSheet();
It's known that the getActiveSheet method returns the first sheet when used with an spreadsheet that is not the active spreadsheet.
The active spreadsheet is retrieved by using getActiveSpreadsheet. I only works on scripts bounded to an spreadsheet and in G Suite Editors add-on for spreadsheets.
In the the same way, getCurrentCell and getActiveRange returns A1 when corresponding sheet is not an active sheet (meaning it's not a sheet from an active spreadsheet)
Resources
https://developers.google.com/apps-script/guides/sheets
Related
Google Apps Script, select a sheet - Sets values in first sheet tab - not a specific sheet tab
All the points in the accepted solution are all true, but sometimes your spreadsheet looses some connection to something on Google's back end or the cache gets corrupted, who knows. The fix is to close the all tabs for the worksheet, editor, triggers, executions -- whichever ones you have open for that spreadsheet, close them. Reopen the spreadsheet. Start again. It's fine now.

Clear a cell using a macro in a separate sheet

I would like to create a macro in sheets that would open a different spreadsheet and clear data from certain cells. I can do it in the same spreadsheet, but haven't been able to figure out how to do it when I have spreadsheet 'A' open and want to delete information on spreadsheet 'B'
You can use either SpreadsheetApp.openById('{your_sheet_id}') (see documentation) or SpreadsheetApp.openByUrl('{your_sheet_url}') (see documentation).
Then you can chain with the usual getSheet(), getRange() and clear() or clearContent() methods, e.g.:
SpreadsheetApp.openById('xxxxxxxxx').getSheetByName('Sheet1').getRange('A4').clearContent();

How to create a defined named range in google sheets using script

Is it possible to create named ranges in Google sheets using google script? I would then want the spreadsheet to be able to use these in formulas.
You may want to check out this post:
setNamedRange() outside of the spreadsheet container?
and see if that helps you ..
Class SpreadSheet has the method setNamedRange(name, Range) that can be used.
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.setNamedRange("myNamedRange", SpreadsheetApp.getActiveRange());
Link to the Google Documentation:
https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet?hl=en#setnamedrangename,-range
With me the pitfall was that I thought the method setNamedRange() belonged to the Class Range or Class Sheet. But turns out it belongs to the SpreadSheet Class.