Skip to main content
A newer version of this page is available. .

How to: Freeze and Unfreeze Rows and Columns

  • 2 minutes to read
static void FreezePanes(SpreadsheetControl control)
{
    //Access the active worksheet.
    Worksheet worksheet = control.Document.Worksheets.ActiveWorksheet;

    // Access the cell range that is currently visible.
    Range visibleRange = control.VisibleRange;

    // Access the active cell. 
    Cell activeCell = control.ActiveCell;

    int rowOffset = activeCell.RowIndex - visibleRange.TopRowIndex - 1;
    int columnOffset = activeCell.ColumnIndex - visibleRange.LeftColumnIndex - 1;

    // If the active cell is outside the visible range of cells, no rows and columns are frozen.
    if (!visibleRange.IsIntersecting(activeCell))
    {
        return;
    }

    if (activeCell.ColumnIndex == visibleRange.LeftColumnIndex)
    {
        // If the active cell matches the top left visible cell, no rows and columns are frozen.
        if (activeCell.RowIndex == visibleRange.TopRowIndex) { return; }
        else
            // Freeze visible rows above the active cell if it is located in the leftmost visible column.
            worksheet.FreezeRows(rowOffset, visibleRange);
    }

    else if (activeCell.RowIndex == visibleRange.TopRowIndex)
    {
        // Freeze visible columns to the left of the active cell if it is located in the topmost visible row.
        worksheet.FreezeColumns(columnOffset, visibleRange);
    }

    else
    {
        // Freeze both rows and columns above and to the left of the active cell.
        worksheet.FreezePanes(rowOffset, columnOffset, visibleRange);
    }
}