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

在Google Apps Script中,如何统计一行中非空白单元格的数量?

解决方法

首先要注意,sheet.getRange()的参数需要是字符串格式,所以要写成sheet.getRange("B2:2")。

getValues()返回的是二维数组(哪怕是单行,结构也是[[单元格1值, 单元格2值, ...]])。要过滤掉空白单元格,你需要先提取出单行的一维数组,再用filter处理:

方式1:使用命名函数

// 定义判断非空的函数
function notBlank(cell) {
  return cell !== "";
}

// 获取B2开始的整行,提取一维数组后过滤
const nonBlankValues = sheet.getRange("B2:2").getValues()[0].filter(notBlank);

方式2:使用内联箭头函数(更简洁)

const nonBlankValues = sheet.getRange("B2:2").getValues()[0].filter(cell => cell !== "");

如果需要同时过滤掉仅含空格的单元格,可以修改为:

const nonBlankValues = sheet.getRange("B2:2").getValues()[0].filter(cell => cell.trim() !== "");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 20:12:03