Home > Blockchain >  How do I use onSelectionChange(e) to switch to another sheet in the UI? [setActiveSheet()]
How do I use onSelectionChange(e) to switch to another sheet in the UI? [setActiveSheet()]

Time:01-20

I have successfully used onSelectionChange(e) to update data in another sheet. I want to also change to that sheet as the active one in the UI, but can not get it to work. What am I missing?

This is what I have tried:

function onSelectionChange(e) { 
  const cell = e.range;
  const row = e.range.getRow();
  const col = e.range.getColumn();
  const as = e.source.getActiveSheet();
  const secondSheet = e.source.getSheetByName("Sheet2");
  if(as.getName() == "Sheet1" && col == 2 && row > 12 ) {
    // This works fine, and sets the value on the Sheet2 correctly.
    secondSheet.getRange('E3').setValue(cell.getValue());
    // This does not work to change the UI to the second sheet
    e.source.setActiveSheet(secondSheet);
    // Nor this
    as.setActiveSheet(secondSheet);
  }
}

Is it possible to change the active sheet in the UI from within the onSelectionChange(e) function? I have successfully used setActiveSheet in other functions to change the active sheet, and it works fine.

CodePudding user response:

This works for me

function onSelectionChange(e) { 
  //Logger.log(e);
  const cell = e.range;
  const row = e.range.getRow();
  const col = e.range.getColumn();
  const as = e.source.getActiveSheet();
  const secondSheet = e.source.getSheetByName("Sheet2");
  if(as.getName() == "Sheet1" && col == 2 && row > 12 ) {
    secondSheet.getRange('E3').setValue(cell.getValue());
    e.source.setActiveSheet(secondSheet);
  }
}
  • Related