如何通过AppsScript让非表格所有者在受保护单元格生成时间戳
解决方案
问题根源是你用的onEdit是简单触发器,它会以当前编辑用户的权限运行——受限用户没有受保护列的编辑权限,所以脚本无法写入时间戳。要解决这个问题,需要换成可安装触发器,它会以触发器创建者的权限运行,就能绕过用户的编辑限制,正常写入受保护列。
步骤1:修改脚本代码
替换原有的onEdit函数为以下代码,逻辑和原代码一致,但使用事件对象获取编辑信息,更适配可安装触发器:
function handleEdit(e) { const sheet = e.source.getActiveSheet(); const editedCol = e.range.getColumn(); // 处理Production Activity表 if (sheet.getName() === "Production Activity") { // 编辑第25列时,给第26列写时间戳 if (editedCol === 25) { const targetCell = e.range.offset(0, 1); if (targetCell.isBlank()) { targetCell.setValue(new Date()); } } // 编辑第27列时,给第28列写时间戳 if (editedCol === 27) { const targetCell = e.range.offset(0, 1); if (targetCell.isBlank()) { targetCell.setValue(new Date()); } } } // 处理Non-Production Activity表 if (sheet.getName() === "Non-Production Activity") { // 编辑第9列时,给第10列写时间戳 if (editedCol === 9) { const targetCell = e.range.offset(0, 1); if (targetCell.isBlank()) { targetCell.setValue(new Date()); } } // 编辑第11列时,给第12列写时间戳 if (editedCol === 11) { const targetCell = e.range.offset(0, 1); if (targetCell.isBlank()) { targetCell.setValue(new Date()); } } } }
步骤2:创建可安装触发器
- 打开Google表格的脚本编辑器(工具>脚本编辑器)
- 点击左侧菜单栏的「触发器」图标(时钟形状)
- 点击「添加触发器」按钮
- 按以下配置设置:
- 选择要运行的函数:
handleEdit - 选择部署类型:「头部部署」
- 选择事件源:「从电子表格」
- 选择事件类型:「编辑时」
- 选择要运行的函数:
- 点击保存,按提示完成授权(需要你拥有表格的编辑权限)
完成后,受限用户编辑指定列时,脚本会以你的权限自动写入受保护列的时间戳,无需移除单元格保护。
内容的提问来源于stack exchange,提问作者Somnath Banerjee
相关产品推荐
相关产品推荐

