从特定列编辑时的时间戳

Timestamp on edit from a specific column

本文关键字:时间戳 编辑      更新时间:2023-09-26

我试图有一个时间戳使用谷歌表。我已经有了一个脚本,每次编辑表单时都会这样做。但是,我想要的是在更新特定列标头时应用时间戳。

我有一个名为"STATUS"的列,这是在列G.我只是想,只有当这个列被编辑时,它才会触发脚本在列L中记录一个时间戳,名为"LAST UPDATED"。

我正在使用的当前脚本是:

function onEdit(event)
{ 
  var timezone = "PST";
  var timestamp_format = "MM/dd/yyyy hh:mm:ss a zzz";
  var sheet = event.source.getActiveSheet();
  // note: actRng = the cell being updated
  var actRng = event.source.getActiveRange();
  var index = actRng.getRowIndex();
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
  var dateCol = headers[0].indexOf('LAST UPDATED');
  if (dateCol > -1 && index > 1) { // only timestamp if 'Last Updated' header exists, but not in the header row itself!
    var cell = sheet.getRange(index, dateCol + 1);
    var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
    cell.setValue(date);
  }
}

我也在这个论坛找到了脚本,但没有找到任何关于我上面的问题。

如有任何帮助,不胜感激。

谢谢

下面是我目前使用的脚本。我对JavaScript的了解非常有限,但它应该能满足您的要求。但是,我仍然难以获得IF返回空值的工作。所以请随时提供反馈。

然后格式化该列以包含日期/时间,但您可以轻松地适当地格式化脚本。

function onEdit() {
  var s = SpreadsheetApp.getActiveSheet();
  if( s.getName() == "Sheet1" ) { //checks that we're on the correct sheet
    var r = s.getActiveCell();
    if( r.getColumn() == 2 ) { //checks the column
      var nextCell = r.offset(0, -1);
      if(s.getActiveCell() == null) { //is empty?
        return nextCell.setValue(null) ;
      } 
      else {
        nextCell.setValue(new Date());
      }
    }
  }