Christian
Christian

Reputation: 1

How can I resolve "Cannot read property 'getName' of null" Error?

This should be an easy fix. Google Sheets is throwing an error stating that it "Cannot read property 'getName' of null." This code has been working just fine up until now, so I'm unsure as to what broke it. Any input as to what is the err here would be very much appreciated! Hopefully, it isn't too tricky of a solution.

function updateSheet(sheetName, cellAddress) {
  //  var range = e.range; // range just edited
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  if (sheet.getName() !== sheetName) {
    return;
  }
  
  var date = new Date();
  date = Utilities.formatDate(date, "GMT-08:00", "MM/dd/yy");
  sheet.getRange(cellAddress).setValue("Last Edited: "+ date.toString());  
}

Upvotes: 0

Views: 3410

Answers (4)

Jason E.
Jason E.

Reputation: 1221

Your first condition seems to be unnecessary in this case. You used the sheetName to get the sheet and then you try to check if the name of the sheet you got is sheetName.

If you want to have a checker if your getSheetByName() returned a sheet, you can try this:

if(!sheet){
 return;
}

Upvotes: 1

Marios
Marios

Reputation: 27400

Issue:

According to the official documentation getSheetByName returns null if there is no sheet with the given name and this also the reason of your issue, because you are actually calling null.getName().

Solution:

Assuming you want to exit the function if the sheet with the name sheetName does not exist:

Replace:

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
if (sheet.getName() !== sheetName) {
    return;
}

with:

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
if (!sheet) {
    return;
}

Upvotes: 1

user9706
user9706

Reputation:

The obvious answer is SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName); returns null. The only argument is sheetName, so I am guessing the sheet was renamed or deleted.

Upvotes: 0

beartrap
beartrap

Reputation: 51

Try checking if the getName property even exist in the object

function updateSheet(sheetName, cellAddress) {
  //  var range = e.range; // range just edited
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  //Try checking if the getName property even exist in the object
  if (sheet.getName() && sheet.getName() !== sheetName) {
    return;
  }
  
  var date = new Date();
  date = Utilities.formatDate(date, "GMT-08:00", "MM/dd/yy");
  sheet.getRange(cellAddress).setValue("Last Edited: "+ date.toString());  
}

Upvotes: 0

Related Questions