TypeError in Google Form script

三世轮回 提交于 2019-12-12 04:53:59

问题


In the Google form script editor, I'm using below code for insert Edit response link in the spreadsheet with form data.

    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);  
}

But when i run this script, it shows error like this

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

How can solve this?


回答1:


This script opens a Form by ID, and expects the response sheet to be in a spreadsheet the script is contained in. So you have two options:

  • Add the code inside the Script Editor of the Google Spreadsheet that is collecting the responses and not inside the Form editor.

  • Alternatively, open the Spreadsheet by ID.

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

    or better yet, as Serge suggests:

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

Explanation: The error message indicates that the object that you attempted method getSheetByName() on was a null object. That object was obtained from SpreadsheetApp.getActiveSpreadsheet(). That method is only applicable within Spreadsheet-bound scripts.



来源:https://stackoverflow.com/questions/26521772/typeerror-in-google-form-script

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