Google Sheets App Script实现勾选触发行锁定及解锁需求
Google表格自动锁定/解锁行脚本实现
实现逻辑
通过onEdit触发器监听AB列复选框的状态变化:
- 复选框勾选时,为对应行的A至AF列添加保护范围,仅表格所有者和指定用户(你)拥有编辑权限
- 复选框取消勾选时,移除该行的保护范围,恢复全员编辑权限
完整脚本代码
function onEdit(e) { const activeSheet = e.source.getActiveSheet(); const editedRange = e.range; // 仅处理AB列(第28列)的单个单元格编辑 if (editedRange.getColumn() !== 28 || editedRange.getNumRows() !== 1 || editedRange.getNumColumns() !== 1) { return; } const targetRow = editedRange.getRow(); // 锁定范围:当前行的A列到AF列(AF是第32列) const lockRange = activeSheet.getRange(targetRow, 1, 1, 32); const ownerEmail = e.source.getOwner().getEmail(); // 替换成你的邮箱,确保你能编辑锁定的行 const allowedEditors = [ownerEmail, 'your-email@example.com']; if (e.value === 'TRUE') { // 勾选复选框:添加行保护 const rowProtection = lockRange.protect().setDescription(`Locked row ${targetRow}`); // 移除所有非授权编辑器 const currentEditors = rowProtection.getEditors(); currentEditors.forEach(editor => { if (!allowedEditors.includes(editor.getEmail())) { rowProtection.removeEditor(editor); } }); // 确保所有者在授权列表中(冗余保障) if (!rowProtection.getEditors().some(editor => editor.getEmail() === ownerEmail)) { rowProtection.addEditor(ownerEmail); } // 设置为强制锁定(非仅警告) rowProtection.setWarningOnly(false); } else { // 取消勾选:移除对应行的保护 const sheetProtections = activeSheet.getProtections(SpreadsheetApp.ProtectionType.RANGE); sheetProtections.forEach(protection => { const protectedRange = protection.getRange(); // 匹配当前行的A-AF列保护范围 if (protectedRange.getRow() === targetRow && protectedRange.getColumn() === 1 && protectedRange.getNumColumns() === 32) { protection.remove(); } }); } }
使用步骤
- 打开目标Google表格,点击顶部菜单栏「扩展程序」→「Apps脚本」
- 删除编辑器中的默认代码,粘贴上述脚本
- 将脚本中的
'your-email@example.com'替换为你自己的邮箱地址 - 点击脚本编辑器顶部的「保存」按钮,给脚本命名(比如
RowLockManager) - 关闭脚本编辑器,返回表格即可生效
注意事项
- 首次触发脚本时,会弹出权限授权提示,按照指引完成授权即可
- 确保AB列的单元格已设置为复选框格式:选中AB列→「数据」→「数据验证」→选择「复选框」
- 若需仅对特定工作表生效,可在脚本开头添加判断:
if (activeSheet.getName() !== '你的工作表名称') return;
内容的提问来源于stack exchange,提问作者BatHen Hazut
相关产品推荐
相关产品推荐

