Google表单脚本中的TypeError

时间:2014-10-23 05:21:04

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

在Google表单脚本编辑器中,我使用下面的代码在电子表格中插入带有表单数据的编辑响应链接。

    function assignEditUrls() {
  var form = FormApp.openById('1bAXKuBKQny9CLU3WOK4xxxxxxxxxxxxxxxxxxxxxxxxxxxx');
    //enter form ID here

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form Responses');

    //Change the sheet name as appropriate
  var data = sheet.getDataRange().getValues();
  var urlCol = 7; // column number where URL's should be populated; A = 1, B = 2 etc
  var responses = form.getResponses();
  var timestamps = [], urls = [], resultUrls = [];

  for (var i = 0; i < responses.length; i++) {
    timestamps.push(responses[i].getTimestamp().setMilliseconds(0));
    urls.push(responses[i].getEditResponseUrl());
  }
  for (var j = 1; j < data.length; j++) {

    resultUrls.push([data[j][0]?urls[timestamps.indexOf(data[j][0].setMilliseconds(0))]:'']);
  }
  sheet.getRange(2, urlCol, resultUrls.length).setValues(resultUrls);  
}

但是当我运行这个脚本时,它会显示如下错误

TypeError: Cannot call method "getSheetByName" of null. (line 5, file "Code")Dismiss

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

此脚本按ID打开表单,并希望响应表位于包含脚本的电子表格中。因此,您有两个选择:

  • 在收集回复的Google电子表格的脚本编辑器中添加代码,而不是在表单编辑器中。

  • 或者,open the Spreadsheet by ID

      var sheet = SpreadsheetApp.openByID(###SHEET-ID###)
                                .getSheetByName('Form Responses');
    

    或更好,正如Serge建议的那样:

      var sheet = SpreadsheetApp.openByID(form.getDestinationId())
                                .getSheetByName('Form Responses');
    

说明:错误消息指示您尝试方法getSheetByName()的对象是null对象。该对象来自SpreadsheetApp.getActiveSpreadsheet()。该方法仅适用于Spreadsheet绑定脚本。