谷歌表格:勾选Col6复选框锁定行,现有脚本无法实现全员锁定
修复谷歌表格复选框锁定/解锁行脚本
原脚本问题排查
你的现有脚本存在3个关键疏漏:
- 仅实现了复选框勾选时的锁定逻辑,完全缺失取消勾选时的解锁处理
- 未移除文档所有者的编辑权限(
getEditors()返回的列表不包含所有者,导致所有者仍能编辑锁定行) - 每次触发都会创建新的行保护,重复保护会导致权限逻辑混乱
修复后的完整脚本
function onEdit(e) { const sh = e.source.getActiveSheet(); const targetRange = e.range; // 仅处理第6列(Col6)的复选框操作 if (targetRange.columnStart !== 6) return; const targetRow = targetRange.rowStart; const isChecked = e.value === "TRUE"; // 复选框勾选状态判断 const rowRange = sh.getRange(targetRow, 1, 1, sh.getMaxColumns()); if (isChecked) { // 勾选时:创建行保护并禁用所有用户编辑权限(包括所有者) const protection = rowRange.protect(); // 移除所有可编辑协作者 protection.removeEditors(protection.getEditors()); // 移除文档所有者的编辑权限 const ownerEmail = SpreadsheetApp.getActiveSpreadsheet().getOwner().getEmail(); if (protection.getEditors().includes(ownerEmail)) { protection.removeEditor(ownerEmail); } // 禁用域内编辑权限(如果适用) if (protection.canDomainEdit()) { protection.setDomainEdit(false); } // 设置保护描述,方便识别 protection.setDescription(`Locked row ${targetRow}`); } else { // 取消勾选时:删除该行的所有保护 const protections = sh.getProtections(SpreadsheetApp.ProtectionType.RANGE); protections.forEach(protection => { const protectedRange = protection.getRange(); if (protectedRange.getRow() === targetRow && protectedRange.getNumRows() === 1) { protection.remove(); } }); } }
关键修复说明
- 双向逻辑处理:同时实现勾选锁定、取消勾选解锁的完整流程
- 所有者权限限制:主动获取文档所有者邮箱并移除其编辑权限,确保包括所有者在内的所有用户都无法编辑锁定行
- 避免重复保护:解锁时遍历并删除对应行的所有范围保护,解决重复保护的冲突问题
- 权限严谨性:禁用域内编辑权限,进一步确保无额外编辑通道
注意事项
由于简单触发器(默认onEdit)的权限限制,无法修改文档所有者的权限,因此你需要设置可安装的onEdit触发器:
- 打开谷歌表格的脚本编辑器
- 点击左侧「触发器」图标 → 「添加触发器」
- 选择函数为
onEdit,事件类型为「从电子表格提交」,事件源为「编辑时」 - 保存并授权所需权限
内容的提问来源于stack exchange,提问作者Vicki Allan
相关产品推荐
相关产品推荐

