求Google Apps Script代码:空单元格可输入并锁定,非空单元格拒绝输入
Google Apps Script 实现单元格输入限制与自动锁定
以下是可直接使用的脚本,实现仅允许空单元格输入数据,输入完成后自动锁定单元格;若尝试修改非空单元格则撤销操作并提示:
function onEdit(e) { const range = e.range; const sheet = range.getSheet(); // 如需限制仅特定区域生效,取消下方注释并修改范围(示例为A2到Z1000) // const allowedRange = sheet.getRange("A2:Z1000"); // if (!range.intersects(allowedRange)) return; // 检查单元格原本是否已有内容 const oldValue = e.oldValue; if (oldValue !== undefined && oldValue !== "") { // 撤销输入并弹出提示 range.setValue(oldValue); SpreadsheetApp.getUi().alert("该单元格已有内容,不允许修改!"); return; } // 输入完成后锁定当前单元格 const protection = sheet.protect(); protection.setDescription("自动锁定单元格"); // 获取当前表格所有未保护的区域 const unprotectedRanges = protection.getUnprotectedRanges(); // 将当前单元格从可编辑区域移除(实现锁定) const updatedUnprotected = unprotectedRanges.filter(r => r.getA1Notation() !== range.getA1Notation()); protection.setUnprotectedRanges(updatedUnprotected); // 仅允许当前用户修改保护设置(防止其他用户解锁) protection.addEditor(SpreadsheetApp.getActiveUser()); protection.removeEditors(protection.getEditors().filter(editor => editor !== SpreadsheetApp.getActiveUser())); if (protection.canDomainEdit()) { protection.setDomainEdit(false); } }
设置步骤
- 打开目标Google表格,点击顶部菜单栏「扩展程序」→「Apps脚本」
- 删除默认的
myFunction代码,粘贴上面的脚本,点击「保存」(给项目起任意名称,比如CellLockTool) - 首次运行需要授权:点击Apps脚本界面的「运行」按钮,按提示完成权限授予(属于官方安全授权,可放心操作)
- 设置自动触发规则:在Apps脚本界面左侧点击「触发器」→「添加触发器」,按以下配置完成设置:
- 选择要运行的函数:
onEdit - 部署类型:
Head - 事件来源:
从电子表格 - 事件类型:
编辑时 - 点击「保存」
- 选择要运行的函数:
注意事项
- 运行脚本的账号必须拥有表格的编辑权限,否则无法添加单元格保护
- 如果只需要在特定区域生效,取消代码中对应注释并修改范围即可
- 测试时,空单元格输入内容后会自动锁定;尝试修改已有内容的单元格会被撤销操作并弹出提示
内容的提问来源于stack exchange,提问作者Raja Abdul Sami
相关产品推荐
相关产品推荐

