如果特定单元格已更改为特定值,则保护/取消保护范围

时间:2018-06-10 16:54:19

标签: google-apps-script google-sheets

我想让一个特定的范围不可更改。但是如果特定单元格已从“否”更改为“是”,则该范围应该是可更改的。如果特定单元格从“是”变为“否”,则该范围不应再次更改。

我怎么能在googe app脚本中意识到这一点?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

下面的内容应该让你开始。基本上,保护Apps脚本中的内容很容易;取消保护更加繁琐。因此,我建议在相关的受保护范围中添加描述(就像我使用“Test1”一样),之后,下面的循环将轻松找到并删除它。

我已将其附加到this demo spreadsheet,因此您可以获得我正在使用的数据的上下文。

function onEdit(event){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheets()[0]; // 0 == first sheet.
  var ee = event.source.getActiveRange().getA1Notation();
  if (ee == "A2") { // Check if edited cell is the one we're watching.
    if (event.value == "yes"){ // If the value == "yes", do stuff.
      var protections = sh.getProtections(SpreadsheetApp.ProtectionType.RANGE);
      for (var i = 0; i < protections.length; i++) {
        if (protections[i].getDescription() == 'Test1') { // If protection description == "Test1"...
          protections[i].remove(); // then remove protection.
        }
      }
    } 
  }  
}

function setProtected(){
  // Sets the desired range to protected with "Test1" description for demonstration.
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheets()[0];
  var protectedRows = sh.getRange("C2:C11");
  protectedRows.protect().setDescription("Test1");
}
相关问题