簡體   English   中英

Google 腳本鎖定單元格

[英]Google Script Lock Cells

我正在嘗試實現一個腳本,當條件為真時鎖定特定范圍的單元格。 這是我的文檔的鏈接:

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

  }


}

正如安迪在評論中所說,如果單元格 G2 不等於 10,您需要明確刪除保護。(此代碼刪除所有保護)。

閱讀保護類頁面,您從中獲得了片段,我無法了解編輯器權限將影響您的需求的方式,因此如果其他人是編輯器,此腳本將起作用。 如果您不希望它們成為編輯器,則必須添加相關代碼。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM