I'm struggling to understand an issue I'm having with row indexes being out of bounds.
Using Apps Script I'm copying a range from one sheet to another. The sheet that is being copied to originally contains one empty row, and then I am copying two rows of data to it - this works fine.
I then am trying to copy the row heights from the source sheet to the destination sheet and this is where I run into the issue. The first row works fine but then when it gets to the 2nd row it gives me an out of bounds error. If I change the destination sheet so that it starts off with 2 empty rows then I do not get this error.
I also do not get the error if I first run the copy function and then separately run the change row height function after.
To me it seems like Apps Script is storing the destination sheet before the additional row is added and then when I try to change the height of the 2nd row it thinks it doesn't exist? Does anyone know a way around this.
What's also odd is if I run getLastRow() on the destination sheet right before changing the row heights it returns 2, so somewhere it knows there are 2 rows.
Here is my function that copies a named range and then the row heights:
const ss = SpreadsheetApp.getActiveSpreadsheet();
const namedRanges = [['namedRange', 24, 2]] //Range name, number of columns, number of rows
function copyRange(sheetName, rangeName, destRow, destCol) {
const sourceRange = ss.getRangeByName(rangeName);
const sourceSheet = sourceRange.getSheet();
const destSheet = ss.getSheetByName(sheetName);
for (let i = 0; i < namedRanges.length; i++) {
if (namedRanges[i][0] === rangeName) {
var rangeIndex = i;
break;
}
}
const destRange = destSheet.getRange(destRow, destCol, namedRanges[rangeIndex][2] - 1, namedRanges[rangeIndex][1] - 1);
sourceRange.copyTo(destRange)
for (let i = 0; i < namedRanges[rangeIndex][2]; i++) {
let row = sourceRange.getRow() + i;
let height = sourceSheet.getRowHeight(row);
destSheet.setRowHeight(destRow + i, height);
}
}