【问题标题】:Timing a VBA code returned a negative time计时 VBA 代码返回负时间
【发布时间】:2018-02-21 09:29:48
【问题描述】:

我按照https://www.thespreadsheetguru.com/the-code-vault/2015/1/28/vba-calculate-macro-run-time 在 VBA 中运行了一些代码,结果返回了一个负值:

-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

【问题讨论】:

  • 如果你的代码需要 18 小时才能运行——也许它需要Code Review

标签: vba excel timer negative-number


【解决方案1】:

代码使用Timer

Timer 返回一个 Single,表示自午夜以来经过的秒数。 SyntaxTimerRemarks 在 Microsoft Windows 中,Timer 函数返回秒的小数部分。在 Macintosh 上,计时器分辨率为一秒。 MSDN

因此,如果您从15:00 开始运行,则代码将返回有意义的内容,如果您最终到达23:59。如果第二天在09:00 结束,它将返回负值。

您可以重新构建代码,以获取帐户中的日期。使用Now,它返回日期和时间 - 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

【讨论】:

  • 不错的答案(我 +1).. 还注意到您最近获得了 VBA 金牌...恭喜!
【解决方案2】:

另一种选择:

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

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

【讨论】:

    猜你喜欢
    • 2021-12-31
    • 2020-01-08
    • 2019-11-18
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 2016-06-10
    • 1970-01-01
    相关资源
    最近更新 更多