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

如何让Google Apps Script仅在指定工作表编辑时触发并插入公式

问题原因

  • 你当前的代码没有在onEdit触发的第一时间做执行条件校验,无论编辑任意工作表的任意单元格,copyFormulas函数都会无条件执行,insertRow也仅校验了单元格位置、没校验所属工作表,因此会出现非目标场景下脚本触发的问题。

修复方案

在onEdit函数入口先判断触发编辑的工作表是否为Test、编辑位置是否为A2,不满足条件则直接终止脚本运行,修改后代码如下:

function onEdit(e) {
  // 触发条件校验:非Test表、非A2单元格编辑直接退出
  const editedSheet = e.range.getSheet();
  if (editedSheet.getName() !== "Test" || e.range.getA1Notation() !== "A2") {
    return;
  }

  insertRow();
  copyFormulas();

  function insertRow() {
    const sheet = SpreadsheetApp.getActive().getSheetByName("Test");
    sheet.insertRowBefore(2);
  }
  
  function copyFormulas() {
    SpreadsheetApp
    .getActive()
    .getSheetByName('Test')
    .getRange('C3')
    .setFormula("=SUM(A3*B3)");
  }
}

内容的提问来源于stack exchange,提问作者Francois le Roux

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:36:02