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

如何修改Apps Script代码实现Google Sheet完整工作表保护

Google Sheets全工作表保护代码修改方案

原代码用于保护指定单元格范围,现在要改成保护整个工作表,无需指定范围,具体修改如下:

核心修改点

  • 删掉与「保护范围」相关的所有逻辑:包括读取B6单元格的代码、校验逻辑里的范围检查,以及提示文本中的Range字段
  • 替换保护类型:从ProtectionType.RANGE改为ProtectionType.SHEET,针对整个工作表创建保护
  • 调整保护清理逻辑:不再清理指定范围的保护,改为清理当前工作表已有的工作表级保护
  • 更新交互文本:确认对话框和完成提示里的内容,把「范围」改成「工作表」

修改后的完整代码

function protectSheet() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getActiveSheet();

  // 读取配置信息(移除了范围相关读取)
  var fileIds = sheet.getRange("B3").getValue().split(',');
  var editorsCell = sheet.getRange("B9");
  var editors = editorsCell.getValue();

  // 整理编辑者列表
  var editorsArray = editors.split(',');
  for (var k = 0; k < editorsArray.length; k++) {
    editorsArray[k] = editorsArray[k].trim();
  }

  // 必填项校验(移除了范围的检查)
  if (fileIds.length === 0 || editorsArray.length === 0) {
    var ui = SpreadsheetApp.getUi();
    ui.alert("错误", "请填写Spreadsheet ID和编辑者列表。", ui.ButtonSet.OK);
    return;
  }

  // 确认对话框(更新为工作表保护的提示)
  var ui = SpreadsheetApp.getUi();
  var confirmationMessage = "即将保护目标文件中的所有可见工作表,允许以下编辑者:\n\n" + editors;
  var response = ui.alert('确认操作', confirmationMessage, ui.ButtonSet.OK_CANCEL);

  if (response == ui.Button.OK) {
    fileIds.forEach(function(fileId) {
      var file = DriveApp.getFileById(fileId.trim());
      if (file.getMimeType() === MimeType.GOOGLE_SHEETS) {
        var ss = SpreadsheetApp.openById(fileId.trim());
        var sheets = ss.getSheets();

        for (var i = 0; i < sheets.length; i++) {
          var currentSheet = sheets[i];

          // 跳过隐藏工作表
          if(currentSheet.isSheetHidden()){
            continue;
          }

          // 清理当前工作表已有的工作表级保护
          var protections = currentSheet.getProtections(SpreadsheetApp.ProtectionType.SHEET);
          for (var j = 0; j < protections.length; j++) {
            protections[j].remove();
          }

          // 创建整个工作表的保护
          var newProtection = currentSheet.protect();
          newProtection.setDescription('工作表级保护');

          // 添加允许的编辑者
          newProtection.addEditors(editorsArray);

          // 移除不在列表中的编辑者(保留所有者)
          var currentEditors = newProtection.getEditors();
          for (var l = 0; l < currentEditors.length; l++) {
            var currentEditor = currentEditors[l].getEmail();
            if (editorsArray.indexOf(currentEditor) === -1 && currentEditor !== spreadsheet.getOwner().getEmail()) {
              newProtection.removeEditor(currentEditor);
            }
          }
        }
      }
    });
    ui.alert('工作表保护完成', '所有可见工作表已成功设置保护。', ui.ButtonSet.OK);
  }
}

额外说明

  • 函数名从protectRange改成了protectSheet,更贴合功能
  • 保留了跳过隐藏工作表的逻辑,如果你不需要可以删掉对应的判断
  • 编辑者列表依然从B9单元格读取,用逗号分隔邮箱地址

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 07:08:20