TypeError: Cannot call method “getRange” of null. (line 4, file “Code”

落爺英雄遲暮 提交于 2021-01-29 12:01:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!