Cell Address with Google Apps Script

Cell Address

The address of a cell can be obtained using getA1Notation:

function example() {
  
  const cell = SpreadsheetApp.getActiveSheet().getRange(2, 4);
  const address = cell.getA1Notation();
  
  console.log(address); // Displays: D2
}

Range of Cells Address

The method getA1Notation can also return the address of a range of cells:

function example() {
  
  const range = SpreadsheetApp.getActiveSheet().getRange(2, 2, 5, 10);
  const address = range.getA1Notation();
  
  console.log(address); // Displays: B2:K6
}

Comparing 2 Cells

To check if 2 cells in a sheet are the same (or not, as the case may be), you can compare their addresses:

function example() {
  
  const sheet = SpreadsheetApp.getActiveSheet();
  const cell = sheet.getRange(2, 4);
  const selectedCell = sheet.getActiveCell();
  
  // If it's the same cell
  if (cell.getA1Notation() == selectedCell.getA1Notation()) {
    console.log("It's the same cell!");
  }
}

In this case, the message is displayed only if the selected cell is the same as that of cell.