如何用一行代码冻结第一行

How to freeze first row with one line of code

我使用 Access 数据库创建 Excel 文件,我还在其中格式化 excel 文件。我想用更简化的代码冻结 excel 文件中的第一行。

效果很好:

wksExcel.Range("A2").Select
wbkExcel.Application.ActiveWindow.FreezePanes = True

但是是否可以像这样只用一行代码就可以做到:

wksExcel.Range("A2").Application.ActiveWindow.FreezePanes = True

此通用函数将冻结 Excel 中没有 Select 的工作表窗格。

您可以根据自己的具体目的将其缩减。

' Freezes a worksheet pane top-left down to the top-left
' corner of the cell of RowIndex and ColumIndex.
'
' If RowIndex or ColumnIndex is less than 2 or omitted,
' only columns or rows respectively are frozen.
' If RowIndex and ColumnIndex are less than 2 or omitted,
' freezing of the worksheet is terminated.
'
' 2017-09-21. Gustav Brock, Cactus Data ApS, CPH.
'
Public Sub FreezeWorksheet( _
    ByVal Index As Variant, _
    Optional ByVal RowIndex As Long = 1, _
    Optional ByVal ColumnIndex As Long = 1)

    Const NoSplitIndex  As Long = 0

    Dim Freeze          As Boolean
    Dim CallIndex       As Long
    Dim ScreenUpdating  As Boolean

    ' Switching of the active window may happen, so
    ' disable screen updating while freezing is set.
    ScreenUpdating = Application.ScreenUpdating
    Application.ScreenUpdating = False
    DoEvents

    ' Record the index of the currently active worksheet.
    CallIndex = ThisWorkbook.ActiveSheet.Index

    ' Activate the worksheet to freeze.
    ThisWorkbook.Worksheets(Index).Activate

    ' Hide row and column numbers.
    ActiveWindow.DisplayHeadings = False
    ' Hide formulabar.
    Application.DisplayFormulaBar = False

    ' Determine wether to freeze or to terminate freezing.
    Freeze = (RowIndex > 1 Or ColumnIndex > 1)
    If Freeze Then
        ' Remove an already set split.
        If ActiveWindow.Split = True Then
            ActiveWindow.Split = False
        End If
        ' Avoid errors.
        If RowIndex < 1 Then
            RowIndex = 1
        End If
        If ColumnIndex < 1 Then
            ColumnIndex = 1
        End If
        ' Set coordinates and apply freezing.
        ActiveWindow.SplitRow = RowIndex - 1
        ActiveWindow.SplitColumn = ColumnIndex - 1
        ActiveWindow.FreezePanes = True
    Else
        ' Terminate split and freeze.
        ActiveWindow.SplitRow = NoSplitIndex
        ActiveWindow.SplitColumn = NoSplitIndex
        ActiveWindow.Split = False
    End If

    ' Return to the previously active worksheet.
    DoEvents
    ThisWorkbook.Worksheets(CallIndex).Activate
    ' Restore status of screen updating.
    Application.ScreenUpdating = ScreenUpdating

End Sub

您将无法仅使用一个命令来完成此操作,因为 Range 对象无法以这种方式与 ActiveWindow 对象组合。如果您在不选择单元格的情况下拆分 sheet 的代码,您可以使用这样的代码:

With ActiveWindow
    .SplitColumn = 0
    .SplitRow = 1
    .FreezePanes = True
End With