计时 VBA 代码返回负时间

Timing a VBA code returned a negative time

我 运行 根据 https://www.thespreadsheetguru.com/the-code-vault/2015/1/28/vba-calculate-macro-run-time 在 VBA 中的一些代码并且有一个负值的 return:

-20439秒

有谁知道为什么?它实际上 运行 约 18 小时(第二天 1500 - 0900)

Option Explicit

Sub CalculateRunTime_Minutes()
'PURPOSE: Determine how many minutes it took for code to completely run
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim StartTime As Double
Dim MinutesElapsed As String

'Remember time when macro starts
  StartTime = Timer

'*****************************
'Insert Your Code Here...
'*****************************

'Determine how many seconds code took to run
  MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")

'Notify user in seconds
  MsgBox "This code ran successfully in " & MinutesElapsed & " minutes", vbInformation

End Sub

代码使用Timer

The Timer returns a Single representing the number of seconds elapsed since midnight. SyntaxTimerRemarks In Microsoft Windows the Timer function returns fractional portions of a second. On the Macintosh, timer resolution is one second. MSDN

因此,如果您从 运行 开始 15:00,代码将 return 有意义,如果您结束 23:59。如果您第二天在 09:00 结束,它将 return 负值。

您可以重新生成代码,以便同时获取帐户中的日期。使用 Now,其中 return 是日期和时间 - 21.02.2018 10:33:55

这看起来是一个不错的选择:

Sub WorkstAtMidnight()

    Dim StartTime As Date
    StartTime = Now()
    'Do something incredible
    MsgBox Round((Now() - StartTime) * 24 * 60 * 60, 0)
    '24 hours times 60 minutes times 60 seconds (usually I just do 24*3600)

End Sub

另一种选择:

MinutesElapsed = Format((Timer - StartTime) / 86400 + IIf(Timer < StartTime, 1, 0), "hh:mm:ss")

这可以准确地跟踪小时和分钟,直到一整天(即它在 24 小时运行时重置)。之后真正的问题是 为什么你的代码需要这么长时间!