午夜计时

时间:2019-01-16 08:05:36

标签: excel vba time counting

计数到午夜的时间失败

计算午夜时间失败 我编写了带有两个计数器的代码-一个(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

1 个答案:

答案 0 :(得分:0)

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

  • 已经指出,overflow错误是由于TimeSerial函数参数上的整数约束所致。
  • 1004错误发生在午夜,是因为当Timer在午夜恢复为0时,您的秒表示为负数。除非您使用1904年日期系统,否则您将无法在Excel中表达负数。
  • 在尝试调整“通过午夜”时,您将秒和天以及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
相关问题