How to Freeze Rows and Columns in Google Sheets Using Apps Script

Let’s see how to freeze rows and columns in Google Sheets using Apps Script. You can use logic in code to dynamically freeze/unfreeze rows and columns as required.

Example 1: Freezing Rows and Columns Using the Built-in Function

To freeze rows and columns in Google Sheets using Apps Script, you can use the built-in setFrozenRows() and setFrozenColumns() methods. Here’s an example code snippet:

function freezeCells() {
  var sheet = SpreadsheetApp.getActiveSheet();
  sheet.setFrozenRows(1);
  sheet.setFrozenColumns(2);
}

In this code, we first get the active sheet using getActiveSheet(). We then use the setFrozenRows() method to freeze the first row using 1 as the row index, and the setFrozenColumns() method to freeze the first two columns using 2 as the column index.

Example 2: Freezing Rows and Columns Using the Range Method

To freeze rows and columns in Google Sheets using Apps Script, you can also use the setFrozenRows() and setFrozenColumns() methods with the getRange() method to specify a specific range of rows and columns to freeze. Here’s an example code snippet:

function freezeCells() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getRange("A1:C3");
  range.activate();
  sheet.setFrozenRows(range.getNumRows());
  sheet.setFrozenColumns(range.getNumColumns());
}

In this code, we first get the active sheet using getActiveSheet(). We then get a specific range of cells using getRange(), and activate the range using activate(). We then use the setFrozenRows() method to freeze the number of rows in the range using range.getNumRows(), and the setFrozenColumns() method to freeze the number of columns in the range using range.getNumColumns().