添加时间戳到指定的列在谷歌电子表格onEdit脚本(Add timestamp to named c

2019-09-02 09:37发布

我试图找出如何在谷歌的电子表格脚本特定名称检索列的索引。

我工作的一个自定义谷歌脚本当编辑的自动添加时间戳到电子表格。 当前版本成功添加时间戳活动单元格的行的最后一列。

我想创建这个脚本,通过使用特定的列名添加时间戳到专门指定的列的新版本。 例如,我要建立在我的电子表格命名一列“最近更新”,而我希望脚本检测列的索引,并自动时间戳添加到它,而不是该行的最后一列的。

这将更好地工作,对我来说,因为我可以再放置时间戳列,无论我想要的,不必担心剧本重写任何偶然重要。

我现在的剧本是这样的:

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

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


文章来源: Add timestamp to named column in Google Spreadsheet onEdit script