【问题标题】:Lock Google Sheets cells/range after condition is met满足条件后锁定 Google 表格单元格/范围
【发布时间】:2022-12-15 02:38:52
【问题描述】:

我们在内部使用 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 脚本中为零(

【问题讨论】:

  • 请提供足够的代码,以便其他人可以更好地理解或重现问题。

标签: google-apps-script google-sheets google-sheets-formula


【解决方案1】:

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

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

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

  //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") {
      SpreadsheetApp.getActive().toast("Cell Locked");
      var protection = rng.protect(); //protect Range;
      var users = protection.getEditors(); //get current editors;

      protection.addEditor(Session.getEffectiveUser());
      protection.removeEditors(users); //remove other editors' access;
    }}else {
      if(!val) { ps.remove(); } //if cell is empty -> remove protection;
    }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多