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

如何在Google Sheet中实现函数自动计算上方至前一个函数的区间值

Google Sheet 分段累加自定义函数实现

实现效果如下:
效果示例图

操作步骤

1. 导入自定义函数

打开目标Google Sheet,点击顶部菜单栏 扩展程序 > Apps 脚本,清空编辑器内的默认代码,粘贴如下代码:

function SUM_ABOVE() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet();
  const currentCell = sheet.getActiveCell();
  const columnNum = currentCell.getColumn();
  const currentRowNum = currentCell.getRow();

  // 从当前单元格上一行向上遍历查找上一个同类函数
  for (let row = currentRowNum - 1; row >= 1; row--) {
    const checkCell = sheet.getRange(row, columnNum);
    const cellFormula = checkCell.getFormula();
    if (cellFormula.includes("SUM_ABOVE")) {
      // 计算两个同类函数中间的单元格总和
      const calcRange = sheet.getRange(row + 1, columnNum, currentRowNum - row - 1, 1);
      return calcRange.getValues().flat().reduce((sum, val) => sum + (Number(val) || 0), 0);
    }
  }

  // 未找到同类函数则从第一行开始累加
  const fullRange = sheet.getRange(1, columnNum, currentRowNum - 1, 1);
  return fullRange.getValues().flat().reduce((sum, val) => sum + (Number(val) || 0), 0);
}

点击编辑器顶部保存按钮,自定义项目名称(如「分段求和工具」),按照页面提示完成脚本授权即可。

2. 使用方法

回到表格页面,在需要分段求和的单元格直接输入公式 =SUM_ABOVE() 即可。公式会自动向上累加所有数值单元格,直到遇到上一个使用SUM_ABOVE()的单元格停止。
你可以直接复制该公式到任意行的单元格,都会自动适配当前列的计算逻辑,不需要手动修改参数。

常见问题

  • 首次使用出现「Google未验证此应用」提示:点击弹窗的「高级」>「前往[你设置的项目名称]」即可继续完成授权,属于自定义脚本的正常提示
  • 修改上方数值后结果未更新:刷新页面即可同步结果,也可以在Apps脚本的触发式设置里添加定时刷新规则,实现自动更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:36:01