'Google Apps-Scripts error "The number of rows in the range must be at least 1."

So I have been having several problems with an apps-script that has until now, been working as it should. When I duplicated a sheet, it is now broken. There have been various errors through the different sheets. This one in particular is throwing me for a loop. I keep getting an error of "The number of rows in the range must be at least 1," when running "CustomImport." (it works on OnOpen). The purpose of the script is to grab data via a sheet url/name/range that is specified in a "links" sheet in the google sheets and the output on to a "master" spreadsheet. The error is at: "outputSheet.getRange(4,1,outputSheet.getLastRow(),outputSheet.getLastColumn()).clearContent();"

As I am not a programmer, I have zero idea where I am supposed to start. This was a custom built script by someone that I cannot find anyone with a similar problem. I am including the entire code so it can be seen. I also have a spreadsheet that is open acces/editing.

function onOpen(e) {
  SpreadsheetApp.getUi().createMenu('IMPORT')
    .addItem('Update data', 'customImport')
    .addToUi();
}

function customImport() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const inputSheet = ss.getSheetByName('Links');
  const outputSheet = ss.getSheetByName('Year-2022 Sessions');
  const columnNumberToFilter = 1

  const inputValues = inputSheet.getRange(2, 1, inputSheet.getLastRow() - 1, 3).getValues();
  let output = [] ;
  
  inputValues.forEach(entrie => {
  const [url, sheetname, range] = entrie;
  const sheetRange = SpreadsheetApp.openByUrl(url)
    .getSheetByName(sheetname)
    .getRange(range)
  let data = sheetRange.getValues();
    output = output.concat(data);
  })
output = output.filter(row => row[columnNumberToFilter - 1] != "") ; 

outputSheet.getRange(4,1,outputSheet.getLastRow(), outputSheet.getLastColumn()).clearContent();
outputSheet.getRange(4, 1, output.length, output[0].length).setValues(output).sort([6,4])
}


Solution 1:[1]

When the error like The number of rows in the range must be at least 1 occurs at outputSheet.getRange(4,1,outputSheet.getLastRow(),outputSheet.getLastColumn()).clearContent();, I think that in that case, outputSheet.getLastRow() might be 0. And, in your situation, I think that outputSheet.getLastRow() might be outputSheet.getLastRow() - 3. If my understanding is correct, how about the following modification?

From:

outputSheet.getRange(4,1,outputSheet.getLastRow(), outputSheet.getLastColumn()).clearContent();

To:

var lastRow = outputSheet.getLastRow();
if (lastRow > 0) {
  outputSheet.getRange(4,1,lastRow - 3, outputSheet.getLastColumn()).clearContent();
}

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Tanaike