将时间戳添加到Google Spreadsheet onEdit脚本中的命名列

时间:2013-05-09 13:25:55

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

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

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

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

这对我来说会更好,因为我可以将时间戳列放在我想要的任何地方,而不必担心脚本会覆盖任何重要的事情。

我当前的脚本如下所示:

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);
}

2 个答案:

答案 0 :(得分:12)

您可以在标题行中获取值,并使用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);
  }
}

答案 1 :(得分:0)

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

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);
  }
相关问题