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

Google Sheets脚本:复制特定值单元格无法触发行锁定求助

Google Sheets脚本适配复制「🔒lock」单元格的解决方案

原脚本仅能在手动输入「🔒lock」时锁定对应行,但复制该单元格到多行时无法触发锁定逻辑,以下是修复后的完整脚本及说明:

修复后的脚本

function onEdit(e) {
  const range = e.range;
  const sheet = range.getSheet();
  const userEmail = Session.getEffectiveUser();
  const startRow = range.getRow();
  const endRow = range.getLastRow();
  const col = range.getColumn();

  // 仅处理I列(第9列)、行号≥4的编辑操作
  if (col !== 9 || startRow < 4) return;

  // 遍历所有受影响的行(适配复制多行的场景)
  for (let currentRow = startRow; currentRow <= endRow; currentRow++) {
    const cell = sheet.getRange(currentRow, col);
    const value = cell.getValue();
    const lockDescription = `${currentRow} - protected`;

    // 先移除当前行已有的保护(如果存在)
    const allProtections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
    for (const protection of allProtections) {
      if (protection.getDescription() === lockDescription) {
        protection.remove();
      }
    }

    // 根据单元格值设置或取消保护
    if (value === "🔒lock") {
      // 锁定当前行的B列到末尾范围(可按需调整锁定列范围)
      const lockRange = sheet.getRange(`B${currentRow}:${currentRow}`);
      const protection = lockRange.protect().setDescription(lockDescription);
      
      // 移除所有编辑者,仅保留当前操作用户
      protection.removeEditors(protection.getEditors());
      protection.addEditor(userEmail);
      if (protection.canDomainEdit()) {
        protection.setDomainEdit(false);
      }
    } else if (value === null || value === "✅good" || value === "❌not good") {
      // 值为空白、✅good或❌not good时,确保该行保护已移除(上方已处理移除逻辑)
    }
  }

  SpreadsheetApp.flush();
}

核心改动说明

  • 遍历所有受影响行:原脚本仅处理编辑范围的起始行,现在循环覆盖所有被编辑的行,完美适配复制多行的场景
  • 直接读取单元格值:不再依赖e.value(复制操作时e.value仅返回第一个单元格内容),改为从每个单元格直接取值,确保每行值都被正确识别
  • 单行独立保护:为每行生成唯一的保护描述,保证锁定/解锁操作精准对应到目标行,避免混淆
  • 简化逻辑流程:先统一移除对应行的旧保护,再根据当前值决定是否添加新保护,避免重复保护或逻辑冲突

内容的提问来源于stack exchange,提问作者Nodirbek Khajiev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 17:42:45