我使用的脚本允许我在“BG”列中放置“X”时锁定一行。
我希望如果我输入“0”,那么保护就会被删除。
还添加一个函数,以便当我更改“BG”单元格中的值时脚本自动运行。
我的脚本:
function Lock_Cells() {
var sheet = SpreadsheetApp.getActive();
for (var i = 5; i <= 1000; i++)
{
var Check_Cell = "BG" + i;
var Temp = sheet.getRange(Check_Cell).getValue();
if (Temp == "X")
{
var Lock_Range = "B" + i + ":BG" + i;
var protection = sheet.getRange(Lock_Range).protect();
var description = "Ligne " + i;
protection.setDescription(description);
var eds = protection.getEditors();
protection.removeEditors(eds);
}
}
}
无需循环遍历所有行,只需使用 onEdit 触发器即可。每当用户在工作表中编辑或插入值时,onEdit 触发器就会执行一个函数。它有一个事件对象,该对象具有范围属性,您可以使用它来确定编辑单元格的行和列。使用这些属性,您可以轻松锁定特定行。
试试这个代码:
function onEdit(e) {
let range = e.range; //get the range of edited cell
let row = range.getRow(); //get the row
let col = range.getColumn(); //get the column
let value = e.value; //get the new value of edited cell
let sheet = range.getSheet(); //get the sheet where edit is made
if(col == 59 && row >= 5 && value == "X"){ //check if the edited cell is BG and row is equal or greater than 5 and value is X
let lock_range = `B${row}:BG${row}`; //set lock range using row
let protection = sheet.getRange(lock_range).protect() //set protection
.setDescription(`Ligne ${row}`) //add description
protection.removeEditors(protection.getEditors()); //remove editors
}else if(col == 59 && row >= 5 && value == "O"){ //check if the edited cell is BG and row is equal or greater than 5 and value is O
var protectedRange = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE); //get all protection with type range
for (var i = 0; i < protectedRange.length; i++) { //loop
if (protectedRange[i].getDescription() == `Ligne ${row}`) { //row matching
protectedRange[i].remove(); //remove protection
}
}
}
}
演示:
测试表:
添加“X”:
将“X”替换为“O”:
如果电子表格中有很多工作表怎么办?