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

使用Apps Script为Google表格受保护范围按邮箱添加授权用户

问题说明

我正在使用绑定在Google表格上的可安装onOpen触发器脚本实现范围保护,脚本在表格打开时自动运行。当前配置的保护规则仅允许表格所有者访问受保护范围,其余所有用户都无编辑权限。需要修改脚本逻辑,让指定邮箱对应的用户和所有者都拥有受保护范围的编辑权限。

原脚本如下:

function installedOnOpen(e) {
const sheetNames = ["Sheet1"]; // Please set the sheet names you want to protect.
const sheets = e.source.getSheets().filter(s => 
sheetNames.includes(s.getSheetName()));
if (sheets.length == 0) return;
sheets.forEach(s => {
const p = s.getProtections(SpreadsheetApp.ProtectionType.RANGE);
if (p.length > 0) {
  p.forEach(pp => pp.remove());
}
const lastRow = s.getLastRow();
if (lastRow != 0) {
  const newProtect = s.getRange(1, 1, lastRow, s.getMaxColumns()).protect();
  newProtect.removeEditors(newProtect.getEditors());
  if (newProtect.canDomainEdit()) newProtect.setDomainEdit(false);
 }
 });
 }
修改方案

原脚本在创建保护规则后,调用removeEditors(newProtect.getEditors())清空了所有非所有者的编辑权限,只需要在这一步之后追加指定邮箱的编辑权限授权即可,修改后的完整代码如下:

function installedOnOpen(e) {
  // 配置需要保护的工作表名称
  const sheetNames = ["Sheet1"];
  // 配置允许编辑受保护范围的用户邮箱,替换为实际邮箱即可
  const allowedEditorEmails = ["user1@yourdomain.com", "user2@gmail.com"];

  const sheets = e.source.getSheets().filter(s => sheetNames.includes(s.getSheetName()));
  if (sheets.length == 0) return;

  sheets.forEach(s => {
    // 清除工作表上已存在的范围保护规则
    const existingProtections = s.getProtections(SpreadsheetApp.ProtectionType.RANGE);
    if (existingProtections.length > 0) {
      existingProtections.forEach(pp => pp.remove());
    }

    const lastRow = s.getLastRow();
    if (lastRow != 0) {
      // 创建新的范围保护,覆盖从第一行到最后一行的所有列
      const newProtect = s.getRange(1, 1, lastRow, s.getMaxColumns()).protect();
      // 移除所有默认编辑者
      newProtect.removeEditors(newProtect.getEditors());
      // 给指定邮箱的用户添加编辑权限
      newProtect.addEditors(allowedEditorEmails);
      // 关闭域内全员可编辑权限
      if (newProtect.canDomainEdit()) newProtect.setDomainEdit(false);
    }
  });
}
注意事项
  • 表格所有者默认拥有所有保护范围的最高权限,不需要将所有者邮箱加入allowedEditorEmails列表
  • 请将allowedEditorEmails数组中的示例邮箱替换为实际需要授权的用户邮箱,支持添加任意数量的邮箱
  • 若需要调整保护的工作表,直接修改sheetNames数组内的工作表名即可
  • 脚本修改完成后无需重新创建触发器,已配置的可安装onOpen触发器会自动加载最新逻辑运行

内容的提问来源于stack exchange,提问作者Edyphant

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 09:00:53