excel vba freeze pane without select

后端 未结 5 1346
情歌与酒
情歌与酒 2020-11-30 07:39

I have a VBA script in Excel that freezes the panes of an Excel worksheet, but I\'m curious to see if this is possible without first selecting a range. Here\'s by code now

5条回答
  •  生来不讨喜
    2020-11-30 08:19

    There are many things to get wrong about freezing panes. I add my own answer, so I will find it here, and won't have to reinvent it next time.

    Public Sub FreezePanesAt(rngDataTopLeft As Range)
        Dim wndCurrent As Window: For Each wndCurrent In rngDataTopLeft.Worksheet.Parent.Windows
            With wndCurrent
                .FreezePanes = False
                If Not ((rngDataTopLeft.Row = 1) And (rngDataTopLeft.Column = 1)) Then
                    .ScrollRow = 1
                    .ScrollColumn = 1
                    .SplitRow = rngDataTopLeft.Row - 1
                    .SplitColumn = rngDataTopLeft.Column - 1
                    .FreezePanes = True
                End If
            End With
        Next
    End Sub
    

    Example usage:

    FreezePanesAt ThisWorkbook.Worksheets("Sheet1").Range("B3")
    FreezePanesAt ThisWorkbook.Names("Header").RefersToRange
    
    • The input parameter is the top left cell of the bottom right pane; I think this is the most frequent use case: you know the range at which to split and don't care about which workbook / worksheet / window it is in
    • If the input parameter is in the first row / first cell but not A1, then there will be only two panes; A1 is a special case, however, Excel would split the window at center of the current view, I prevented this because I can't think of any case where this would be intended
    • It iterates through all Windows attached to the workbook / worksheet; indexing into Application.Windows (Windows(Thisworkbook.Name)) won't cause an error if you have more windows to the same workbook (the name would be "MyWorkbook:1"), or Excel attempted (which usually fails) to repair a workbook after a crash (the name would be "MyWorkbook [Repaired]")
    • It takes into consideration that panes may already be frozen and the user / another macro might have scrolled to a location in the workbook, and the top left cell in the window is not A1

提交回复
热议问题