4

我想弄清楚如何检索Google Spreadsheet脚本中具有特定名称的列的索引。将时间戳添加到Google Spreadsheet onEdit脚本中的指定列

我正在开发自定义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); 
} 

回答

11

你可以让你的标题行的值,然后搜索使用的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); 
    } 
} 
+0

感谢您的快速回复,亚当!我现在正在测试这个。 :) – 2013-05-09 21:11:33

+0

完美的作品!谢谢!! – 2013-05-09 21:30:51