TypeError in Google Form script

2019-09-05 13:13发布

问题:

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.