You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多区域带下拉列表的Google Form从Google Sheet填充及报错排查

问题修复:Google Form下拉列表填充重复值报错及代码优化

核心问题与错误分析

  • 重复值报错:Google Form不允许下拉选项存在重复值,你的Sheet对应列中存在重复内容,导致调用setChoiceValues时触发报错。
  • 代码语法错误:
    • getDataFromGoogleSheets函数中,SpreadsheetApp.getActiveSpreadsheet(your text)写法错误,getActiveSpreadsheet不需要传入参数,直接调用即可。
    • populateGoogleForms函数里的GOOGLE_FORM_ID混入了无效字符your text,导致无法正确识别表单ID。
    • switch语句重复三次相同的FormApp.ItemType.LIST分支,属于冗余代码。

修复后的完整代码

// 从Sheet获取去重后的选项数据
function getDataFromGoogleSheets() {
  const ss = SpreadsheetApp.getActiveSpreadsheet(); // 修正:无需传参
  const sheet = ss.getSheetByName("FormList");
  const [hA, ...rows] = sheet.getDataRange().getDisplayValues();
  const cols = {};
  
  hA.forEach((h, i) => {
    // 提取列数据 → 过滤空值 → 去重
    const uniqueValues = [...new Set(rows.map(r => r[i]).filter(e => e))];
    cols[h] = uniqueValues;
  });
  
  return cols;
}

// 填充Google Form下拉列表
function populateGoogleForms() {
  // 修正:移除无效字符,使用正确的表单ID
  const GOOGLE_FORM_ID = "1cuPfuzzoEPEaIliiRKDqUvZ3dq4vawDPLERZYMUwpZQ";
  const googleForm = FormApp.openById(GOOGLE_FORM_ID);
  const items = googleForm.getItems();
  const choices = getDataFromGoogleSheets();

  items.forEach(function (item) {
    const itemTitle = item.getTitle();
    if (choices[itemTitle]) {
      const itemType = item.getType();
      switch (itemType) {
        case FormApp.ItemType.LIST:
          item.asListItem().setChoiceValues(choices[itemTitle]);
          break;
        default:
          Logger.log("忽略非下拉列表问题:", itemTitle);
      }
    }
  });
}

关键优化点说明

  1. 重复值处理:通过[...new Set(arr)]对Sheet拉取的列数据进行去重,确保传入Form的选项无重复。
  2. 代码精简:移除了冗余的col和idx变量(原代码中未使用),简化逻辑。
  3. 语法修正:修复了表单ID和Spreadsheet调用的错误写法。

使用注意事项

  • 确保Sheet中FormList工作表的表头文字与Google Form中下拉列表的标题文字完全一致(大小写、空格都要匹配)。
  • 若需要保留原数据的顺序,[...new Set(arr)]在大多数场景下可以保持顺序,若有特殊需求可改用其他去重方式。

内容的提问来源于stack exchange,提问作者VanoTate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 07:50:25