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

如何在Google Sheets脚本中添加If Else条件,按描述检查保护并按需添加?

解决Google Sheets脚本中添加保护的条件判断问题

直接给你修改后的完整脚本,核心是先检查目标范围是否存在指定描述的保护,再决定是否执行添加操作:

function LockFriday() {
  const spreadsheetId = 'alsdfjalsfjdlasjfl';
  const targetRange = 'C8:D60';
  const protectionDesc = 'AA Lock Friday Cells';
  const removeEmails = ['email1@gmail.com','email2@gmail.com','email3.com'];

  const spreadsheet = SpreadsheetApp.openById(spreadsheetId);
  const range = spreadsheet.getRange(targetRange);
  
  // 获取该范围的所有范围保护
  const protections = range.getProtections(SpreadsheetApp.ProtectionType.RANGE);
  let protectionExists = false;

  // 遍历检查是否存在指定描述的保护
  for (let i = 0; i < protections.length; i++) {
    const protection = protections[i];
    if (protection.getDescription() === protectionDesc) {
      protectionExists = true;
      break;
    }
  }

  // 根据判断结果执行操作
  if (!protectionExists) {
    const newProtection = range.protect();
    newProtection.setDescription(protectionDesc)
                 .removeEditors(removeEmails);
  }
}

关键说明:

  • 移除了原脚本中不必要的activate()和setCurrentCell(),这些操作对创建保护没有作用,只会增加冗余步骤
  • 用getProtections()获取目标范围的所有保护规则,遍历检查描述是否匹配
  • 通过protectionExists标志变量记录是否找到目标保护,避免重复创建
  • 把常量(如表格ID、目标范围、保护描述)单独提取出来,后续修改更方便

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 00:42:18