Home > Software design >  How to check if sheet A and B are literally the same sheet?
How to check if sheet A and B are literally the same sheet?

Time:10-13

So I'm trying to optimize my sheets onEdit function by initially checking if the modified cells are even in the right sheet like this:

var spreadsheet1 = ss.getSheetByName("ONE")
var spreadsheet2 =  ss.getSheetByName("TWO")

function onEdit(e) {

  let range = e.range
  
  Logger.log("Starting onEdit")

  Logger.log("Range: "   range.getSheet().getSheetId().toString())
  Logger.log("spreadsheet1: "   spreadsheet1.getSheetId().toString())
  Logger.log("spreadsheet2: "   spreadsheet1.getSheetId().toString())

  Logger.log("Is spreadsheet1 :"   range.getSheet().getSheetId() == spreadsheet1.getSheetId())
  Logger.log("Is spreadsheet2:"   range.getSheet().getSheetId() == spreadsheet2.getSheetId())
  
  if (range.getSheet().getSheetId() == spreadsheet1.getSheetId() ||
      range.getSheet().getSheetId() == spreadsheet2.getSheetId())
  {
    do stuff
  }

The logs look like this:

Oct 12, 2021, 2:12:54 PM    Info    Starting onEdit
Oct 12, 2021, 2:12:54 PM    Info    Range: 78085800
Oct 12, 2021, 2:12:54 PM    Info    spreadsheet1: 78085800
Oct 12, 2021, 2:12:54 PM    Info    spreadsheet2: 514624715
Oct 12, 2021, 2:12:54 PM    Info    Is spreadhseet1: false
Oct 12, 2021, 2:12:54 PM    Info    Is spreadsheet2: false

One of the two conditions should return true and the if should be evaluated as true but for some reason it doesn't work!

CodePudding user response:

The problem is in your loggers. Currently, it's adding two strings together and comparing them to a third. So what's being compared looks something like this:

"Is spreadsheet1 :78085800" == "78085800"

This is obviously false, so all that's needed is to use parentheses to change the order of operations. Try updating the loggers to the following:

Logger.log("Is spreadsheet1: "   (range.getSheet().getSheetId() == spreadsheet1.getSheetId()))
Logger.log("Is spreadsheet2: "   (range.getSheet().getSheetId() == spreadsheet2.getSheetId()))
  • Related