Google Sheet: TypeError: Cannot read property 'range' of undefined

Viewed 87

I am trying to use a AutoSort Script to sort data using Column CY on addition of any new row

function autoSort(e) {
  const row = e.range.getRow()
  const column = e.range.getColumn()
  const ss = e.source
  const currentSheet = ss.getActiveSheet()
  const currentSheetName = currentSheet.getSheetName()

  if(!(currentSheetName === "Final Data" && column ===103 && row >=2)) return
 
  const range = currentSheet.getRange(2,1,currentSheet.getLastRow()-1,103)

  range.sort({column: 103, ascending: false})

}
function onEdit(e) {
  autoSort(e)
}

I get an error on running the script as follows TypeError: Cannot read property 'range' of undefined

What exactly is going wrong? Please guide!

1 Answers

This is due to ss = e.source. Try

function autoSort(e) {
  const row = e.range.getRow()
  const column = e.range.getColumn()
  //const ss = e.source
  const currentSheet = e.source.getActiveSheet()
  const currentSheetName = currentSheet.getSheetName()

  if(!(currentSheetName === "Final Data" && column ===1 && row >=2)) return
 
  var range = currentSheet.getRange(2,1,currentSheet.getLastRow()-1,103)

  range.sort({column: 103, ascending: false})

}
function onEdit(e) {
  autoSort(e)
}
Related