Google Sheets自定义函数报given_list不可迭代,如何传入数组参数?
Google Sheets自定义统计函数错误修复方案
错误核心原因
- Google Sheets中用
{}定义的数组传入自定义函数时,统一为二维数组格式:行数组{a,b}转为[[a,b]],列数组{a;b}转为[[a],[b]];如果{}内只有单个值,会直接被解析为标量(普通数值/字符串),不是数组类型,不支持迭代遍历。 - 原代码未做参数兼容处理,当传入的匹配列表为单个值时,就会触发
given_list is not iterable报错。
修复后的代码
function count_if_in_set(range, given_list) { let counter = 0; // 兼容标量、二维数组输入,统一转为一维数组 const flatMatchList = Array.isArray(given_list) ? given_list.flat(Infinity) : [given_list]; // 用Set做匹配,比多层循环效率更高 const matchSet = new Set(flatMatchList); // 遍历单元格区域统计 for (let row of range) { for (let cellValue of row) { if (matchSet.has(cellValue)) { counter++; } } } return counter; }
调用说明
- 匹配单个值时直接传值即可,无需用
{}包裹:=count_if_in_set(Z30:Z33, 1),你的测试用例调用该公式会返回结果1,符合预期。 - 匹配多个值时用
{}定义数组即可,比如匹配1和3:=count_if_in_set(Z30:Z33, {1,3}),会返回结果3。
内容的提问来源于stack exchange,提问作者Maxijazz
相关产品推荐
相关产品推荐

