如何在谷歌表格复制的新工作表指定单元格添加锁定时间戳?
修改谷歌表格复制脚本:添加时间戳并保护指定单元格
以下是修改后的完整脚本,可实现复制工作表后在指定单元格添加时间戳,并将该单元格设置为禁止编辑:
function duplicateSheetWithProtections() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheetByName('MASTER'); var sheetName = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'dd/MM'); if (ss.getSheetByName(sheetName)) { console.log(`Same sheet name of "${sheetName}" is existing. Please confirm the sheet name again.`); return; } var sheet2 = sheet.copyTo(ss).setName(sheetName).activate(); var idx = ss.getSheets().findIndex(s => s.getSheetName() == "MASTER") + 2; ss.moveActiveSheet(idx); // 写入时间戳到指定单元格(此处为A1,可自行替换为目标单元格) var targetCell = sheet2.getRange("A1"); var timestamp = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd HH:mm:ss'); targetCell.setValue(timestamp); // 保护该单元格,禁止编辑 var cellProtection = targetCell.protect(); cellProtection.setDescription("Protected Timestamp Cell"); cellProtection.setWarningOnly(false); // 移除所有默认编辑者,仅保留表格所有者/脚本运行者权限 cellProtection.removeEditors(cellProtection.getEditors()); // 如需允许特定用户编辑,取消下方注释并添加邮箱 // cellProtection.addEditors(["user1@example.com", "user2@example.com"]); // 原有的复制工作表保护逻辑 var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE); for (var i = 0; i < protections.length; i++) { var p = protections[i]; var rangeNotation = p.getRange().getA1Notation(); var p2 = sheet2.getRange(rangeNotation).protect(); p2.setDescription(p.getDescription()); p2.setWarningOnly(p.isWarningOnly()); if (!p.isWarningOnly()) { p2.removeEditors(p2.getEditors()); p2.addEditors(p.getEditors()); // p2.setDomainEdit(p.canDomainEdit()); // 仅适用于Google Workspace域名环境 } } }
关键修改说明
- 时间戳写入:
- 替换
"A1"为你需要放置时间戳的目标单元格(如"B2")。 - 时间格式
'yyyy-MM-dd HH:mm:ss'可按需调整,比如改为'dd/MM/yyyy HH:mm'。
- 替换
- 单元格保护:
setWarningOnly(false)设置为严格禁止编辑(若设为true则仅显示警告,仍可编辑)。removeEditors移除所有默认编辑者,确保只有表格所有者或脚本运行者能修改该单元格;如需开放给特定用户,取消addEditors的注释并添加对应邮箱即可。
内容的提问来源于stack exchange,提问作者dek
相关产品推荐
相关产品推荐

