【问题标题】:Countdown Timer fails倒数计时器失败
【发布时间】:2019-02-12 20:37:42
【问题描述】:

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

错误 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

【问题讨论】:

  • 你想用(Start > Timer)做什么,这将导致True(转换为-1)或False(转换为0)。你能解释一下你的尝试是什么吗?
  • @Peh 有了(Start > Timer),我将避免计数器在午夜发生故障。
  • 您能解释一下您的计时器应该如何计数吗?你的计算完全不清楚。 • 你明白我在第一条评论中写的内容吗?
  • @PEH 我是新手,我会将您链接到我之前的问题,其中计算来自 [链接] stackoverflow.com/questions/54212631/… - 是的,我了解True 或 @987654333 的评估@ 并且它在 Count UP Timer 中用于在链接中计算到午夜。如果倒数计时器将经过午夜,我不确定在计算中是否需要它。
  • 奇怪我无法重现您的问题。代码运行良好。尝试使用CLng(Start > Timer) 将布尔值显式转换为数字。如果这没有帮助,那么肯定有其他问题。您有任何名为Timer 的子/功能吗?如果是这样,请重命名!

标签: excel vba countdowntimer


【解决方案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

【讨论】:

    【解决方案2】:

    不要在循环中使用布尔值,而是使用一个取 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 2011-12-19
      • 2015-08-19
      相关资源
      最近更新 更多