Google Sheets每行仅勾选一个复选框及勾选后密码锁定单元格实现问询
Google Sheets 复选框互斥+自动锁定实现方案
1. E、F列单行复选框互斥功能实现
通过内置的Apps Script触发器即可实现,操作步骤如下:
- 打开目标表格,点击顶部菜单栏「扩展程序」->「Apps Script」进入脚本编辑器
- 清空编辑器内的默认代码,粘贴以下代码:
function onEdit(e) { const sheet = e.source.getActiveSheet(); const editRange = e.range; // 仅响应E、F列(列号对应5、6)的勾选操作 if (editRange.columnStart < 5 || editRange.columnStart > 6 || editRange.getValue() !== true) return; const targetRow = editRange.rowStart; const anotherCol = editRange.columnStart === 5 ? 6 : 5; // 同行另一列复选框自动设为未勾选 sheet.getRange(targetRow, anotherCol).setValue(false); }
- 自定义项目名称后保存,按页面提示完成脚本访问表格的权限授权即可。后续E、F列每行仅可勾选一个复选框,勾选其中一个后另一个会自动取消。
2. 复选框勾选后自动锁定+密码解锁功能实现
在上述脚本基础上扩展代码即可完成,具体操作:
- 回到Apps Script编辑器,将原有代码替换为以下完整代码,将代码中
'自定义解锁密码'替换为你自己设置的密码:
// 替换为你自定义的解锁密码 const UNLOCK_PASSWORD = '自定义解锁密码'; // 复选框互斥+自动锁定逻辑 function onEdit(e) { const sheet = e.source.getActiveSheet(); const editRange = e.range; if (editRange.columnStart >= 5 && editRange.columnStart <= 6 && editRange.getValue() === true) { const targetRow = editRange.rowStart; const anotherCol = editRange.columnStart === 5 ? 6 : 5; sheet.getRange(targetRow, anotherCol).setValue(false); // 给当前勾选的单元格添加保护,锁定编辑权限 const cellProtection = editRange.protect().setDescription('复选框锁定'); const allEditors = cellProtection.getEditors(); cellProtection.removeEditors(allEditors); } } // 密码解锁逻辑 function unlockCell() { const ui = SpreadsheetApp.getUi(); const pwdInput = ui.prompt('请输入解锁密码', ui.ButtonSet.OK_CANCEL); if (pwdInput.getSelectedButton() !== ui.Button.OK) return; if (pwdInput.getResponseText() !== UNLOCK_PASSWORD) { ui.alert('密码错误,无法解锁'); return; } const selectedRange = SpreadsheetApp.getActiveRange(); const protections = selectedRange.getProtections(SpreadsheetApp.ProtectionType.RANGE); if (protections.length === 0) { ui.alert('当前单元格未被锁定'); return; } protections.forEach(item => item.remove()); ui.alert('解锁成功,可正常编辑单元格'); } // 表格顶部新增自定义功能菜单 function onOpen() { const ui = SpreadsheetApp.getUi(); ui.createMenu('自定义工具') .addItem('解锁选中单元格', 'unlockCell') .addToUi(); }
- 保存代码后刷新Google Sheets页面,等待数秒后顶部菜单栏会出现「自定义工具」菜单。后续只要勾选E、F列的复选框,对应单元格就会自动锁定,仅可通过选中目标单元格后点击「自定义工具」->「解锁选中单元格」,输入预设密码完成解锁。
内容的提问来源于stack exchange,提问作者General DDay
相关产品推荐
相关产品推荐

