如何在Google Sheets中编写自定义脚本实现列值自动增减与重置
Google Sheets 实现自动扣减/累加并清空输入列的脚本
操作步骤:
- 打开目标Google Sheets文档,点击顶部菜单栏的 工具 > 脚本编辑器
- 在脚本编辑器中,替换默认代码为以下内容:
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
相关产品推荐
相关产品推荐

