Google spreadsheet “Cannot call method ”getRange“

2020-02-07 11:03发布

问题:

I'd like to generate a unique ID in column A if column B has changed in every row from the 6th. It would be enough to use a number from 1 to X as ID but it should no change after moving de row. Yet I'm getting an error continuously "Cannot call method "getRange" of null."

function onEdit() {
 var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('ScriptTest');
 var column0 = sheet.getRange(6, 2, sheet.getLastRow()-6, 1);
 var oValues = column0.getValues();

 if (oValues[sheet.getLastRow()][0] == '') {
   sheet.getRange(sheet.getLastRow(), 1, 1, 1).setValue(ContentService.createTextOutput(sheet.getLastRow()-6));
 }  
}

回答1:

When you have errors with working with sheet objects like here you can easily identify the source by the kind of missing value it's pulling from.

undefined is undefined, meaning the variable for the sheet was never given a value or has been set to undefined.

the variable is set to null when you are trying to get a tab by a name that doesn't exist, as is the case here.

Anything else probably means you are accessing the wrong variable.