在脚本运行时阻止编辑单元格

时间:2016-12-12 14:41:59

标签: google-apps-script google-sheets

我有一个小型Google Apps脚本,在电子表格中的某些单元格被编辑后会运行几秒钟。

我的问题是,是否可以阻止当前用户在脚本运行时对电子表格进行进一步更改。

所以它应该是这样的:

  1. 单元格已编辑
  2. 脚本正在运行,当前用户的用户交互/更改被阻止
  3. 脚本已完成
  4. 当前用户的用户互动/更改已取消阻止

1 个答案:

答案 0 :(得分:2)

您可以使用班级保护:https://developers.google.com/apps-script/reference/spreadsheet/protection

根据以上链接改编,您可以尝试:

function pro(){
  var sheet = SpreadsheetApp.getActiveSheet();
  var protection = sheet.protect().setDescription('Sample protected sheet');

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

  //YOUR CODE TO RUN

  SpreadsheetApp.flush();
  protection.remove();  
}

修改

这对我有用:

function onEdit(){
  //Adapted from:  https://developers.google.com/apps-script/reference/spreadsheet/protection
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
  var me = Session.getActiveUser().getEmail();

  if (me != 'owner email'){
    var protection = sheet.protect().setDescription('Sample protected sheet');
    protection.removeEditors(protection.getEditors());
    if (protection.canDomainEdit()) {
      protection.setDomainEdit(false);
    }

    //YOUR CODE TO RUN
    SpreadsheetApp.flush();
    protection.remove(); 
  }
}