Check if a Cell is Within a Range with Apps Script

To check if a cell is within a range of cells, use the inRange function provided on this page.

The function returns true if the cell is within the specified range of cells, or false otherwise.

Usage:

inRange(cell, cell_range)

Usage Example

First, copy and paste the inRange function into the script editor of your Google Sheets document:

function inRange(cell, range) {
  
  // Source : https://sheets-pratique.com/en/codes/in-range-function

  const cellRow = cell.getRow();
  const rangeRow1 = range.getRow();
  const rangeRow2 = range.getLastRow();

  if (cellRow > rangeRow2 || cellRow < rangeRow1) {
    return false;
  }

  const cellCol = cell.getColumn();
  const rangeCol1 = range.getColumn();
  const rangeCol2 = range.getLastColumn();

  if (cellCol > rangeCol2 || cellCol < rangeCol1) {
    return false;
  }

  return true;
}

You can then use this function, for example, to check if cell B1 is within the range A1:C3:

function example() {

  const sheet = SpreadsheetApp.getActiveSheet();
  const cell = sheet.getRange('B1');
  const range = sheet.getRange('A1:C3');

  const result = inRange(cell, range);

  console.log(result); // Returns: true
}

Condensed Function

For better understanding of the code in the previous example, the inRange function was not condensed.

Here is a much shorter equivalent version:

function inRange(cell, range) {
  // Source : https://sheets-pratique.com/en/codes/in-range-function
  const r = cell.getRow(), c = cell.getColumn();
  return r <= range.getLastRow() && r >= range.getRow() && c <= range.getLastColumn() && c >= range.getColumn();
}