簡體   English   中英

如何使用 Apps 腳本使用來自不同 Google 表格選項卡的 A 列數據填充 Google 表單問題?

[英]How do I populate Google Form questions using column A data from different Google Sheets Tabs using Apps Script?

我正在嘗試使用 Apps 腳本從 Google Sheet 工作簿中填充 Google Form 問題。 我遇到的問題是表單沒有填充,並且我收到錯誤 TypeError: Cannot read property '0' of undefined specific on line googleSheetsQuestions[0]。 如何僅使用兩個表格中的 A 列值填充我的 Google 表單上的 2 個問題?

function openForm(e)
{
  populateQuestions();
}

function populateQuestions() {
  var form = FormApp.getActiveForm();
  var googleSheetsQuestions = getQuestionValues();
  var itemsArray = form.getItems();
  itemsArray.forEach(function(item){
    googleSheetsQuestions[0].forEach(function(header_value, header_index) {
      if(header_value == item.getTitle())
      {
        var choiceArray = [];
        for(j = 1; j < googleSheetsQuestions.length; j++)
        {
          (googleSheetsQuestions[j][header_index] != '') ? choiceArray.push(googleSheetsQuestions[j][header_index]) : null;
        }
        item.asCheckboxItem().setChoiceValues(choiceArray);
      }
    });     
  });
}

function getQuestionValues() {
var ss= SpreadsheetApp.openById('1234567890');
["Sheet1", "Sheet2"].forEach(function (s) {
    var questionSheet = ss.getSheetByName(s);
    var returnData = questionSheet.getDataRange().getValues();
    debugger;
    return returnData;
})
}

在此處輸入圖像描述 在此處輸入圖像描述 在此處輸入圖像描述

在您的情況下,以下示例腳本怎么樣?

示例腳本:

function populateQuestions() {
  // Retrieve values from Google Spreadsheet.
  var ss = SpreadsheetApp.openById('1234567890');
  var obj = ["Sheet1", "Sheet2"].reduce((o, s) => {
    var sheet = ss.getSheetByName(s);
    var [h, ...values] = sheet.getRange("A1:A" + sheet.getLastRow()).getValues();
    o[h] = values;
    return o;
  }, {});
  
  // Put values to the Google Form.
  var form = FormApp.getActiveForm();
  var itemsArray = form.getItems();
  itemsArray.forEach(e => {
    var item = e.asCheckboxItem();
    var title = item.getTitle();
    if (obj[title]) {
      item.setChoiceValues(obj[title]);
    }
  });
}
  • 運行此腳本時,將從 2 張 Google 電子表格中檢索值,並將檢索到的值放入 Google 表單中。

  • 在您的顯示腳本中, googleSheetsQuestions of var googleSheetsQuestions = getQuestionValues(); 總是undefined的。 根據您的目標,在這種情況下,我使用了一個對象來搜索問題的標題。

筆記:

  • 在此示例腳本中,請再次確認 Google Form 的標題是否與每張表的“A1”的值相同。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM