【问题标题】:Auto timestamp when editing column编辑列时自动时间戳
【发布时间】:2017-09-11 18:28:32
【问题描述】:

尝试向我的电子表格添加自动时间戳。任何时候在“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);
  }
}

【问题讨论】:

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


    【解决方案1】:
    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);
        }
      }
    }
    

    【讨论】:

    • 由于某种原因,我收到一条错误消息,说它无法读取属性“source”
    • 您不能手动运行这些函数,您必须使用触发器运行。如果您手动运行它们,则事件对象不会提供 event.source 和 event.range。所以不要手动运行这些,而是​​编辑适当的范围以查看它是否有效。我想你已经知道了,因为你已经有了这个功能。
    • 我明白了。我刚刚添加了一个触发器。触发器正在编辑,来自电子表格,正在编辑。我保存了函数并转到电子表格。当我编辑 PM 状态列中的内容时,它仍然没有在“日期​​更新”列中生成时间戳。
    • 应该有一个“(”,你目前有 =="All Leads")
    • if(sheet.getName()=="All Leads") { 这看起来对我来说是正确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    相关资源
    最近更新 更多