如何在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
相关产品推荐
相关产品推荐

