I use a script that allows me to lock a row if in the “BG” column I put an “X”.
I would like that if I put a “0” then the protection is removed.
Also add a function so that the script runs automatically when I change the value in the “BG” cell.
My Script:
JavaScript
x
18
18
1
function Lock_Cells() {
2
var sheet = SpreadsheetApp.getActive();
3
for (var i = 5; i <= 1000; i++)
4
{
5
var Check_Cell = "BG" + i;
6
var Temp = sheet.getRange(Check_Cell).getValue();
7
if (Temp == "X")
8
{
9
var Lock_Range = "B" + i + ":BG" + i;
10
var protection = sheet.getRange(Lock_Range).protect();
11
var description = "Ligne " + i;
12
protection.setDescription(description);
13
var eds = protection.getEditors();
14
protection.removeEditors(eds);
15
}
16
}
17
}
18
Advertisement
Answer
Instead of looping through all the rows, just use onEdit Trigger. onEdit Trigger will execute a function whenever a user edited or inserted value to the sheet. It has an Event Object which has property of range which you can use to determine the row and column of the edited cell. Using those properties you can easily lock a specific row.
Try this code:
JavaScript
1
22
22
1
function onEdit(e) {
2
let range = e.range; //get the range of edited cell
3
let row = range.getRow(); //get the row
4
let col = range.getColumn(); //get the column
5
let value = e.value; //get the new value of edited cell
6
let sheet = range.getSheet(); //get the sheet where edit is made
7
8
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
9
let lock_range = `B${row}:BG${row}`; //set lock range using row
10
let protection = sheet.getRange(lock_range).protect() //set protection
11
.setDescription(`Ligne ${row}`) //add description
12
protection.removeEditors(protection.getEditors()); //remove editors
13
}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
14
var protectedRange = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE); //get all protection with type range
15
for (var i = 0; i < protectedRange.length; i++) { //loop
16
if (protectedRange[i].getDescription() == `Ligne ${row}`) { //row matching
17
protectedRange[i].remove(); //remove protection
18
}
19
}
20
}
21
}
22
Demo:
Test Sheet:
Adding “X”:
Replacing “X” with “O”: