Google Script Lock Cells

こ雲淡風輕ζ 提交于 2020-01-30 09:23:08

问题


I am trying to implement a script that locks a certain range of cells when a condition is true. Here is the link to my document:

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

Basically I am sharing this document with a group of people so they fill their mail addresses in column B and put a number 1 in column C so it increments my counters for each slot. What I am trying to do is to lock each slot when it is full so other people can no more edit these slots but the problem is with my if statement if (cell1 == 10). The range is always locked even if the if condition is not realized. Here is my code :

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:


As Andy says in the comments, you need to explicitly remove the protection if cell G2 does not equal 10. (This code removes all protections).

Reading the Protection Class page, where you got the snippets from, I couldn't get a handle on the way editor privileges would factor into your needs, so this script will work if others are editors. If you don't want them to be editors, you'll have to add the relevant code.

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();
    }
  }  
} 


来源:https://stackoverflow.com/questions/30620299/google-script-lock-cells

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!