我已成功将此代码用作“倒数计时器”,但失败作为“ <倒数计时器” 。我得到
错误1004应用程序定义的对象定义的错误
在行
Cell.Value = CountDown - (Timer - Start - 86400 * (Start > Timer)) / 86400
我认为它乘以零。
我知道代码可以与Cell.Value = CountDown - TimeSerial(0, 0, Timer - Start)
一起使用,但是我不能使用它,而TimeSerial
是Variant(integer),这意味着代码只能在秒前执行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
答案 0 :(得分: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
答案 1 :(得分: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
的类型更改为双精度,而不是使用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