繁体   English   中英

满足条件后锁定 Google 表格单元格/范围

[英]Lock Google Sheets cells/range after condition is met

我们在内部使用 Google 表格进行财务核对,但其中存在一些错误。 有一个包含所有数据的电子表格,几乎公司中的每个人都可以访问并进行编辑。 我想做的是在满足简单条件(例如,单元格填充颜色更改为红色)时,为除少数人之外的所有用户锁定某些单元格。 所以功能描述看起来像:

  1. 每个人都可以访问电子表格
  2. 范围内的单元格(应锁定的单元格)未锁定
  3. 在满足条件之前单元格不会被锁定
  4. 用户向单元格/范围输入值
  5. 用户应用条件(例如填充颜色)
  6. 细胞锁。 除少数用户外,所有用户的访问权限都被删除
  7. 具有访问权限的用户可以编辑/解锁

如果有人可以帮助应用确切的功能,我们将不胜感激。 提前谢谢了!

我唯一找到的是接近我的问题的文档: https ://developers.google.com/apps-script/reference/spreadsheet/range https://developers.google.com/apps-script/reference /spreadsheet/protection但我在 Google 表格使用的 Apps 脚本中为零(

这让你接近但不幸的是我遇到了 onEdit 事件的问题显然不考虑背景颜色变化......所以最终这只会在单元格值改变后触发。

如果单元格为红色且范围尚未受到保护,那么它将受到保护,因为您是唯一的编辑者。 如果背景不是红色,它将取消保护或不改变。

/**
* Protects and unprotects ranges;
* @param {Object} e event object;
*/
function onEdit(e) {
  //access cell formats;
  var bgColor = e.range.getBackground();
  var bold = e.range.getFontWeight();

  //access edited range, value and sheet;
  var rng = e.range;
  var val = e.value;
  var sh  = rng.getSheet();

  //access edited range row and column;
  var row = rng.getRow();
  var col = rng.getColumn();

  //access protections;
  var ps = sh.getProtections(SpreadsheetApp.ProtectionType.RANGE);

  //filter out other cells protections;
  ps = ps.filter(function(p){
   var ptd = p.getRange();
   if(row===ptd.getRow()&&col===ptd.getColumn()) {
     return p;
   }
  })[0];

  //SpreadsheetApp.getActive().toast(bgColor); //Uncomment to get a toast displaying background color of edited cell.

  //if protection not set -> protect;
  if(!ps) {
    if (bgColor === '#ff0000' && bold === 'bold') {
      SpreadsheetApp.getActive().toast("Cell Locked");
      var protection = rng.protect(); //protect Range;
      var users = protection.getEditors(); //get current editors;
      var emails = [Session.getEffectiveUser(),'email1@email.com','email2@email.com']; //declare list of users (emails)
      
      protection.addEditor(Session.getEffectiveUser());
      protection.addEditors(emails);
      protection.removeEditors(users); //remove other editors' access;
    }}else {
      if(!val || bgColor != '#ff0000' || bold != 'bold') { ps.remove(); } //if cell is empty -> remove protection;
    }
}

也许有人可以对此进行改进并仅针对背景事件进行调整。 另外,如果工作速度很快,这就跟不上了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM