0
votes

I'm working on script for Google Sheets which sends data to server. Target Google Sheets document have several sheets. Each sheet must have its own menu. So I've searched for any trigger that fires when active sheet is changed but I couldn't.

How can I get event of sheet switching?

Thank you :)

Update. I have this function:

function onOpen() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var menuEntries = [
    { name: "Upload " + sheet.getName() + " to Server", functionName: "ExportSheet" },
  ];
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.addMenu("Export JSON", menuEntries);

}

But I want to replace onOpen by function that will be called by some event that fires on activating a sheet.

Update 2.

const ss=SpreadsheetApp.getActive();

function onOpen(e) {
  CreateMenuOptions(e);
}

function onSelectionChange(e) {
  CreateMenuOptions(e);
}

function CreateMenuOptions(e){
  var sheetName = e.range.getSheet().getName();
  var menuEntries = [
    { name: "Upload " + sheetName + " to Server", functionName: "ExportSheet" },
  ];
  ss.updateMenu("Export to JSON", menuEntries);
  ss.toast(sheetName);
  console.log(sheetName);
}

I apply changes according to answer of @Cooper. Now, onOpen still works fine, but onSelectionChange don't do anything unless log name of sheet. Menu is not updated and toast is not shown. :(

1
When you say that each sheet must have it's own menu, are you talking about Spreadsheets or Sheets.Cooper
I'm talking about Spreadsheets menu. But menu should be different for different active sheets.HedgehogNSK

1 Answers

3
votes

Try this:

function onSelectionChange(e) {
  const ss=SpreadsheetApp.getActive();
  ss.toast(e.range.getSheet().getName());
}

The only reason that it gets the new sheet is because the selection changes as you go from one sheet to another. But it will fire on any selection change.