我正在嘗試使用 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;
})
}

uj5u.com熱心網友回復:
在您的情況下,以下示例腳本怎么樣?
示例腳本:
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 表單中。
在您的放映腳本中,
googleSheetsQuestionsofvar googleSheetsQuestions = getQuestionValues();始終是undefined. 根據您的目標,在這種情況下,我使用了一個物件來搜索問題的標題。
筆記:
- 在此示例腳本中,請再次確認 Google Form 的標題是否與每張表的“A1”的值相同。
參考:
- 減少()
- forEach()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/494436.html
