简体   繁体   中英

Google Apps Scripts - Add Timestamp to multiple cells when updated

I'm trying to update the code in this tutorial to add a timestamp when I update a cell. So far it's working for the first cell but not all of them when copying values to a whole range.

Could someone take a look and help adapt this so that all cells are updated with a timestamp rather than just the first?

Thanks!

 function onEdit(event) { var timezone = "GMT+1"; var timestamp_format = "dd/MM/yyyy HH:mm:ss"; // Timestamp Format. var updateColName = "Message"; var timeStampColName = "Timestamp"; var sheet = event.source.getSheetByName('Sheet1'); //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); } }

You are using getRange(row, column) which retrieves a single cell.

The following lines are setting only first cell's value in the range when you copy paste multiple values or pull down a cell:

var cell = sheet.getRange(index, dateCol + 1);

cell.setValue(date);

Use getRange(row, column, numRows) to retrieve a range with multiple rows. If we change it with:

sheet.getRange (index, dateCol + 1, numRows)

it will change all cells in this range.

Try this please.

function onEdit(event) { 
  var timezone = "GMT+1";
  var timestamp_format = "dd/MM/yyyy HH:mm:ss"; // Timestamp Format. 
  var updateColName = "Message";
  var timeStampColName = "Timestamp";
  var sheet = event.source.getSheetByName('Sheet1'); //Name of the sheet where you want to run this script.    
  var actRng = event.range;
  var editColumn = actRng.getColumn();
  var index = actRng.getRowIndex();
  var numRows = actRng.getNumRows();
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
  var dateCol = headers[0].indexOf(timeStampColName);
  var updateCol = headers[0].indexOf(updateColName)+1; 
  if (dateCol > -1 && index > 1 && editColumn == updateCol) { 
    var range = sheet.getRange(index, dateCol + 1,numRows);
    var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
    range.setValue(date);
  }
}

Reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM