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

如何合并两个Google Sheet宏脚本实现插入空行与锁定行功能

合并后的Google Sheet脚本

把两个onEdit触发器合并成一个即可解决冲突问题,以下是整合后的完整代码:

function onEdit(e) {
  // 获取当前编辑的工作表、范围及关键参数
  const sheet = e.source.getActiveSheet();
  const range = e.range;
  const editedRow = range.getRow();
  const editedValue = e.value;
  const editedCol = range.columnStart;

  // 插入空白行逻辑:第3行单元格设为TRUE时,在其上方插入新行
  if (editedRow === 3 && editedValue === "TRUE") {
    sheet.insertRowBefore(3);
  }

  // 锁定行逻辑:编辑第4列时,锁定当前整行
  if (editedCol === 4) {
    const rowProtection = sheet.getRange(editedRow, 1, 1, sheet.getMaxColumns()).protect();
    // 移除所有协作者的编辑权限
    rowProtection.removeEditors(rowProtection.getEditors());
    // 关闭域级编辑权限(若存在)
    if (rowProtection.canDomainEdit()) {
      rowProtection.setDomainEdit(false);
    }
    // 保留脚本所有者的编辑权限(避免自己被锁)
    rowProtection.addEditor(Session.getEffectiveUser());
  }
}

关键说明

  • 整合后两个功能独立触发:满足插入行条件时执行插入,满足锁定行条件时执行锁定,互不影响。
  • 新增了rowProtection.addEditor(Session.getEffectiveUser()),确保脚本的创建者不会被自己的脚本锁死,这个步骤可根据需求选择保留或删除。
  • 统一获取变量减少重复API调用,提升脚本运行效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 03:15:50