我们在使用大量工作表时遇到了一些性能问题。特别是,三个操作似乎非常慢:插入行,删除行和撤消。
我一直在阅读有关优化的内容,并希望量化哪些更改确实有所作为。为此,我想设置一些VBA来跟踪上面列出的事件的已用时间,但我找不到任何钩子。
我想要像worksheet_change_start,worksheet_change_end这样的东西,但我还没有找到类似的东西。
我有一个“伟大”的想法,但它没有用。我以为我会做两个背靠背的插入行,在每个插入一个时间戳,然后计算差异......但是Excel会让我失望,并以某种方式将它们拼凑在一起。
提前感谢您的建议
注意:感谢目前为止的答案。我知道计时器功能,但我无法找到如何捕获我可以启动的事件,并结束一些用户行为的计时器,例如在用户插入行之前和之后。
答案 0 :(得分:2)
您可以使用下面的小宏来计算工作簿执行操作所需的时间
Dim t As Date
t = Now()
'your code for inserting new line here
MsgBox Format(Now() - t, "hh:mm:ss")
答案 1 :(得分:0)
您可以使用基本计时器类(来自之前的SO问题 - 参考tba)将其放入类模块(称为CTimer
)。这种方法的好处是可以重复使用。
Option Explicit
Private Type LARGE_INTEGER
lowpart As Long
highpart As Long
End Type
Private Declare Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As LARGE_INTEGER) As Long
Private Declare Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As LARGE_INTEGER) As Long
Private m_CounterStart As LARGE_INTEGER
Private m_CounterEnd As LARGE_INTEGER
Private m_crFrequency As Double
Private Const TWO_32 = 4294967296# ' = 256# * 256# * 256# * 256#
Private Function LI2Double(LI As LARGE_INTEGER) As Double
Dim Low As Double
Low = LI.lowpart
If Low < 0 Then
Low = Low + TWO_32
End If
LI2Double = LI.highpart * TWO_32 + Low
End Function
Private Sub Class_Initialize()
Dim PerfFrequency As LARGE_INTEGER
QueryPerformanceFrequency PerfFrequency
m_crFrequency = LI2Double(PerfFrequency)
End Sub
Public Sub StartCounter()
QueryPerformanceCounter m_CounterStart
End Sub
Property Get TimeElapsed() As Double
Dim crStart As Double
Dim crStop As Double
QueryPerformanceCounter m_CounterEnd
crStart = LI2Double(m_CounterStart)
crStop = LI2Double(m_CounterEnd)
TimeElapsed = 1000# * (crStop - crStart) / m_crFrequency
End Property
然后在普通代码模块中,您可以像这样使用它:
Sub test_time()
Dim time_this As New CTimer
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
time_this.StartCounter
ws.Rows("6:6").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
ws.Rows("8:8").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
MsgBox time_this.TimeElapsed
End Sub