You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Sheet指定日期后保护工作表,仅所有者可编辑脚本修改

解决Google Sheet脚本保护后仅所有者可编辑的修改方案

修改后的脚本

function onOpen() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const owner = ss.getOwner(); // 获取表格所有者
  const sheets = ss.getSheets();
  const lockDates = ss.getSheetByName("LockDates").getDataRange().getValues();
  const now = new Date();
  
  for (let i = 0; i < sheets.length; i++){
    const currentSheet = sheets[i];
    // 查找当前工作表对应的锁定日期
    const sheetLockDate = lockDates.find(row => row[0] === currentSheet.getName())?.[1];
    
    if (sheetLockDate) { // 仅处理在LockDates表中存在的工作表
      if (now >= sheetLockDate && sheetLockDate > 0) {
        // 创建或获取保护对象
        const protection = currentSheet.protect();
        // 清除所有现有编辑器
        protection.removeEditors(protection.getEditors());
        // 仅添加所有者为编辑器
        protection.addEditor(owner);
        // 禁止用户通过链接获取编辑权限(可选,增强安全性)
        protection.setDomainEdit(false);
        console.log(`工作表 - ${currentSheet.getName()} - 已设置为仅所有者可编辑`);
      } else {
        // 移除工作表的所有保护
        const protections = currentSheet.getProtections(SpreadsheetApp.ProtectionType.SHEET);
        protections.forEach(protection => protection.remove());
        console.log(`工作表 - ${currentSheet.getName()} - 已解除保护`);
      }
    }
  }
}

关键修改说明

  • 核心权限修正:创建保护后先清空所有现有编辑器,仅保留表格所有者作为唯一编辑者,彻底限制其他用户的编辑权限
  • 优化查找逻辑:用find方法替代原有的索引计算方式,避免因表格结构变化导致的匹配错误
  • 移除无效中断:删除原脚本中的break语句,确保所有符合锁定日期条件的工作表都会被处理
  • 优化保护移除逻辑:直接获取工作表已存在的保护对象再移除,避免创建新保护后立即删除的无效操作
  • 可选安全增强:添加setDomainEdit(false),禁止同域名用户通过链接获取编辑权限(不需要可删除该行)

内容的提问来源于stack exchange,提问作者Tuấn Anh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 08:47:33