【问题标题】:Add timestamp to named column in Google Spreadsheet onEdit script将时间戳添加到 Google 电子表格 onEdit 脚本中的命名列
【发布时间】:2013-05-09 13:25:54
【问题描述】:

我试图弄清楚如何在 Google 电子表格脚本中检索具有特定名称的列的索引。

我正在开发一个自定义的 Google 脚本,它会在编辑电子表格时自动将时间戳添加到电子表格中。当前版本成功将时间戳添加到活动单元格行的最后一列。

我想创建此脚本的新版本,通过使用特定列名将时间戳添加到特别指定的列。例如,我想在我的电子表格中创建一个名为“上次更新”的列,并且我希望脚本检测该列的索引并自动将时间戳添加到该列,而不是行中的最后一列。

这对我来说会更好,因为我可以将时间戳列放在我想要的任何位置,而不必担心脚本会意外覆盖任何重要的内容。

我当前的脚本如下所示:

function onEdit(event)
{ 
  var timezone = "GMT-4";
  var timestamp_format = "yyyy-MM-dd HH:mm:ss";
  var sheet = event.source.getActiveSheet();

  // note: actRng = the cell being updated
  var actRng = event.source.getActiveRange();
  var index = actRng.getRowIndex();
  var cindex = actRng.getColumnIndex();

  // Here is where I want to use a named column's index instead of the active row's last column.
  var dateCol = sheet.getLastColumn();
  //var dateCol = sheet.getColumnIndexByName('Last Updated');

  var lastCell = sheet.getRange(index,dateCol);
  var date = Utilities.formatDate(new Date(), timezone, timestamp_format);

  lastCell.setValue(date);
}

【问题讨论】:

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


    【解决方案1】:

    您可以获取标题行中的值,并使用 indexOf() 在这些值中搜索所需的标题。

    function onEdit(event)
    { 
      var timezone = "GMT-4";
      var timestamp_format = "yyyy-MM-dd HH:mm:ss";
      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);
      }
    }
    

    【讨论】:

    • 感谢亚当的快速回复!我现在正在测试这个。 :)
    • 完美运行!谢谢!!
    【解决方案2】:

    这比我想象的要容易!最后两个括号之间:

    var dateCol = headers[0].indexOf('Updated By');
    
      if (dateCol > -1 && index > 1) { // only timestamp if 'Updated By' header exists, but not in the header row itself!
        var cell = sheet.getRange(index, dateCol + 1);
        var Who = Session.getActiveUser();
        cell.setValue(Who);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      • 2012-12-04
      相关资源
      最近更新 更多