GoogleSheet脚本编辑器 - 带有condition / if语句的onEdit事件

时间:2016-06-04 17:04:04

标签: if-statement google-apps-script

人!

我是这个网站的新手,也不熟悉编码。所以我真的很感激一些帮助。

现在我需要一个特定的代码才能使Google工作表完美运行。

进一步解释: 我有一张谷歌表,其他同事会输入一些信息。我需要的是一个代码,它将在特定单元格中注册日期,并在另一个单元格上输入。

到目前为止,这就是我所拥有的:

function onEdit(event) { 

  var sheet = event.source.getSheetByName("Input");

  // Note: actRng = return the last cell of the row modified
  var actRng = event.source.getActiveRange();
  var index = actRng.getRowIndex();
  var cindex = actRng.getColumnIndex();

  // Note: date = return date
  // Note: user = return the user email
  var userCell = sheet.getRange(index,14);
  var dateCell = sheet.getRange(index,2);
  var inputdate = Utilities.formatDate(new Date(), "GMT+0200", "yyyy-MM-dd");
  // Note(with hour): var inputdate = Utilities.formatDate(new Date(), "GMT+0200", "yy-MM-dd HH:mm");


  //var user = event.user;  // Note: event.user will not give you collaborator's Id
  var user = Session.getEffectiveUser();

  // Note: setValue = Insert in the cell the date when this row was modified
  if (userCell.Value == null) {
    userCell.setValue(user); 
    dateCell.setValue(inputdate)
  } 

}

我的主要问题是:

  • 我不需要最后一个修饰符,而是首先在单元格上输入信息的人。因此,我尝试了最后一个IF(如果应该有最后一个修改器电子邮件的单元格为空,这意味着之前没有人更改过该行,因此代码应该在userCell上添加用户),尽管它不起作用因为每次更改都会忽略验证。

  • 我还想补充说,只有在添加值时才会发生事件,如果删除它们,则不会发生任何事情。 (到目前为止,即使我删除了单元格,也算作修改)

  • 大多数工作表都受到保护,以避免人们意外删除某些公式,因此此代码更改的单元格也受到保护。有没有办法让代码绕过细胞保护?

请帮助我确定我做错了什么,并希望我能完美地完成这项工作!谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

如果要在删除单元格时阻止脚本触发,请尝试:

var editedCell = SpreadsheetApp.getActiveSheet().getRange(e.range.getRow(), e.range.getColumn());
if (editedCell == "") {
    return;
}

我会将Session.getEffectiveUser()更改为session.getActiveUser()。

最后一个if语句是不必要的。您希望识别最近编辑该字段的人员以及日期。