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

如何在Google Sheets中编写自定义脚本实现列值自动增减与重置

Google Sheets 实现自动扣减/累加并清空输入列的脚本

操作步骤:

  1. 打开目标Google Sheets文档,点击顶部菜单栏的 工具 > 脚本编辑器
  2. 在脚本编辑器中,替换默认代码为以下内容:
function onEdit(e) {
  const activeCell = e.range;
  const sheet = activeCell.getSheet();
  
  // 仅处理A列第2行及以下的单元格(若需包含A1,移除&& activeCell.getRow() > 1)
  if (activeCell.getColumn() === 1 && activeCell.getRow() > 1) {
    const inputValue = activeCell.getValue();
    
    // 验证输入为有效数值
    if (typeof inputValue === 'number' && !isNaN(inputValue)) {
      const bCell = sheet.getRange(activeCell.getRow(), 2);
      const cCell = sheet.getRange(activeCell.getRow(), 3);
      
      // 计算并更新B、C列值
      bCell.setValue(bCell.getValue() - inputValue);
      cCell.setValue(cCell.getValue() + inputValue);
      
      // 清空A列输入单元格
      activeCell.setValue('');
    }
  }
}

脚本说明:

  • 依赖Google Apps Script的onEdit内置触发器,表格编辑时自动触发
  • 仅响应A列的输入操作,避免误触发其他列的编辑
  • 仅对有效数值输入执行操作,防止非数值内容导致计算错误
  • 操作完成后自动清空当前A列的输入单元格,匹配需求场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 12:32:36