请求修改脚本:复制带有多范围例外的受保护工作表
修正后的脚本:支持复制带多例外范围的受保护工作表
原脚本的问题在于仅复制了基础的范围保护规则,但没有处理受保护范围中的例外可编辑区域,同时存在重复复制的冗余代码。以下是修复后的完整代码:
function copyProtectedSheets() { const ss = SpreadsheetApp.getActiveSpreadsheet(); const sourceSheet = ss.getSheetByName('Monthly Budget'); // 生成15份带完整保护的副本 for (let i = 1; i <= 15; i++) { copySheetWithFullProtections_(sourceSheet, `Monthly Copy ${i}`); } } function copySheetWithFullProtections_(sourceSheet, newName) { const ss = SpreadsheetApp.getActiveSpreadsheet(); const newSheet = sourceSheet.copyTo(ss); newSheet.setName(newName); // 复制工作表级保护(如果有的话) const sheetProtection = sourceSheet.getProtection(SpreadsheetApp.ProtectionType.SHEET); if (sheetProtection) { const newSheetProtection = newSheet.protect(); newSheetProtection.setDescription(sheetProtection.getDescription()); newSheetProtection.setWarningOnly(sheetProtection.isWarningOnly()); if (!sheetProtection.isWarningOnly()) { newSheetProtection.removeEditors(newSheetProtection.getEditors()); newSheetProtection.addEditors(sheetProtection.getEditors()); // 复制工作表级保护的例外范围 const unprotectedRanges = sheetProtection.getUnprotectedRanges(); const newUnprotectedRanges = unprotectedRanges.map(range => { return newSheet.getRange(range.getA1Notation()); }); newSheetProtection.setUnprotectedRanges(newUnprotectedRanges); } } // 复制范围级保护及对应的例外范围 const rangeProtections = sourceSheet.getProtections(SpreadsheetApp.ProtectionType.RANGE); rangeProtections.forEach(protection => { const rangeNotation = protection.getRange().getA1Notation(); const newRange = newSheet.getRange(rangeNotation); const newProtection = newRange.protect(); // 复制基础保护属性 newProtection.setDescription(protection.getDescription()); newProtection.setWarningOnly(protection.isWarningOnly()); if (!protection.isWarningOnly()) { newProtection.removeEditors(newProtection.getEditors()); newProtection.addEditors(protection.getEditors()); } // 复制保护范围中的例外可编辑区域 const unprotectedRanges = protection.getUnprotectedRanges(); const newUnprotectedRanges = unprotectedRanges.map(range => { return newSheet.getRange(range.getA1Notation()); }); newProtection.setUnprotectedRanges(newUnprotectedRanges); }); return newSheet; }
关键修改说明
- 移除冗余代码:删除原脚本中重复的单独复制逻辑,统一通过循环调用改进后的复制函数生成15份副本。
- 增加例外范围复制:在复制工作表级和范围级保护时,通过
getUnprotectedRanges()获取原保护的例外区域,映射到新工作表后用setUnprotectedRanges()设置,确保例外可编辑区域完整保留。 - 覆盖两种保护类型:同时处理工作表级(Sheet)和范围级(Range)的保护规则,避免遗漏任何保护设置。
使用说明:直接运行copyProtectedSheets函数即可生成15份保留完整保护(含例外范围)的工作表副本。
内容的提问来源于stack exchange,提问作者Alesha
相关产品推荐
相关产品推荐

