在多个工作表的第一保护中添加或删除编辑器

时间:2020-01-09 23:59:45

标签: javascript google-apps-script google-sheets

美好的一天!我有几个工作表,每个工作表都有1个保护,我想在这些工作表之间循环,并在其保护中添加或删除编辑器。

最初,我有以下代码:

function AddOrRemove() {
  var spreadsheet = SpreadsheetApp.getActive();
  var allProtections = spreadsheet.getActiveSheet().getProtections(SpreadsheetApp.ProtectionType.SHEET);
  var protection = allProtections[0];
  protection.removeEditors(['email1@gmail.com']);
  protection.addEditors(['email2@gmail.com']);
};

这将删除email1@gmail.com,同时在email2@gmail.com上添加ActiveSheet,这意味着我必须手动转到每个工作表并从那里运行它。但是,我想自动执行工作表循环,因此想出了以下代码:

function AddOrRemove() {
  var sheets = ["Sheet1","Sheet2","Sheet3","Sheet4","Sheet5","Sheet6","Sheet7","Sheet8","Sheet9","Sheet10"];
  for (var i = 0 ; i = 15 ; i++){
    var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheets[i]);
    var allProtections = spreadsheet.getProtections(SpreadsheetApp.ProtectionType.SHEET);
    var protection = allProtections[0];
    protection.removeEditors(['email1@gmail.com']);
    protection.addEditors(['email2@gmail.com']);
  }
};

其中sheets是我要用来运行代码的所有工作表名称。但是,当尝试运行它时,我遇到此错误:

TypeError: Cannot call method "getProtections" of null. (line 5, file "AddOrRemoveEditors")

我在for循环中的Logger.log(sheets[i]);之前尝试过var Spreadsheets,它记录的是“空”。但是,当我将Logger.log(sheets[0]);放在for循环之前时,它正确地返回了K。我不太确定这里缺少什么。我觉得代码背后的逻辑应该起作用,但也许我遗漏了一些东西。在这方面寻求建议。谢谢!

1 个答案:

答案 0 :(得分:0)

尝试一下:

function AddOrRemove() {
  var sheets = ["Sheet1","Sheet2","Sheet3","Sheet4","Sheet5","Sheet6","Sheet7","Sheet8","Sheet9","Sheet10"];
  for (var i=0;i<sheets.length;i++){//modified
    var spreadsheet = SpreadsheetApp.getActive().getSheetByName(sheets[i]);//modified
    var allProtections = spreadsheet.getProtections(SpreadsheetApp.ProtectionType.SHEET);
    var protection = allProtections[0];
    protection.removeEditors(['email1@gmail.com']);
    protection.addEditors(['email2@gmail.com']);
  }
};
相关问题