【问题标题】:How can I get this to protect a sheet on scripting basis (Google Apps Script)?我怎样才能得到这个来保护基于脚本的工作表(Google Apps Script)?
【发布时间】:2021-05-27 20:13:35
【问题描述】:
我让这段代码运行没有错误;
生成的电子表格确实在工作表名称旁边显示了一个储物柜;
受保护的工作表和范围仅显示特定范围不受保护,但打开文件的其他用户可以编辑受保护范围:
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]);
我在这里错过了什么?
【问题讨论】:
标签:
google-apps-script
google-sheets
protection
【解决方案1】:
解释/问题:
根据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);
}
}