我使用Access数据库创建Excel文件,并在其中格式化excel文件。我想用更简化的代码冻结excel文件中的第一行。
效果很好:
wksExcel.Range("A2").Select
wbkExcel.Application.ActiveWindow.FreezePanes = True
但是可以只用一行这样的代码来做到这一点:
wksExcel.Range("A2").Application.ActiveWindow.FreezePanes = True
答案 0 :(得分:1)
仅使用一个命令就无法做到这一点,因为Range对象不能以这种方式与ActiveWindow对象结合使用。如果您使用的是用于在不选择单元格的情况下拆分工作表的代码,则可以使用以下代码:
With ActiveWindow
.SplitColumn = 0
.SplitRow = 1
.FreezePanes = True
End With
答案 1 :(得分:0)
此通用功能将冻结Excel中的工作表窗格,而无需进行选择。
您可以将其缩减为您的特定用途。
' 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