I'm trying to use this code I adapted from http://www.internetgeeks.org/tech/add-timestamp-time-stamp-google-docs-spreadsheet/ to automatically timestamp cells upon entering question and answer text for a Google Sheets file. When I only use the code for one column it works, but when I duplicate and try to get it to work on two columns, it doesn't work.
function onEdit(event)
{
var timezone = "GMT-4";
var timestamp_format = "MM-dd-yyyy HH:mm:ss"; // Timestamp Format.
var updateColName = "Question/Comment";
var timeStampColName = "Date/Time Sent";
var sheet = event.source.getSheetByName('ArtsVision Questions/Comments'); //Name of the sheet where you want to run this script.
var actRng = event.source.getActiveRange();
var editColumn = actRng.getColumn();
var index = actRng.getRowIndex();
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
var dateCol = headers[0].indexOf(timeStampColName);
var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
if (dateCol > -1 && index > 1 && editColumn == updateCol) { // 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);
}
}
function onEdit(event)
{
var timezone = "GMT-4";
var timestamp_format = "MM-dd-yyyy HH:mm:ss"; // Timestamp Format.
var updateColName = "Response";
var timeStampColName = "Date/Time Answered";
var sheet = event.source.getSheetByName('ArtsVision Questions/Comments'); //Name of the sheet where you want to run this script.
var actRng = event.source.getActiveRange();
var editColumn = actRng.getColumn();
var index = actRng.getRowIndex();
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
var dateCol = headers[0].indexOf(timeStampColName);
var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
if (dateCol > -1 && index > 1 && editColumn == updateCol) { // 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);
}
}
It doesn't work that way. You don't duplicate the onEdit trigger function and expect it to work all of a sudden. You have to understand the concepts of:
Having said that, I've edited your code and hope you review it so you can modify it according to your need:
Given that in this case we can be pretty confident that the the event.range will contain just the last cell edited (see https://developers.google.com/apps-script/guides/triggers/events) this should work:
If you protect the ranges in the sheet you don't want people to be able to edit (the headers, and the two timestamp columns) this should work ok.