Google script: How do I find active cell in a different spreadsheet - google-apps-script

I have an active cell in an open google sheet. I have a macro in a different spreadsheet that wants to get the value of the target active cell in a different google spreadsheet. Currently when I run the macro it is finding Sheet1 in the target workbook, but not the active sheet. How do I find the active sheet and active cell when I run the macro?
function getFormula() {
//Precedents
var ssThis=SpreadsheetApp.openById("1VMwjomfjtJLIQc<replaced>8J1zWx_GujXuCY");
//Universal Demo - v5
var tss = SpreadsheetApp.openById("1Pev8gCbl_Mn9JMJId<replaced>Cbc0aikBZambI");
var targetSheet=tss.getActiveSheet();
var targetSheetName=targetSheet.getName();
Logger.log(targetSheetName);
var cellThis=targetSheet.getActiveCell();
var targetFormula=cellThis.getFormula();
Logger.log(targetFormula);
getPrecedents(targetFormula);
}

The script doesn’t have a direct relation with the Sheets UI regarding the active cells, sheets, etc, at least that you’re using a container bound spreadsheet and you’re running the script with a macro or add-on inside the spreadsheets UI (as i understand you’re doing). But in this case, you’ll only be able to work with the active cells on the spreadsheet that’s container bound.
To summarize, the functions getActiveSheet() and getActiveCell() will only return the correct value for a container bound spreadsheet, running the script inside the spreadsheet (macro or add-on) and using the “getActive...” functions to obtain the spreadsheet, sheet or range, (instead of openById()) [1]. For example:
var ssThis = SpreadsheetApp.getActiveSpreadsheet();
var activeSheet=ssThis.getActiveSheet();
var cellThis=activeSheet.getCurrentCell();
In any other cases, on the spreadsheet you open, it will always return the first sheet and the first celL (A1). At least you use the “activate()” function [2] or “setActive…” functions [3] to set the active cell or sheet, but for this you would have to know the active cell.
[1] https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app#getactive
[2] https://developers.google.com/apps-script/reference/spreadsheet/range
[3] https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app#setactiverangerange

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.

How to apply a macro to all sheets in one spreadsheet in Google Sheets

I have a recorded macro in google sheets for one sheet in my spreadsheet. I would like to edit the script so that it will apply to all sheets in the spreadsheet (so that I won't have to run the recorded macro in each sheet separately). I've seen articles on how to do this in Excel but is it possible in Google Sheets?
are you sure it doesn't work on the other sheets? recorded macros usually use the active sheet not a named sheet.
Although I am 9 months late in answering this, here is a working answer to your question with an example to clear all visible sheets using another function called ClearActiveSheet. If someone is still looking for how to do this, this should give an idea.
function ClearActiveSheet() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();
sheet.getRange('A1').activate();
sheet.clear();
};
function ClearAllVisibleSheets() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
sheets.forEach(function(sheet) {
//You would need to make this the current active sheet, so that you can call the ClearActiveSheet function that works on active sheet
sheet.activate()
// Now since you have this sheet activated, you can call the function to clear the active sheet
ClearActiveSheet();
});
};
Select the function ClearAllVisibleSheets in GoogleSpredsheets from Tools-> ScriptsEditor -> SelectFunction (ClearAllVisibleSheets) and run/or debug and you will see this do the job.
P.S: If this satisfies your need, remember to upvote and kindly accept this as an answer :).

When to use getActiveSpreadsheet?

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