javascriptarraysgoogle-apps-script

Error copying 2d array contents to Google Sheets column


In GAS, I have a 2d array that I have populated with data and after the function runs I want to be able to push that data into a single column in a Google Sheet. I keep getting an error that the number of rows in the data doesn't match the number of rows in the range. Looking for some extra eyes to tell me what I'm doing wrong.

var allExpensesStatus = [];
for (i = 0; i < somevar.length; i++)
{
   allExpensesStatus.push([i,"some text"]);
}

spreadsheet.getSheetByName("MySheet").getRange("H2:H" + allExpensesStatus.length).setValues(allExpensesStatus);

Solution

  • Since your range "H2:H" starts in row 2 you should add 1 to the ending row or length+1

    I notice each row has 2 elements so the range should be expanded to “H2:I”.

    spreadsheet.getSheetByName("MySheet").getRange("H2:I" + (allExpensesStatus.length+1)).setValues(allExpensesStatus);
    

    I always prefer to use this form of getRange. It's sure to fit the array size.

    spreadsheet.getSheetByName("MySheet").getRange(2,8,allExpensesStatus.length,allExpenseStatus[0].length).setValues(allExpensesStatus);