Skip to content

Diagnostic reference

Cannot read properties of undefined (reading 'getRange')

Fix Apps Script's undefined getRange error by checking getSheets() indexes, missing return statements, and unassigned sheet variables.

Updated November 26, 2026

Apps Script error

TypeError: Cannot read properties of undefined (reading 'getRange')

What it means

The variable before .getRange() holds undefined instead of a Sheet object. Unlike null from getSheetByName(), undefined comes from JavaScript itself. The usual causes are an index past the end of getSheets(), an uninitialized variable, a helper that forgets to return the sheet, or a function parameter left empty when you click Run.

Related error messages

  • TypeError: Cannot read properties of undefined (reading 'getDataRange')
  • TypeError: Cannot read properties of undefined (reading 'getLastRow')
  • TypeError: Cannot read properties of undefined (reading 'getSheetByName')

Before and after

The code before and after the fix.

Problem 0 changed lines
function readSecondTab() {
  const sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  const archive = sheets[2];
  return archive.getRange('A1:C10').getValues();
}
Fixed 3 changed lines
function readSecondTab() {
  const sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  const archive = sheets[2];
  if (!archive) {
    throw new Error('Expected at least 3 tabs, but found ' + sheets.length + '.');
  }
  return archive.getRange('A1:C10').getValues();
}

How to fix it

  • Open Executions, find the failing line, and trace where the sheet variable got its value.
  • Check array indexes carefully. getSheets() starts at 0, so sheets[2] is the third tab.
  • Use getSheetByName() with a null check when you want a named tab instead of a positional index.
  • If a helper looks up the sheet, confirm that every branch ends with return sheet.
  • If the sheet comes from a parameter, stop running that helper directly from the editor toolbar.

Things to check

  • If the error says null instead of undefined, getSheetByName() or getActiveSpreadsheet() returned null. Read the null getRange guide instead.
  • Decide whether a missing tab should throw an error or exit early.

In the Apps Script editor

Catch errors like this before clicking Run.

myFunction (published as Error Checker for Google Apps Script on the Chrome Web Store) checks your code while you edit at script.google.com. Diagnostics, autocomplete, and rule-based quick fixes are free without an account, run in your browser, and request no Google Drive, Gmail, or Apps Script project OAuth scopes.