Fill a cell with timestamp of another cell edit ONLY if another cell is not blank

限于喜欢 提交于 2021-01-29 16:28:21

问题


I need fill a cell in google spreedsheet with the timestamp of the another cell's edition. But this timestamp should be show only if the another cell is edited with some content, not with erase the cell.

I have been try with this code, but the timestamp is shown also if i erase the another cell.

function onEdit(e) 
{
  if ([8].indexOf(e.range.columnStart) != -1) 
  {
    if ([8].indexOf(e.range.columnStart) === '') 
    {
      e.range.offset(0, -7).setValue('0');
    }
    else
     e.range.offset(0, -7).setValue(new Date()).setNumberFormat("yyMMdd HH:mm:ss");
  }      
}

回答1:


function onEdit(e) {
  // Make sure our edit is a single cell in the H column
  // and that our edit has a value
  if(e.range.columnStart === 8 && e.value.length) {
    e.range.offset(0, -7).setValue(new Date()).setNumberFormat("yyMMdd HH:mm:ss");
  } else {
    e.range.offset(0, -7).setValue('0');
  }
}

The updated conditional now does 3 checks:

  • e.range.columnStart === 8 ensures we are starting in the H column
  • e.value.length ensures that

    1. our edit is not blank
    2. the edit only affected a single cell as e.value is not available when multiple cells are edited (see: Edit section)

[8].indexOf(e.range.columnStart) === '' I removed this as indexOf cannot return an empty string. It would always evaluate to false and was the reason for all edits updating the timestamp.

EDIT: Documentation for columnStart, still looking for an official google source. e.range.getHeight() === 1 && e.range.getWidth() === 1 && e.range.getColumn() === 8 is a verified alternative.



来源:https://stackoverflow.com/questions/53825225/fill-a-cell-with-timestamp-of-another-cell-edit-only-if-another-cell-is-not-blan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!