How to create timestamp on multiple columns in GSheet

Am havong some trouble creating a script to automate timestamp on GSheet. I have 2 columns - AD & AE, that I want it to have the date timestamp for when column L and AA are updated. Have tried the following script but doesn't seem to work.

function onEdit(e) {

  addTimestamp(e);

}

function addTimestamp(e){

  var startRow = 3;
  var targetColumn = 12;
  var targetColumn2 = 27;
  var ws = "Brand List";

  var row = e.range.getRow();
  var col = e.range.getColumn();
  
  if (col === targetColumn && row >= startRow && e.source.getActiveSheet().getName() === ws) {

    var currentDate = new Date();
    e.source.getActiveSheet().getRange(row,30).setValue(currentDate)

  }

  if (col === targetColumn2 && row >= startRow && e.source.getActiveSheet().getName() === ws) {

    var currentDate = new Date();
    e.source.getActiveSheet().getRange(row,31).setValue(currentDate)

  }
}

Answers 1

  • Your script is working fine, but it seems that you're getting an error saying TypeError: Cannot read property 'range' of undefined.

    This happens because the script is using a trigger to execute the function onEdit() whenever the spreadsheet is edited. When executed, this trigger will pass an event object (e) as an argument to the function, which includes data such as the cell that was edited.

    However, this event object is only passed if the sheet is edited, which doesn't happen if you run the function from the script editor. So, to make it work, you need to edit the sheet as you'd do when using the script.

    If you actually want to test it separately, you'd need to explicitly create this event object and pass it to the onEdit() function: How can I test a trigger function in GAS?


Related Articles