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

Google Apps Script设置Google Forms动态下拉选项带跳转逻辑问题求解

问题原因
  • Range.getValues() 方法返回的是二维数组,格式为 [[行1列1值], [行2列1值], [行3列1值]],你直接将整个二维数组传入createChoice方法时,JavaScript会自动将数组转为逗号拼接的字符串,因此所有位置/物料会合并为单条选项。
解决方案

你不需要在setChoices内写循环,只要提前构建完整的选项数组再传入即可,修改后代码如下:

function updateForm() {
  // 注意补全你代码缺失的初始化逻辑,示例如下:
  // var form = FormApp.openById('你的表单ID');
  // var spreadsheet = SpreadsheetApp.openById('你的关联表格ID');
  // var tblLocations = spreadsheet.getSheetByName('位置存储表名');
  // var tblItems = spreadsheet.getSheetByName('物料存储表名');

  var locationForm = form.getItemById("413015265").asListItem();
  var equipmentForm = form.getItemById("2123556695").asListItem();
  var newLocation = form.getItemById('231469190').asPageBreakItem();
  var newItem = form.getItemById('90044295').asPageBreakItem();
  var gotoIssue = form.getItemById('1493817332').asPageBreakItem();
  var gotoLocation = form.getItemById('1425783734').asPageBreakItem();

  // 处理位置选项
  var locations = tblLocations.getRange(2,2,tblLocations.getLastRow()-1,1).getValues().flat().sort();
  var locationChoices = [
    locationForm.createChoice("** Add Location **", newLocation)
  ];
  locations.forEach(location => {
    if(location) { // 过滤表格空行
      locationChoices.push(locationForm.createChoice(location, gotoIssue));
    }
  });
  locationForm.setChoices(locationChoices);

  // 处理物料选项
  var items = tblItems.getRange(2,2,tblItems.getLastRow()-1,1).getValues().flat().sort();
  var itemChoices = [
    equipmentForm.createChoice("** Add Item **", newItem)
  ];
  items.forEach(item => {
    if(item) { // 过滤表格空行
      itemChoices.push(equipmentForm.createChoice(item, gotoLocation));
    }
  });
  equipmentForm.setChoices(itemChoices);
}
改动说明
  • 用flat()方法将getValues()返回的二维数组拍平为一维数组,直接拿到所有位置/物料的字符串值
  • 提前初始化选项数组,先加入固定的新增选项,再用forEach遍历所有数据,逐个生成选项加入数组
  • 增加空值过滤逻辑,避免表格空行生成空白选项
  • 完全适配动态增长需求:表格新增数据后,下次运行代码会自动读取新值加入下拉列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 17:36:02