倒计时失败

Countdown Timer fails

我已将此代码成功用作正计时计时器,但它失败了用作倒计时计时器。我得到

Error 1004 Application-definde og object-defined error

在行

Cell.Value = CountDown - (Timer - Start - 86400 * (Start > Timer)) / 86400

我认为它乘以零。

我知道代码可以与 Cell.Value = CountDown - TimeSerial(0, 0, Timer - Start) 一起使用,但我不能使用它,而 TimeSerial 是一个变体(整数),这意味着代码只能在几秒钟前进行 32767 次计数它将在 溢出错误 中停止。 有没有人知道如何解决下面代码中的错误 1004 问题。

Option Explicit

Sub NewTimer() 'Countdown timer
    Dim Start As Long
    Dim Cell As Range
    Dim CountDown As Date

    Start = Timer

    Set Cell = Sheet1.Range("B1")    'This is the starting value.
    CountDown = TimeSerial(0, 0, 10)    'Set takttime
    Cell.Value = CountDown

    Do While Cell.Value > 0
        Cell.Value = CountDown - (Timer - Start - 86400 * (Start > Timer)) / 86400
        DoEvents
    Loop
End Sub

不要在循环中使用布尔值,而是使用取 1 或 0 的变量。这样可以消除错误。

Dim temp As Integer
# ...
Do While Cell.Value > 0
    If Start > Timer Then
        temp = 1
    Else
        temp = 0
    End If

    Cell.Value = CountDown - (Timer - Start - 86400 * temp) / 86400
    DoEvents
Loop

为了避免溢出错误,您可以将 CountDown 的类型更改为 double,而不是使用 TimeSerial 函数指定时间(以天为单位)。一些例子:

CountDown = 1 # 1 day
CountDown = 1/24 # 1 hour
CountDown = 1/24/60 # 1 minute
CountDown = 1/24/60/60 # 1 second
CountDown = 2/24 + 40/24/60/60 # 2 hours and 40 seconds

因为我不知道为什么您的代码会抛出该错误并且只是有时会抛出该错误,请尝试使用没有该问题的替代方法。

Sub OtherTimer()
    Dim UserInput As String
    UserInput = "00:00:10"

    Dim SecondsToRun As Long
    SecondsToRun = CDbl(TimeValue(UserInput)) * 24 * 60 * 60

    Dim TimerStart As Double
    TimerStart = Timer 'remember when timer starts

    Do
        Range("B1").Value = Format$((SecondsToRun - (Timer - TimerStart)) / 24 / 60 / 60, "hh:mm:ss")
        'count backwards from 01:15 format as hh:mm:ss and output in cell A1

        DoEvents
    Loop While TimerStart + SecondsToRun > Timer 'run until SecondsToRun are over
End Sub