午夜开始计时

Time counting over midnight

计时超过午夜失败

计算午夜时间失败 我制作了一个带有两个计数器的代码 - 一个 (CountUPS) 每次启动程序 (A1) 时从 0 开始计数秒数,另一个 (CountUP) 从预设时间 (A2) 开始计数秒数。 它在同一天内计数时工作正常,但每次在午夜计数时都会出现错误。当 A2 及时到达 23:37:53 时停止。 我对价值观的定义有问题吗?

Sub RunMe()

Dim StartS As Single
Dim CellS As Range
Dim Cellt As Range
Dim CountUPS As Date
Dim CountUp As Date

'Timer is the number of seconds since midnight.
'Store timer at this point in a variable
StartS = Timer

'Store A1 in a variable to make it easier to refer
'to it later. Also, if the cell changes, you only
'have to change it in one place
Set CellS = Sheet1.Range("A1")

'This is the starting value.
CountUPS = TimeSerial(0, 0, 0)

'Set our cell to the starting value
CellS.Value = CountUPS

Set Cellt = Sheet1.Range("A2")
CountUp = Sheet1.Range("A2")

b_pause = True

Do While CellS.Value >= 0

    CellS.Value = CountUPS + TimeSerial(0, 0, Timer - StartS + (StartS > Timer))
    Cellt.Value = CountUp + TimeSerial(0, 0, Timer - StartS + (StartS > Timer))
    DoEvents
Loop

End Sub

错误消息解决了很多问题。

  • overflow 错误,正如已经指出的那样,是因为 TimeSerial 函数参数的整数约束。
  • 1004 错误发生在午夜,是因为当 Timer 在午夜恢复为 0 时,您的秒数表达式为负数。除非您使用的是 1904 日期系统,否则您不能在 Excel 中表示负数时间。
  • 在尝试针对 "passing midnight" 进行调整时,您将秒数和天数以及 Excel 和 VBA 混为一谈。你在你的宏中试图增加一秒钟,而你可能真的想增加一天。此外,由于 VBA 中的 True 等于 -1,您实际上是在减去而不是加法!

我认为以下修改可能有效,但尚未广泛测试。 86400 是一天中的秒数。

Option Explicit
Sub RunMe()

Dim StartS As Single
Dim CellS As Range
Dim Cellt As Range
Dim CountUPS As Date
Dim CountUp As Date

'Timer is the number of seconds since midnight.
'Store timer at this point in a variable
StartS = TIMER

'Store A1 in a variable to make it easier to refer
'to it later. Also, if the cell changes, you only
'have to change it in one place
Set CellS = Sheet1.Range("A1")

'This is the starting value.
CountUPS = TimeSerial(0, 0, 0)

'Set our cell to the starting value
CellS.Value = CountUPS

Set Cellt = Sheet1.Range("A2")
CountUp = Sheet1.Range("A2")

'b_pause = True

Do While CellS.Value >= 0

    CellS.Value = CountUPS + (TIMER - StartS - 86400 * (StartS > TIMER)) / 86400
    Cellt.Value = CountUp + (TIMER - StartS - 86400 * (StartS > TIMER)) / 86400
    DoEvents
Loop

End Sub