我有一个工作表,其中包含用户在 C 和 D 列第 3 - 20 行中输入的响应。响应取决于时间并查看 E 列第 3-20 行以查看它是“锁定”还是“打开”。
使用保护,我锁定整个工作表以进行编辑,但 C3:D20 除外。该工作表设置为每分钟计算一次。
我正在尝试编写一个脚本来检查列 E 以查看它是设置为锁定还是打开。如果将其设置为锁定,我想锁定(保护)该行中的 C&D 列,以便除我以外的所有人进行编辑。我每 5 分钟运行一次脚本,我处理了 for 循环和 if 语句,但是当我去使用 RemoveEditors 函数时,它做了两件事:
我尝试使用谷歌的示例代码,但他们的代码将当前用户添加为编辑器,这是我试图避免的,因为从那时起,编辑器就可以删除代码设置的保护。
您能提供的任何帮助将不胜感激。
当前代码如下:
function Lock_Cells() {
var sheet = SpreadsheetApp.getActive();
for (var i = 3; i <= 20; i++)
{
var Check_Cell = "E" + i;
var Temp = sheet.getRange(Check_Cell).getValue();
if (Temp == "Locked")
{
var Lock_Range = "C" + (i + 2) + ":D" + "i";
var protection = sheet.getRange(Lock_Range).protect();
var description = "Row " + i;
protection.setDescription(description);
var eds = protection.getEditors();
protection.removeEditors(eds);
}
}
}
为避免创建一组新的受保护范围,您可以添加逻辑来检查哪些行已被锁定。有了这些信息,您只需要跳过这些行:
注意:这一行有一个错误:
var Lock_Range = "C" + (i + 2) + ":D" + "i";
变量 i 不应该有引号。
function Lock_Cells() {
var sheet = SpreadsheetApp.getActive();
var rows = get_protected_Rows();
for (var i =3; i <= 20; i++)
{
var Check_Cell = "E" + i;
var cell = sheet.getRange(Check_Cell);
var Temp = sheet.getRange(Check_Cell).getValue();
if (Temp == "Locked" && rows.indexOf(i) <0)
{
var Lock_Range = "C" + i + ":D" + i; //In this line you put "i"
.....
...
}
function get_protected_Rows()
{
var ss = SpreadsheetApp.getActive();
var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
var rows = [];
for (var i = 0; i < protections.length; i++) {
var protection = protections[i];
var anotation = protection.getRange().getRow();
rows.push(anotation);
}
return rows
}
你是对的,当其中一个用户执行代码时,保护使该用户能够编辑这些行。我建议作为文件的所有者,您还可以运行一个任务以从这些行中删除所有其他编辑器。该功能将与之前的功能非常相似。我知道这不是最好的,但它可以帮助你处理你的用例。
function remove_editors()
{
var ss = SpreadsheetApp.getActive();
var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
var protection = protections[i];
var anotation = protection.getRange().getA1Notation();
var eds = protection.getEditors();
protection.removeEditors(eds);
}
}
通过这样做,我能够限制对其他用户的权限。希望对您有所帮助。