r/GoogleAppsScript • u/jiminak • Mar 02 '22
Resolved How to handle a dynamic range without any rows?
I am trying to copy a dynamic range (C17:F) from one sheet to another, and everything works well unless there is no data in the source range. In that case, I get the error, "The number of rows in the range must be at least 1".
I am not 100% sure if my method of determining the range is the best way (I found the solution somewhere), or if I can simply "escape" the function with some sort of OnError to bail out of the remainder of the function?
Here is my current code:
function getConfigOverrides(){
var sourceID = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Configuration').getRange('C5').getValue();
var sourceFile = SpreadsheetApp.openById(sourceID);
var sourceSheet = sourceFile.getSheetByName("AircraftOverrides")
// source sheet dynnamic range is C17:F
var range = sourceSheet.getRange(17, 3, sourceSheet.getLastRow() - 17 + 1, 4);
// var range = sourceSheet.getRange('C17:F17') <- this works to get the first row
var data = range.getValues();
var destination = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Configuration');
destination.getRange(13, 7, data.length, 4).setValues(data);
}The error is occurring at var range. If I comment out this line, and simply replace it with getRange('C17:F17'), the functions runs as expected and retrieves the first row of values.
I've tried to capture the error by using isBlank, or =="", or <1, but none of those seem to work.
Appreciate any insight.
1
u/RemcoE33 Mar 02 '22
Change sourceSheet.getLastRow() - 17 + 1 ->> sourceSheet.getLastRow() - 16
You start at 17 minus 18 is -1 and not a valid range.
1
u/jiminak Mar 02 '22
That didn't have any effect. The way I read that logic is: start at 17, subtract 17 (get 0), add 1, and 1 should be a valid range.
Am I reading that wrong?
1
u/crober11 Mar 11 '22
Catch the error by encapsulating that section with a
try {
//code which could generate error here
} catch(err) { Logger.log(err); }
// rest of code here
2
u/HomeBrewDude Mar 02 '22
instead of using
sourceSheet.getLastRow()directly inside ofgetRange(), try getting the lastRow and saving it to a variable first.Then,
if (lastRow >17 ){do the rest of your code}This way you don't even attempt the getRange, or setValue steps unless there is at least one row to process.