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

指定Sheet仍报错:Google Apps Script工作表选择异常问题

问题分析与解决方案

你的错误根源有两个:

  • 未绑定指定工作表获取范围:代码中ss.getRange("A36:A104")没有关联你定义的WTO_sheet,会默认使用当前活跃的工作表。当选中其他工作表时,这个范围可能来自非目标表,导致获取的值全为空,过滤后WTO_countries变成空数组。
  • 空数组传入setChoiceValues:Google Forms的setChoiceValues不接受空数组,当WTO_countries为空时会直接抛出Array is empty: values错误。

修改后的代码

function WTOUpdate() {
    const WTO_list = form.getItemById('18116013').asListItem();
    let WTO_countries = [];
    const WTO_sheet = ss.getSheetByName('UNGA Countries');
    
    // 绑定指定工作表获取范围,避免使用当前活跃表
    const WTOCountries = WTO_sheet.getRange("A36:A104").getValues();
    
    for (let i = 0; i < WTOCountries.length; i++) {
      if (WTOCountries[i][0] !== '') {
        WTO_countries.push(WTOCountries[i][0])
      }
    }
    
    // 处理空数组情况,避免抛出错误
    if (WTO_countries.length > 0) {
      WTO_list.setChoiceValues(WTO_countries);
    } else {
      // 可选:设置默认选项或提示,比如添加一个占位选项
      WTO_list.setChoiceValues(['无可用国家']);
    }
}

额外优化建议

  • 用let/const替代未声明的i(原代码中i是全局变量,可能引发意外问题)。
  • 如果ss是全局变量,确保它已正确初始化(比如const ss = SpreadsheetApp.getActiveSpreadsheet();),避免未定义错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:19:01