0

NOTE: This is a proposal of canonical Q/A. Please discuss it on Meta

As a new Google Apps Script user, I'm struggling about how to fix this error

This happen when using the default runtime

TypeError: Cannot read property 'getRange' of null

This happen when using the old runtime

TypeError: Cannot call method "getRange" of null.

Bounded project

function myFunction(){
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = spreadsheet.getSheetByName('my sheet');
  sheet.getRange('A1');
}

Standalone project

function myFunction(){
  const spreadsheet = SpreadsheetApp.openByUrl('put_here_a_spreadsheet_url');
  const sheet = spreadsheet.getSheetByName('my sheet');
  sheet.getRange('A1');
}

Using getActiveSpredsheet() and getRange directly from the spreadsheet variable

function myFunction(){
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  spreadsheet.getRange('A1');
}
0

1 Answer 1

0

The error occurs because the spreadsheet hasn't a sheet named my sheet. Please bear in mind that the getSheetByName parameter should be exactly the same as the sheet name:

  • Same number of characters
  • Same casing (uppercase / lowercase)
  • The characters not only should look the same way, they should be the same i.e. a space looks similar to the human eye as a non-breaking-space but for the computers they aren't the same.

You might try typing the sheet name again both on the Google Sheets UI and on the Google Apps Script editor, or copy the name from one place and paste it into the other.

NOTE: You could use a variable name or put the sheet name directly inside the parenthesis. If you go for putting the sheet name inside the parenthesis it should be enclosed between ' (apostrophe / straight single quote), " (straight double quote) or ` (grave accent / backtick).

The same error might happen when using getActiveSpreadsheet() or getActiveSheet() there is no active spreadsheet or active sheet respectively. This usually happen when using these methods on stand-alone projects. In these cases, first you have to open the spreadsheet by using one of the following SpreadsheetApp methods open(file), openById(id), openByUrl(url), then you might use .activate() before getActiveSpreadsheet() / getActiveSheet() methods.

Resources

Related (from oldest to newest)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.