如何实现Google Sheets单元格编辑后保护、清空后自动取消保护?
Google Sheets 编辑后自动保护/清空后取消保护脚本修改方案
修改后完整代码
function onEdit(e) { const range = e.range; const newValue = e.value; // 单元格被清空时,移除对应保护 if (newValue === "") { const protections = range.getProtections(SpreadsheetApp.ProtectionType.RANGE); protections.forEach(protection => { if (protection.canEdit()) { protection.remove(); } }); return; } // 单元格有内容时,设置/更新保护 let protection = range.getProtections(SpreadsheetApp.ProtectionType.RANGE)[0]; if (!protection) { protection = range.protect(); } protection.removeEditors(protection.getEditors()); if (protection.canDomainEdit()) { protection.setDomainEdit(false); } }
关键改动说明
- 新增空值判断逻辑:通过
e.value获取编辑后的单元格内容,当值为空时触发保护移除流程 - 移除保护处理:调用
getProtections获取当前单元格的所有范围保护,遍历并移除(需确保当前脚本有权限编辑保护) - 避免重复创建保护:设置保护前先检查单元格是否已有保护,仅在无保护时创建新的,避免冗余保护条目
- 保留原有保护权限设置:维持原代码中移除所有编辑者、关闭域编辑权限的逻辑,确保保护生效
内容的提问来源于stack exchange,提问作者melontyme
相关产品推荐
相关产品推荐

