Search code examples
arraysfor-loopgoogle-apps-scriptgoogle-sheetsoff-by-one

Freezing rows in Sheets with Google Apps throws type error


I'm trying to use GAS to freeze the top row of each sheet. It works, freezes the desired rows, but returns an error:

"TypeError: cannot call method setFrozenRows" of undefined (line6, file "freezeLabelRows")

According to Google documentation, the syntax is correct. I'm running the script from the code editor attached to the sheet where I'm developing the app. I tried a number (1) where numRowsFr is now; that was a workaround I used to dodge this error.

function rowFreeze() {
  var numSheets = SpreadsheetApp.getActiveSpreadsheet().getNumSheets();
   for(var i = 0; i <= numSheets; i++) {
     var frSheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[i];
     var numRowsFr = 1;
     frSheet.setFrozenRows(numRowsFr);
   }
}

As I said, the code works to freeze the desired row on each sheet, but returns an error. I'd like to get the rest of this app in place to upgrade for current users.


Solution

  • Issue:

    • Array index starts at 0 and ends at length of array -1. You're looping after the end of the array(sheets array) when you use <=numSheets as the loop condition. After the last sheet, frsheet will be undefined and undefined doesn't have a setFrozenRows method as it's not a sheet type.

    Solution:

    • Loop only till the end of the array.

    Snippet:

    i <= numSheets - 1;
    

    or

    i < numSheets;