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

如何用Google Apps Script实现谷歌表格用户自锁定指定区域

解决方案:锁定指定区域并自动通知主管

你已经迈出了第一步,我来帮你完善这段脚本,实现运行脚本的用户无法编辑目标区域,同时自动通知主管待审核的完整功能。以下是经过优化的完整代码,附带详细解释:

function lockRangeAndNotifySupervisor() {
  // 获取当前打开的电子表格
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  // 定义要锁定的区域(替换成你实际的起始行、列参数)
  const targetRange = ss.getRange(start_row, start_col, 30, 7);
  // 获取当前运行脚本的用户邮箱
  const currentUserEmail = Session.getActiveUser().getEmail();
  // 替换成主管的邮箱地址
  const supervisorEmail = 'your-supervisor@example.com';

  try {
    // 创建区域保护,并设置描述
    let rangeProtection = targetRange.protect().setDescription('Suunnitelma ilmoitettu.');

    // 移除当前用户的编辑权限——核心逻辑,让运行脚本的人无法再编辑该区域
    rangeProtection.removeEditor(currentUserEmail);

    // 保留表格所有者的编辑权限(可选,避免所有者被误锁)
    const ownerEmail = ss.getOwner().getEmail();
    rangeProtection.addEditor(ownerEmail);

    // 给主管添加编辑权限(可选,方便主管审核时修改内容)
    rangeProtection.addEditor(supervisorEmail);

    // 设置为强制锁定(而非仅警告)
    rangeProtection.setWarningOnly(false);

    // 发送邮件通知主管
    const emailSubject = '【表格审核通知】区域已锁定';
    const emailBody = `
用户 ${currentUserEmail} 已锁定表格「${ss.getName()}」中的区域:${targetRange.getA1Notation()}
请及时进行审核处理。
`;
    MailApp.sendEmail(supervisorEmail, emailSubject, emailBody);

    // 给当前用户弹出操作成功提示
    SpreadsheetApp.getUi().alert('区域已成功锁定,已通知主管审核!');
  } catch (error) {
    // 捕获异常并提示用户
    SpreadsheetApp.getUi().alert(`操作失败:${error.message}`);
  }
}

关键细节说明:

  • 锁定当前用户权限:通过rangeProtection.removeEditor(currentUserEmail)直接移除运行脚本用户的编辑权限,确保他们无法再修改目标区域。
  • 权限精细化控制:
    • 保留表格所有者的编辑权限,避免管理员也被锁定(可根据需求删除这一行)。
    • 给主管添加编辑权限,方便他们审核时调整内容(如果不需要主管编辑,可删除这一行)。
    • setWarningOnly(false)确保区域是强制锁定,而不是仅显示“编辑会被限制”的警告。
  • 自动通知机制:用MailApp.sendEmail()给主管发送清晰的通知,包含操作人、表格名称和锁定区域的A1标记。
  • 异常处理:用try-catch包裹逻辑,避免脚本崩溃,同时给用户明确的错误提示。

额外优化建议:

如果担心重复创建保护,可以添加“检查已有保护”的逻辑,避免覆盖已有设置:

// 先检查是否存在同名保护
const existingProtections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
let rangeProtection = existingProtections.find(protection => protection.getDescription() === 'Suunnitelma ilmoitettu.');
// 如果没有找到,再创建新的保护
if (!rangeProtection) {
  rangeProtection = targetRange.protect().setDescription('Suunnitelma ilmoitettu.');
}

最后,记得替换代码中的start_row、start_col和supervisorEmail为你的实际参数,首次运行脚本时需要授权访问电子表格和发送邮件的权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:16:05