I'm trying to figure out how to retrieve the index of a column with a specific name in a Google Spreadsheet script.
I'm working on a custom Google Script that automatically adds timestamps to a spreadsheet when it is edited. The current version successfully adds the timestamp to the last column of the active cell's row.
I want to create a new version of this script that adds the timestamp to a specially designated column by using a specific column name. For example, I want to create a column in my spreadsheet named "Last Updated," and I want the script to detect the index of that column and automatically add the timestamps to it instead of the last column in the row.
This would work better for me, because I could then place the timestamp column wherever I wanted and not have to worry about the script overriding anything important by accident.
My current script looks like this:
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);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…