【问题标题】:Google Apps Script error: Cannot read property 'appendRow' of nullGoogle Apps 脚本错误:无法读取 null 的属性“appendRow”
【发布时间】:2021-03-17 23:16:03
【问题描述】:

Google Apps 脚本不断给我错误:

TypeError:无法读取 null 的属性“appendRow”
AddRecord@Code.gs:4

代码:

function AddRecord() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var mainSheet = ss.getSheetByName("MAIN");
  mainSheet.appendRow(["purple", new Date()]);
}

如何解决?

【问题讨论】:

  • 那么 mainSheet 可能是未定义的。 MAIN 工作表名称中是否有空格

标签: forms google-apps-script google-sheets


【解决方案1】:

以下功能将避免不必要的活动电子表格和潜在错误:

//replace: 
var ss = SpreadsheetApp.getActiveSpreadsheet();

//by: 
var ss = SpreadsheetApp.openById('xxxxx'); 
// you will find the ID in the URL of the sheet, between "spreadsheets/d/" and "/edit"

如果仍有问题,问题必须来自工作表名称,正如@Cooper 已经告诉你的那样;)

【讨论】:

    【解决方案2】:

    根据文档:

    如果没有具有给定名称的工作表,getSheetByName(name) 返回 null,如果在电子表格中找到工作表名称,则返回 Sheet

    有 2 个可能的原因导致 null 值:

    1. 名为MAIN 的工作表不存在。
    2. 工作表名称中有印刷错误。

    您可以通过添加名为 MAIN 的工作表或将工作表重命名为 MAIN 以删除任何多余的字符来解决此问题。

    参考资料:

    【讨论】:

      【解决方案3】:

      在您正在使用的文件中,工作表可能未称为 MAIN。

      我遇到了类似的问题。如果您之前没有编辑过工作表,请尝试以下操作:

      var mainSheet = ss.getSheetByName("Sheet1");

      替换这个:

      var mainSheet = ss.getSheetByName("MAIN");

      这将引用文件中的特定工作表,然后它应该可以正常执行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多