Google Sheets需求:状态为Done时锁定行并记录时间戳与用户信息
Google Sheets 自动锁定已完成行并记录操作信息方案
实现步骤
1. 打开脚本编辑器
打开目标Google Sheets表格,点击顶部菜单栏「扩展程序」>「Apps 脚本」,进入脚本编辑界面。
2. 替换脚本代码
清空编辑器默认代码,粘贴以下完整脚本:
function onEdit(e) { const sheet = e.source.getActiveSheet(); const range = e.range; const col = range.getColumn(); const row = range.getRow(); // 仅处理G列(第7列)的编辑,跳过表头行(假设表头为第1行,可按需修改) if (col !== 7 || row <= 1) return; const status = range.getValue().toString().toLowerCase(); if (status === 'done') { // 写入时间戳到H列 sheet.getRange(row, 8).setValue(new Date()); // 写入操作人邮箱到I列 sheet.getRange(row, 9).setValue(Session.getActiveUser().getEmail()); // 锁定当前整行 const rowRange = sheet.getRange(row, 1, 1, sheet.getLastColumn()); const protection = rowRange.protect(); // 移除所有默认编辑者,仅保留操作人和表格所有者 const editors = protection.getEditors(); editors.forEach(editor => protection.removeEditor(editor)); protection.addEditor(Session.getActiveUser()); protection.addEditor(sheet.getOwner()); // 设置保护备注 protection.setDescription(`已锁定:由${Session.getActiveUser().getEmail()}标记为完成`); } else { // 若状态改为非done,自动移除该行保护(可选逻辑,可按需删除) const existingProtection = sheet.getRange(row, 1, 1, sheet.getLastColumn()).getProtection(); if (existingProtection && existingProtection.canEdit()) { existingProtection.remove(); } } }
3. 设置可安装触发器
简单触发器权限不足,需手动添加可安装触发器:
- 在脚本编辑器左侧点击「触发器」图标(时钟形状);
- 点击「添加触发器」按钮;
- 配置参数:
- 选择函数:
onEdit - 选择事件源:「从电子表格」
- 选择事件类型:「编辑时」
- 选择函数:
- 点击「保存」,按提示完成授权流程。
关键说明
- 表头行适配:脚本中
row <=1假设表头在第1行,若你的表头在其他行,修改对应数字即可; - 操作人信息:
Session.getActiveUser().getEmail()获取当前编辑用户的邮箱,若需显示姓名,可替换为Session.getActiveUser().getName(); - 保护逻辑:脚本仅允许操作人和表格所有者编辑锁定行,可根据需求调整
addEditor部分的用户范围; - 非done状态处理:脚本包含移除保护的逻辑,若不需要该功能,删除
else块内的代码即可。
内容的提问来源于stack exchange,提问作者Imitiazuddin Mohammed
相关产品推荐
相关产品推荐

