簡體   English   中英

如何使用谷歌腳本鎖定單元格?

[英]How to lock cell using google script?

我有一個 Google 電子表格,可以與我的員工共享以記錄每個訂單的詳細信息。 這只是示例:

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

每次訂單關閉時,我希望保護整個訂單行以避免錯誤編輯。 在示例文件中,我有一個腳本代碼,是我從其他一些帖子中復制的(我再也找不到了),但是我和原始海報之間的需求有點不同,所以我編輯了范圍,但仍然無法實現完美的。

這是我需要的:

  1. 如果 G2 = 1,A2:F2 保護只有所有者可以編輯。 當 G2 為其他時,清除保護范圍 A2:F2。 在 2000 年之前,我需要它在每一行中都做同樣的事情。(G3 = 1 然后保護 A3:F3)(G4 = 1 然后保護 A4:F4)直到 2000 行這樣的事情。

  2. 我希望將相同的代碼應用於所有 4 個選項卡(Sheet1 到 Sheet4)

  3. 我發現使用我當前的腳本,如果 G2 = 1,每次我編輯某些內容時,它都會向同一范圍 (A2:F2) 添加一個新范圍。我記得原來的帖子是 onOpen 但我必須將其設為 onEdit 以確保一切都得到了很好的保護。

也許這可以幫助你。 首先考慮幾點:

首先,創建 Range 不是一個快速的過程,它需要 0.5 到 1 秒,因此對 4 張紙中的 2000 行(即 8000 行)執行此操作需要 1 或 2 小時,這遠遠超出了即使您是 Enterprise G Suite 用戶,也有執行時間限制

范圍的主要問題是它們存儲在SpreadsheetApp.ProtectionType.RANGE ,這會創建一個范圍數組,因此為了在 G 不為 1 時刪除特定范圍,您必須將您編輯的行與所有值進行比較范圍數組的。

每次編輯行時都會執行此腳本,如果它受保護 (G = 1),則它什么也不做,如果不是,並且您更改 G = 1,則它會保護該行的范圍 A:F。 如果更改 G 中的 1,則會刪除保護。 因此,這不會保護或取消保護 4 個工作表中的每一行,它只會保護或取消保護您在任何工作表中編輯的行。

 function onEdit() {
  var sprsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = sprsheet.getActiveSheet();
  var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
  var col_G = sheet.getRange("G2:G2000").getValues();
  var edited_row = sheet.getActiveRange().getRow();
  var protected = false;
  var range_pos;
  modifyProtection(edited_row, protections, col_G, sheet, protected);

}

function modifyProtection(edited_row, protections, col_G, sheet, protected, range_pos){
  if (protections.length == 0 && col_G[edited_row - 2] == 1){ //In case there aren't ranges yet
    createRange(edited_row, sheet);

  } else {
      for (var i = 0; i < protections.length; i++){

          if (edited_row == protections[i].getRange().getRow()){
            range_pos = i;
            protected = true;

          }
  }
    if (protected && col_G[edited_row - 2] != 1){
          protected = false;
          deleteRange(range_pos, protections);        


    } else {
          if (!protected && col_G[edited_row - 2] == 1){
              protected = true;
              createRange(edited_row, sheet);
      }
    }
  }
}

function createRange(edited_row, sheet, protected){

   var range = sheet.getRange('A'+(edited_row)+':F'+(edited_row));
   var protection = range.protect().setDescription('Sample protected range');
   var me = 'your_email';//This will be the only editor of the protected ranges   
   protection.addEditor(me);  
   protection.removeEditors(protection.getEditors());

   if (protection.canDomainEdit()) {
       protection.setDomainEdit(false);
   }
}

function deleteRange(i, protections){
    protections[i].remove();
}

暫無
暫無

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

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