繁体   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