根据编辑器为单元格着色

Colorize cells based on editor

我尝试为 Google Sheets 制作一个脚本,看看编辑们修改了什么。 这是我的脚本:

function onEdit() {  
  var sheet = SpreadsheetApp.getActiveSheet();
  var email = Session.getActiveUser().getEmail();
  Logger.log(email);
  var User1 = email.indexOf("user1@email.com");
  var User2 = email.indexOf("user2@email.com");
  Logger.log(User1);
  Logger.log(User2);
  if (User1 = -1.0){
    sheet.getActiveCell().setBackground('#f4cccc')}
  if (User2 = -1.0){
    sheet.getActiveCell().setBackground('#c9daf8')}
}

日志看起来正确:

11:42:08 AM Notice  Execution started
11:42:10 AM Info    user1@email.com
11:42:10 AM Info    0.0
11:42:10 AM Info    -1.0
11:42:09 AM Notice  Execution completed

但是 User1 和 2 得到了相同的颜色 (c9daf8)。所以我错过了一些东西。

试试下面的代码:

您需要使用 getEffectiveUser() 而不是 getActiveUser()

function onEdit() {  
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var email = Session.getEffectiveUser().getEmail();
  Logger.log(email);
  var User1 = "user1@email.com";
  var User2 ="user2@email.com";

  if (email == User1){
    sheet.getActiveCell().setBackground('#f4cccc');

    }
  if (email == User2) {
    sheet.getActiveCell().setBackground('#c9daf8');}
}

参考:getEffectiveUser()

如果适用于特定数据范围:

function onEdit() {  
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var dataRng = sheet.getActiveCell().getColumn();
  var email = Session.getEffectiveUser().getEmail();
  Logger.log(email);
  var User1 = "user1@gmail.com";
  var User2 = "user2@gmail.com";

  if (email == User1 && (dataRng == 2 || dataRng == 3) ){
    sheet.getActiveCell().setBackground('#f4cccc');

    }
  if (email == User2 && (dataRng == 2 || dataRng == 3)){
    sheet.getActiveCell().setBackground('#c9daf8');

  }

}