如何删除以前由Google表格中的简单触发器onEdit()的事件对象(e)设置的单元格值?

时间:2019-06-04 12:48:35

标签: google-apps-script google-sheets

在我之前的帖子之后,还有一个问题是在How to automatically add the ordinal number of an entry based on timstamp to a row when non-contiguous new data is added to it in Google Sheets?此处删除(e)事件对象预先设置的值

在当前情况下如何使用变量或更简单的方法获得以下代码的结果?

在@TheMaster的大力帮助下,@ Tanaike的更多帮助google script detect empty cell after edit 我找到了一种解决方法,可以删除先前由(e)事件对象预先设置的值。

这是我发现的东西:

function onEdit(e) {
  var rg = e.range,
    row = rg.rowStart,
    col = rg.columnStart,
    sht = rg.getSheet();

  //exit code
  if (col !== 2 || sht.getName() !== 'Sheet1' || row === 1) return;

  // When the empty cell is edited, this becomes true.
  if ((e.value != null) && (e.oldValue == null)){ 
  //Calculate max value and add 1
  rg.offset(0, -1, 1, 1).setValue(//setvalue in colA
    rg
      .offset(2 - row, -1, sht.getLastRow() - 1, 1) //get all of colA
      .getValues()
      .reduce(function(acc, curr) {//get max of colA
        return Math.max(acc, Number(curr[0]));
      }, 0) + 1
  );
  }

  // When the value of cell with a value is removed, this becomes true.
  else if ((e.value == null) && (e.oldValue == null)) { 
  rg.offset(0, -1, 1, 1).setValue(//setvalue in colA
    rg
      .offset(2 - row, -1, sht.getLastRow() - 1, 1) //get all of colA
      .getValues()
      .reduce(function(acc, curr) {//get max of colA
        return Math.max(acc, Number(curr[0]));
      }, 0)
  ).clearContent(); // If we delete cell
  }

}

实时结果:

https://i.imgur.com/jWd4Erz.gif

您会建议哪种更简单明了的方法来获得结果?

结果符合预期。但是有没有办法在下面的@TheMaster原始代码的上下文中使用变量来达到相同的结果?

@TheMaster link的原始代码:

function onEdit(e) {
  var rg = e.range,
    row = rg.rowStart,
    col = rg.columnStart,
    sht = rg.getSheet();

  //exit code
  if (col !== 2 || sht.getName() !== 'Sheet1' || row === 1) return;

  //Calculate max value and add 1
  rg.offset(0, -1, 1, 1).setValue(//setvalue in colA
    rg
      .offset(2 - row, -1, sht.getLastRow() - 1, 1) //get all of colA
      .getValues()
      .reduce(function(acc, curr) {//get max of colA
        return Math.max(acc, Number(curr[0]));
      }, 0) + 1
  );
}

非常感谢您的帮助和想法!

0 个答案:

没有答案