【发布时间】:2017-10-23 13:11:03
【问题描述】:
我需要在 Excel 中动态冻结标题行,因为我正在使用的工作表有几个很大的表,如果它们位于同一个工作表上,则更容易理解。
但是在无休止地搜索之后我找不到解决方案,因为没有滚动事件并且滚动不会改变活动单元格。
谢天谢地,我想出了一个解决办法。
【问题讨论】:
标签: excel excel-formula vba
我需要在 Excel 中动态冻结标题行,因为我正在使用的工作表有几个很大的表,如果它们位于同一个工作表上,则更容易理解。
但是在无休止地搜索之后我找不到解决方案,因为没有滚动事件并且滚动不会改变活动单元格。
谢天谢地,我想出了一个解决办法。
【问题讨论】:
标签: excel excel-formula vba
在搜索了如何识别正在运行的活动窗口中的第一个可见行之后,我能够为我的困境提出一个可接受的解决方案
MSDN: Identify First Visible Row of Active Window
然后我能够获取该代码并将其转换为可以与仅在需要冻结行的工作表上激活的 Timer 事件结合使用的函数。
工作表代码:
Private Sub Worksheet_Activate()
StartFreezePaneTimeRefresh
End Sub
Private Sub Worksheet_Deactivate()
StopFreezePaneTimeRefresh
End Sub
动态冻结窗格模块代码:
Private RefreshTime
Sub SetFreezePane()
'Check if correct worksheet is active
If ActiveWorkbook.ActiveSheet.Name = "Data" Then
If IdentifyTopVisibleRow < 227 Then
'Check if Frozen Row is the same as the Range to be Copied
If Range("A1") <> Range("AN1") Then
'Copy New Headers for Frozen Row
Range("AN1:BU1").Copy
Range("A1").PasteSpecial xlPasteValues
End If
ElseIf IdentifyTopVisibleRow > 227 Then
'Check if Frozen Row is the same as the Range to be Copied
If Range("A1") <> Range("AN2") Then
'Copy New Headers for Frozen Row
Range("AN2:BU2").Copy
Range("A1").PasteSpecial xlPasteValues
End If
End If
Else
StopFreezePaneTimeRefresh
End If
End Sub
Sub StartFreezePaneTimeRefresh()
Call SetFreezePane
RefreshTime = Now + TimeValue("00:00:01")
Application.OnTime RefreshTime, "StartFreezePaneTimeRefresh"
End Sub
Sub StopFreezePaneTimeRefresh()
On Error Resume Next
Application.OnTime RefreshTime, "StartFreezePaneTimeRefresh", , False
End Sub
Public Function IdentifyTopVisibleRow() As Long
'This code was found on MSDN at
'https://social.msdn.microsoft.com/Forums/en-US/a6cff632-e123-4190-8556-d9f48af8fe9a/identify-first-visible-row-of-scrolled-excel-worksheet?forum=isvvba
Dim lngTopRow As Long ' top row
Dim lngNumRows As Long ' number of visible rows
Dim lngLeftCol As Long ' leftmost column
Dim lngNumCols As Long ' number of visible columns
With ActiveWindow.VisibleRange
lngTopRow = .Row
lngNumRows = .Rows.Count
lngLeftCol = .Column
lngNumCols = .Columns.Count
End With
IdentifyTopVisibleRow = lngTopRow
End Function
代码首先检查正确的工作表是否处于活动状态,如果是,则每秒检查最顶部的可见行。
如果顶行大于或小于每个表的开始行,则它将检查第一个标题是否已设置,以防止它一遍又一遍地更改值。
如果不是,它会根据用户在工作簿中的位置更改 Frozen Row 值。
注意事项:
更改延迟了 1 秒,但这对于我这样做的目的是可以接受的。
我使用它的工作表只是视图,因为如果您知道如何在不更改选择的情况下设置第一行值,这将不断地将焦点转移到第一行,这将使这项工作变得更好。
【讨论】: