问题
I am trying to delete specific rows containing specific string "X".
function deleteRows() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('delete containing');
var r = s.getRange('A:A');
var v = r.getValues();
for(var i=v.length-1;i>=0;i--)
if(v[0,i]=='Substitution: ')
s.deleteRow(i+1);
};
But I am getting below error:
TypeError: Cannot call method "getRange of null.(line 4, file "Code").
Can Anybody help me resolving this error? Thank you
回答1:
From the documentation: getSheetByName() "Returns null if there is no sheet with the given name." So you need to handle that, see the inserted if block:
function deleteRows() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('delete containing');
if (s === null) {
ui = SpreadsheetApp.getUi();
ui.alert("No worksheet of that name"); // Note: displays in the worksheet GUI, not the scripts editor.
return false;
}
var r = s.getRange('A:A');
var v = r.getValues();
for(var i=v.length-1;i>=0;i--)
if(v[0,i]=='Substitution: ') // [sic] jshint kicking up a storm about this line!
s.deleteRow(i+1);
}
来源:https://stackoverflow.com/questions/54266510/typeerror-cannot-call-method-getrange-of-null-line-4-file-code