繁体   English   中英

Google表格脚本根据列单元格中的值锁定或解锁行

[英]Google Sheets Script to lock or unlock a row depending on the value in the cell of a column

如果在“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”:

在此处输入图像描述

参考:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM