Luk*_*one 4 javascript timestamp google-sheets google-apps-script
我正在尝试弄清楚如何在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);
}
Run Code Online (Sandbox Code Playgroud)
Ada*_*amL 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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5566 次 |
| 最近记录: |