In your case, I think that when maxRows-lastRow is 0 or less than 0, such error occurs. So please confirm whether there are the values to the bottom row of the sheet. If there are not values to the bottom row of the sheet, can you provide the sample Spreadsheet for replicating your issue? I would like to confirm it.
As a modification point for avoiding the error, how about the following modification?
From:
sh.deleteRows(lastRow+1, maxRows-lastRow);
To:
if (maxRows-lastRow > 0) {
sh.deleteRows(lastRow+1, maxRows-lastRow);
}
Other pattern:
Or, how about removing the empty rows using the data region from the 1st row as follows?
function removeEmptyRows(){
var sh = SpreadsheetApp.getActiveSheet();
var lastRowOfDataRegion = sh.getRange("1:1").getDataRegion(SpreadsheetApp.Dimension.ROWS).getLastRow();
var maxRows = sh.getMaxRows();
if (maxRows-lastRowOfDataRegion > 0) {
sh.deleteRows(lastRowOfDataRegion+1, maxRows-lastRowOfDataRegion);
}
}
Reference:
If I misunderstood your question, I apologize.