我怎样才能得到它来保护基于脚本的工作表Google Apps 脚本?

问题描述

我运行这段代码没有错误; 生成的电子表格确实在工作表名称旁边显示了一个储物柜; 受保护的工作表和范围仅显示未受保护的特定范围,但打开文件的其他用户可以编辑受保护的范围:

      var editors = newSpreadsheet.getEditors();
      for (var i = 0; i < editors.length; i++) {
        newSpreadsheet.removeEditor(editors[i]);
      };

      var sheetToProtect = newSpreadsheet.getSheetByName('CheckList');
      var rngMonitorUnprotect = sheetToProtect.getRange("F11:F14");
      var protection = sheetToProtect.protect();
      protection.setUnprotectedRanges([rngMonitorUnprotect]);

我在这里遗漏了什么?

解决方法

说明/问题:

根据 official documentation,这是对工作表应用保护的正确方法。

  • 问题在于您没有从 protection 对象中删除编辑者列表。您所做的是将它们从电子表格文件本身中删除。

  • 本质上,当您向工作表添加保护时,所有当前编辑者都会自动拥有编辑工作表(或工作表范围)的权利,而不管保护如何。因此,您的脚本需要从该权限中删除它们,这就是我们执行此操作的原因:

    protection.removeEditors(protection.getEditors());
    

仅保护工作表的范围F11:F14

function myFunction() {
  // Protect range F11:F14,then remove all other users from the list of editors.
  var sheetToProtect = SpreadsheetApp.getActive().getSheetByName('CheckList'); 
  var range = sheetToProtect.getRange('F11:F14'); 
  var protection = range.protect();

  // Ensure the current user is an editor before removing others. Otherwise,if the user's edit
  // permission comes from a group,the script throws an exception upon removing the group.
  var me = Session.getEffectiveUser();
  protection.addEditor(me);
  protection.removeEditors(protection.getEditors());
  if (protection.canDomainEdit()) {
    protection.setDomainEdit(false);
  }
}

保护除F11:F14之外的整个工作表:

function myFunction() {
  var sheetToProtect = SpreadsheetApp.getActive().getSheetByName('CheckList'); 
  var protection = sheetToProtect.protect();
  var rngMonitorUnprotect = sheetToProtect.getRange("F11:F14");  
  protection.setUnprotectedRanges([rngMonitorUnprotect]);    
  var me = Session.getEffectiveUser();
  protection.addEditor(me);
  protection.removeEditors(protection.getEditors());
  if (protection.canDomainEdit()) {
    protection.setDomainEdit(false);
  }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...