通过脚本替换受保护范围内的用户(Google Sheet)

Replace user in a protected range by script (Google Sheet)

这里是我的具体案例:

  1. 我在 google sheets
  2. 中保护了一些范围
  3. 如果是那些范围内的编辑器,我需要替换一些特定的编辑器(var Editor2Replace 和 Editor2Add 是电子邮件)
  4. 逻辑上我尝试了,对于每个 sheet:

这是代码,但是逻辑上有问题,我怀疑什么是数组,什么不是..

   var Protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
    for (var p = 0; p < Protections.length; p++) {
      var Protection_Desc = Protections[p].getDescription();
      var Protection_Editors = [];
      var Protection_Editors = [Protections[p].getEditors()];
      for (var r = 0; r < Protection_Editors.length; r++){
         var Protection_Email[r] = [Protection_Editors[r].getEmail()];
         if (Protection_Idontknow == Editor2Replace){
          Protections[p].addEditor = Editor2Add;
          Protections[p].removeEditor = Editor2Replace;

          var Protection_Range = Protections[p].getRange();
          var Protection_Row = Protection_Range.getRow();
          var Owner1 = sheet.getRange(Protection_Row,5).getValue();
          var Owner2 = sheet.getRange(Protection_Row,6).getValue();
          if (Owner1 == Editor2Replace){
              sheet.getRange(Protection_Row,5).setValue(Editor2Add);
          }
          if (Owner2 == Editor2Replace){
              sheet.getRange(Protection_Row,6).setValue(Editor2Add);
          }
        }
      }

非常感谢您的帮助

你的脚本有很多问题,我会一一列举。此外,我能够通过修改脚本替换受保护 sheet 中的用户。

问题:

  1. 重复声明
var Protection_Editors = [];
var Protection_Editors = [Protections[p].getEditors()];
  1. 将返回值(数组)存储在另一个数组中(这不应该在您的问题中完成,它对您没有任何帮助)
var Protection_Editors = [Protections[p].getEditors()];
...
var Protection_Email[r] = [Protection_Editors[r].getEmail()];
  1. 新声明的变量有一个索引(我不明白为什么)
var Protection_Email[r] = [Protection_Editors[r].getEmail()];
  1. 变量未声明Protection_Idontknow
if (Protection_Idontknow == Editor2Replace){
  1. 方法 addEditorremoveEditor
  2. 的使用不正确
Protections[p].addEditor = Editor2Add;
Protections[p].removeEditor = Editor2Replace;

下面的代码应该可以解决这些问题(添加了一些注释):

代码:

  var Protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
  for (var p = 0; p < Protections.length; p++) {
    var Protection_Desc = Protections[p].getDescription();
    // returned value of getEditors is already an array, return as is
    var Protection_Editors = Protections[p].getEditors();
    for (var r = 0; r < Protection_Editors.length; r++) {
      var Protection_Email = Protection_Editors[r].getEmail();
      // compare current email with the one you want to replace
      if (Protection_Email == Editor2Replace) {
        // add new and remove the one to replace
        Protections[p].addEditor(Editor2Add);
        Protections[p].removeEditor(Editor2Replace);
      }
    }
  }

注:

  • 我已经删除了与更换编辑器无关的所有内容。

参考: