'How to get the last 1000 rows dynamically and sort them using GAS?

I'm trying to get this to sort only the last 1000 rows, dynamically. This is the code I'm using:

function sort(e){
const formRespSheet = e.source.getSheetByName('Form Responses 1');
let lr = formRespSheet.getLastRow()-1;
let firstRow = 2
 if (lr > 1000) {
   firstRow = lr - 1000;
 }
 Logger.log('First Row: ' + firstRow)
 Logger.log('Last Row: ' + lr)
 formRespSheet.getRange(firstRow, 1, lr, 16).sort(14);
}

It gives me the correct firstRow and lr, but it also throws The coordinates of the range are outside the dimensions of the sheet, besides running forever (15 sec).

Could anyone help me find the flaw here (besides myself)?

Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source