Reputation: 25
I would like to know if there's a way to automatically trigger a script every time a specific sheet, inside a worksheet, is selected.
Looking around I found the onSelectionChange function but I have not been able to use it for my scope. Script draft below.
function onSelectionChange(e)
{ // Run update script when sheet is selected
var sheet = e.sheet;
var ssname = SpreadsheetApp.getActiveSheet().getName();
if(ssname === "Projects") {
UpdateProjects();
}
}
Any suggestion would be much appreciated. Thanks!
Upvotes: 1
Views: 1049
Reputation: 201693
I believe your goal as follows.
I thought that in this case, your goal can be achieve by modifying the sample script of this thread.
Please copy and paste the following sample script to the container-bound script of Google Spreadsheet, and save the script.
Please reopen the Google Spreadsheet.
onOpen
is run and the current sheet is put to PropertiesService.onSelectionChange
has no information about the change of tab. So in order to detect the change of tab, I used the PropertiesService.Then, please select other sheet on Google Spreadsheet.
onSelectionChange
is run by the onSelectionChange event trigger, and when the activated sheet is included in specificSheetNames
, the script of e.source.toast("Run script");
is run.function onOpen(e) {
const prop = PropertiesService.getScriptProperties();
const sheetName = e.range.getSheet().getSheetName();
prop.setProperty("previousSheet", sheetName);
}
function onSelectionChange(e) {
const specificSheetNames = ["Projects"]; // Please set the sheet names you want to run the script.
const prop = PropertiesService.getScriptProperties();
const previousSheet = prop.getProperty("previousSheet");
const range = e.range;
const a1Notation = range.getA1Notation();
const sheetName = range.getSheet().getSheetName();
if (!specificSheetNames.includes(sheetName)) return;
// When the specifc sheet names are activated, this script is run.
e.source.toast("run script"); // This is a sample script.
prop.setProperty("previousSheet", sheetName);
}
UpdateProjects()
in your script. In the current stage, all methods cannot be run with onSelectionChange
because of the authorization. Because this trigger is the simple trigger. So please be careful this. So as a simple test for checking above script, at first, please use e.source.toast("run script");
.Upvotes: 1