Apps Script报Header not defined错误,谷歌表单联动谷歌表格生成下拉列表如何修复
错误原因与修复方案
核心错误点
- 第6行调用的
header变量没有提前声明赋值,是触发「Header not defined」报错的直接原因 - 第4行
getDisplayValue()为错误写法,该方法仅能返回单个单元格的值,获取整表所有单元格的显示值需要使用复数方法getDisplayValues(),否则后续的数组遍历、map操作都会报错
修复后的完整代码
function getDataFromGoogleSheets() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const sheet = ss.getSheetByName("CompanyName"); // 修正为复数方法getDisplayValues,返回整表二维数组 const data = sheet.getDataRange().getDisplayValues(); const choices = {} // 新增header定义,取数据表第一行作为表头 const header = data.shift(); header.forEach(function(title,index){ choices[title] = data.map(row=>row[index]).filter(e=>e!=""); }); return choices; } function populateGoogleForms(){ // 替换为你自己的Google Form ID const GOOGLE_FORM_ID = "1H80nNJXb3hekZp7CZOZ0FGNpEwCiQnpHL17y3w8WSNk"; const googleForm = FormApp.openById(GOOGLE_FORM_ID); const items = googleForm.getItems(); const choices = getDataFromGoogleSheets(); items.forEach(function(item){ const itemTitle = item.getTitle(); if(itemTitle in choices) { const itemType = item.getType(); switch (itemType){ case FormApp.ItemType.LIST: item.asListItem().setChoiceValues(choices[itemTitle]); break; default: Logger.log("ignore question", itemTitle) } } }); }
使用注意事项
- 确保Google Sheet中名为
CompanyName的工作表第一行是表头,表头名称必须和Google Form中对应下拉题目的标题完全一致才能匹配成功 - 运行脚本前需要根据你自己的Google Form ID替换
populateGoogleForms函数中的GOOGLE_FORM_ID变量值 - 首次运行需要按照提示授予脚本访问Google Sheet和Google Form的权限
内容的提问来源于stack exchange,提问作者Sushant Kumar
相关产品推荐
相关产品推荐

