倒数计时器失败

问题描述 投票:0回答:2

我已成功使用此代码作为Count Up Timer,但它作为倒数计时器失败。我明白了

错误1004 Application-definde og对象定义的错误

在线

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

我认为它是多重的。

我知道代码可以使用Cell.Value = CountDown - TimeSerial(0, 0, Timer - Start),但我不能使用它,而TimeSerial是一个Variant(整数),这意味着代码只能在几秒钟内完成32767计数,然后才会在溢出错误中停止。有没有人有一个idear如何解决下面的代码中的错误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
excel vba countdowntimer
2个回答
1
投票

因为我不知道为什么你的代码会抛出那个错误而且只是有时候,尝试这个没有那个问题的替代方案。

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

0
投票

而不是在循环中使用布尔值使用一个取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
© www.soinside.com 2019 - 2024. All rights reserved.