Search code examples
javascriptgoogle-sheetsgoogle-apps-scripttriggers

Function onEdit(e) works only for single cell edit


I am using the below script to add a timestamp for every edit in Column A, however if i copied a range of cells and pasted to Column A, the script will work on the first cell only. Is there a way to capture the timestamp for all the edited cells?

function onEdit(e) {

  var startRow=3;
  var targetColumn=1;
  var ws="Master Data";
  var row = e.range.getRow();
  var col = e.range.getColumn();
  
  if (col === targetColumn && row >= startRow && e.source.getActiveSheet().getName() === ws ){ 
    var currentDate = new Date();
    
    if(e.source.getActiveSheet().getRange(row,1).getValue() !== ""){
      if(e.source.getActiveSheet().getRange(row,2).getValue() == ""){
        e.source.getActiveSheet().getRange(row,2).setValue(currentDate);
      }    
    }
  }
}

Solution

  • function onEdit(e) {
      //e.source.toast('Entry');
      const sh=e.range.getSheet();
      if (e.range.columnStart==1 && e.range.rowStart>2 && sh.getName()=="Master Data") { 
        var ts = Utilities.formatDate(new Date(),Session.getScriptTimeZone(),"E MMM dd, yyyy HH:mm:ss");
        var vs=sh.getRange(e.range.rowStart,e.range.columnStart,e.range.rowEnd-e.range.rowStart+1,2).getValues();
        vs.forEach(function(r,i){
          if(r[0].toString().length!=0 && !r[1]) {
            sh.getRange(i+e.range.rowStart,2).setValue(ts);
          }
        });
      }
    }
    

    onEdit Event Object