通过GetTickCount获取代码运行时并以特定的方式进行格式化

我试图让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 

我希望以下列方式呈现运行时。

  • 如果运行时间在1秒以内 ,应该以毫秒为单位。 例如: 180 milliseconds
  • 如果运行时间低于1分钟但超过1秒钟 ,则应以秒(毫秒)表示。 例如: 30 seconds
  • 如果运行时间超过1分钟但小于1小时 ,应该以分秒为单位。 例如: 1 minute, 30 seconds
  • 如果运行时间超过1小时 ,应以小时,分钟和秒为单位示例: 2 hours, 1 minute, 30 seconds

我将如何实现这一点,任何帮助将不胜感激。

这应该让你得到你正在寻找的基本结果。

 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…案例语句(Visual Basic)上的select案例方法的更多条件。