【发布时间】:2020-10-26 15:22:20
【问题描述】:
抱歉,如果这是一个基本问题,但我正在自学 VBA PowerPoint,如果有人能解释为什么我收到溢出错误,我将不胜感激。
我一直在尝试获取我的程序用户使用 DateDiff 和 Now 来设置开始和结束计时器执行活动的时间。我的方法是获取秒数,然后计算出这个数字需要多少天、多少分钟、多少小时和多少秒。
以下代码有效,但是,每当我使用 Messagebox (Msgbox) 函数时,我都会收到溢出错误。例如,如果您查看下面的代码一切正常,直到您取消注释我评论的 MsgBoxes 之一,然后程序崩溃并出现运行时错误“6”:溢出。我注意到实际崩溃发生在未注释消息框下方的后续计算行之一上。我注意到第一个未注释的 MsgBox 不会导致计算机崩溃。
如果有人能解释计算机崩溃的原因,我将不胜感激,其次是否需要对我的代码进行任何更改以使其可靠使用?
感谢任何cmets!
Sub NewTimer()
Dim TimeStart As Date
Dim TimeEnd As Date
Dim Days As Long
Dim Hours As Long
Dim Hours2 As Long
Dim Hours3 As Long
Dim Minutes As Long
Dim Minutes2 As Long
Dim Seconds As Long
Dim TimePassed As String
Dim Seconds2 As Long
Seconds = Int(DateDiff("s", Now, Now + 1))
MsgBox "The total number of seconds that make up this number is " & Seconds
Days = Int(DateDiff("d", Now, Now + 1))
MsgBox "The total number of days in this number is " & Days
Hours2 = Seconds - (Days * 24 * 60 * 60) 'This gets the number of seconds remaining
Hours3 = Hours2 / (60 * 60) 'This works out the number of hours
Hours = Int(Hours3)
'MsgBox Hours
Minutes = Seconds - (Days * 24 * 60 * 60) - (Hours * 60 * 60) ' Hours2 - (Hours * 60 * 60)
'MsgBox Minutes
Minutes2 = Int(Minutes / 60)
'MsgBox Minutes2
'Minutes2 = Minutes / 60
Seconds = Seconds - (Days * 24 * 60 * 60) - (Hours * 60 * 60) - (Minutes2 * 60)
MsgBox "The time taken is " & Days & " days, " & Hours & " hours, " & Minutes2 & " minutes and " & Seconds & " seconds."
【问题讨论】:
-
刚刚运行了您的代码,我的计算机处理时间不到 0.02 秒。此外,没有溢出错误。
-
JulianG - 感谢您运行该程序。您是否尝试取消注释其中一个消息框 - 因为这是发生溢出问题的时候。
-
是的,我做到了。再次没有溢出错误。
-
JulianG - 谢谢你的评论。这很有趣,因为当我取消注释消息框时,我在收到错误时没有任何问题!我唯一能想到的是我可能没有使用好的数据类型。我发现自己使用的是 Long 类型。你认为这是我应该使用的吗?例如,双倍会更好吗?
-
JulianG - 我尝试再次更改数据类型(如前所述),但没有区别。所以由于某种原因,当我激活消息框时程序总是崩溃!
标签: vba time powerpoint overflow datediff