编辑列时的自动时间戳

时间:2017-09-11 18:28:32

标签: google-apps-script google-sheets timestamp

尝试在电子表格中添加自动时间戳。无论何时在列“PM状态”中编辑数据,我都希望在“日期更新”列中显示自动时间戳。

function onEdit(event)
{ 
  var timezone = "ET";
  var timestamp_format = "MM-dd-yyyy"; // Timestamp Format. 
  var updateColName = "PM Status";
  var timeStampColName = "Date Update";
  var sheet = event.source.getSheetByName('All Leads'); //Name of the sheet where you want to run this script.


  var actRng = event.source.getActiveRange();
  var editColumn = actRng.getColumn();
  var index = actRng.getRowIndex();
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
  var dateCol = headers[0].indexOf(timeStampColName);
  var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
  if (dateCol > -1 && index > 1 && editColumn == updateCol) { // 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);
  }
}

1 个答案:

答案 0 :(得分:0)

function onEdit(event)
{ 
  var sheet=event.source.getActiveSheet();
  if(sheet.getName()=="All Leads")
  {
    var timezone = "ET";
    var timestamp_format = "MM-dd-yyyy HH:mm:ss"; // Timestamp Format. 
    var updateColName = "PM Status";
    var timeStampColName = "Date Update";
    var actRng = event.range;
    var editColumn = actRng.getColumn();
    var actRow = actRng.getRow();
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
    var dateCol = headers[0].indexOf(timeStampColName) + 1;
    var updateCol = headers[0].indexOf(updateColName) + 1; 
    if (dateCol > 0 && actRow > 1 && editColumn == updateCol) 
    {
      var cell = sheet.getRange(actRow, dateCol);
      var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
      cell.setValue(date);
    }
  }
}