Google Script Lock Cells

时间:2015-06-03 12:36:34

标签: google-apps-script google-sheets

我正在尝试实现一个脚本,当条件为真时锁定某个范围的单元格。这是我的文档的链接:

https://docs.google.com/spreadsheets/d/1XShGxlz2fA2w2omth-TvYc7cK0nXvVMrhwRKafzVjOA/edit?usp=sharing

基本上我正在与一群人共享此文档,因此他们在B列填写他们的邮件地址,并在C列中放置一个数字1,以便为每个插槽增加我的计数器。我想要做的是在每个插槽已满时将其锁定,以便其他人无法再编辑这些插槽,但问题在于我的if语句if (cell1 == 10)。即使未实现if条件,范围也始终处于锁定状态。这是我的代码:

function onOpen() {


  var ss = SpreadsheetApp.getActive();
  var source =         SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");

 var cell=60;
 var cell1 = source.getRange("G2").getValue();

 if (cell1 == 10){

// Protect range B2:B11, then remove all other users from the list of editors.
var ss = SpreadsheetApp.getActive();
var range = ss.getRange('B2:B11');
var protection = range.protect().setDescription('Sample protected range');

// Ensure the current user is an editor before removing others. Otherwise, if the user's edit
// permission comes from a group, the script will throw an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}

  }


}

1 个答案:

答案 0 :(得分:1)

正如Andy在评论中所说,如果单元格G2不等于10,则需要明确删除保护。(此代码将删除所有保护措施)。

阅读Protection Class页面,您从中获取了片段,我无法理解编辑器权限会影响您的需求的方式,因此如果其他人是编辑者,此脚本将起作用。如果您不希望它们成为编辑者,则必须添加相关代码。

function onOpen() {

  var ss = SpreadsheetApp.getActive();
  var source = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var cell = source.getRange("G2").getValue();
  var range = ss.getRange('B2:B11');

  if (cell == 10) {

    // Protect range B2:B11 if cell 'G2' = 10
    var protection = range.protect().setDescription('Sample protected range');
    Logger.log

  } else {

    // Remove protection if cell 'G2' is anything other than 10
    var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);

    for (var i = 0; i < protections.length; i++) {
      var protection = protections[i];
      protection.remove();
    }
  }  
}