Google Sheets – How to Compare Two Range Objects

google sheets

I have two Range variables. How can I make sure that they belong to the same Sheet and reference the same set of cells?

For example:

var mySheet = // ...
function onEdit(e) {
  var range1 = e.range;
  var range2 = mySheet.getRange(123, 234);
  if (areEqual(range1, range2)) {
    // cell (123, 234) was edited,
    // let's do stuff
  }
}

What should I write instead of areEqual?

Best Answer

Instead of checking row, column, width and height, you can just compare the A1 notations (like A1:B2), in combination with something that identifies the sheet:

function areEqual(r1, r2) {
  return r1.getGridId() === r2.getGridId()
    && r1.getA1Notation() === r2.getA1Notation()
}

range.getGridId() uniquely identifies a sheet the range belongs to (within a spreadsheet).

See the documentation for the Range object, and the getA1Notation() and getGridId() in particular.


You can shorten it even further by just comparing range.getDataSourceUrl():

function areEqual(r1, r2) {
  return r1.getDataSourceUrl() === r2.getDataSourceUrl()
}