我正在尝试让VBA的GetTickCount工作,以便我可以看到代码的运行时间,但它不一定非常准确。
以下一些代码运行良好但我需要进行一些更改,但无法解决如何实现此目的。
#If Win64 Then
Public Declare PtrSafe Function GetTickCount Lib "kernel32" () As Long
#Else
Public Declare Function GetTickCount Lib "kernel32" () As Long
#End If
' Get first tickcount, start of code
t1 = GetTickCount
'Do stuff here
'#############
'#############
'#############
' Get second tickcount, end of code
t2 = GetTickCount
' Compare tickcounts
If t2 < t1 Then
' If t2 is smaller than t1 then the tickcount has been reset, use reset tick value + t2 - t1
Application.StatusBar = "VBA Code Runtime ms: " & (4294967295# + t2) - t1
Else
' If t2 is bigger than t1 then just use t2 - t1
Application.StatusBar = "VBA Code Runtime ms: " & t2 - t1
End If
我希望以下列方式呈现运行时。
180 milliseconds
30 seconds
1 minute, 30 seconds
2 hours, 1 minute, 30 seconds
我将如何实现这一点,我们将非常感谢任何帮助。
答案 0 :(得分:1)
这可以为您提供您正在寻找的基本结果。
Sub myStopwatch()
Dim t1 As Double, t2 As Double, et As Double, mssg As String
Application.StatusBar = "Running..."
Debug.Print "Start at: " & Time
t1 = Timer
' do stuff here
t2 = Timer
Debug.Print "End at: " & Time
et = t2 - t1 + Abs((t2 < t1) * 86400)
mssg = "VBA Code Runtime: "
Select Case et
Case Is < 1
mssg = mssg & Format(et, "0.000 \m\s")
Case 1 To 59.999
mssg = mssg & Format(Int(et), "0 \s") 'this one rounds down
'mssg = mssg & Format(et\1, "0 \s") this one rounds it off up or down
Case 60 To 3599.999
mssg = mssg & Format(Int(et / 60), "0 \m\, ") & Format(et Mod 60, "0 \s")
Case Is >= 3600
mssg = mssg & Format(Int(et / 3600), "0 \h\, ") & Format(Int((et Mod 3600) / 60), "0 \m\, ") & Format(et Mod 60, "0 \s")
Case Else
'do nothing
End Select
Application.StatusBar = mssg
End Sub
我使用了VBA的内置Timer
而不是GetTickCount
,因为您最多只需要10个小时。 Timer
在午夜重置,因此对延长的计时会话没有用。我已经补偿了一个午夜的营业额。
如果您对结果感到满意,请转到VBE的立即窗口(例如Ctrl+G
)以查看实际的开始和停止时间。
更多关于Select...Case Statement (Visual Basic)的选择案例方法的标准。