【问题标题】:Calling sub not completing before loop moves to next iteration in VBA在循环移动到VBA中的下一次迭代之前调用子未完成
【发布时间】:2020-07-12 03:23:23
【问题描述】:

我正在编写一段 VBA 代码来显示倒数计时器。 Excel 表 1 列出了事件的时间和描述,表 2 显示倒计时。

这个想法是,一旦第一个事件成功倒计时,它会检查第二个事件的日期,如果是今天,它会继续倒计时到第二个事件,依此类推。倒计时方面第一次和描述成功地工作,但是当它完成倒计时到第一个事件时,它完全停止。

有 3 个替补,第一个决定活动是否在今天,以及需要倒计时多长时间。第一个调用第二个通过减去TimeSerial(0,0,1) 来进行倒计时,第三个是计时器。我承认我从网上找到的一篇写得很好的文章中借用了第 2 和第 3 篇(感谢写这篇文章的人,谢谢)。

我已经简化了我在下面写的内容:

For i=1 to 10
    If *Conditions to determine if countdown should happen exist*
    *calculate time to countdown and sets it to sheets("Countdown").Cells("A13")*
       Cells(13, 1) = TotaltimeCountdown
       Call Countdowntimer
    End if
 Next i
Sub Countdowntimer()
    Sheets("Countdown").Activate
    Dim Counter As Range        
    Set Counter = ActiveSheet.Range("A13")

    If Counter.Value > 0 Then
        Counter.Value = Counter.Value - TimeSerial(0, 0, 1)
        Call Timer
    ElseIf Counter.Value <= 0 Then
        Sheets("Countdown").Range("A13:H17").ClearContents
        Exit Sub
    End If              
End Sub
'Sub to trigger the reset of the countdown timer every second
Sub Timer()
    Dim gCount As Date
    gCount = Now + TimeValue("00:00:01")
    Application.OnTime gCount, "Countdowntimer"
End Sub

我在第一个 sub 中调用 Countdowntimer 后放置了一个消息框,并且能够确定它显示倒计时的时间量,然后显示消息框并循环遍历 i 的每个值。直到那时,它才真正进行倒计时。

关于如何使 for 循环完全暂停直到被调用子的倒计时完成有什么建议吗?

任何建议表示赞赏

【问题讨论】:

    标签: excel vba call countdown


    【解决方案1】:

    问题在于使用Application.OnTime,而对于倒计时计时器,请使用Do 循环和DoEvents 倒计时。

    类似的东西:

    Option Explicit
    
    Public Sub CountDownTimer()
        With ThisWorkbook.Worksheets("Countdown")
            Dim Duration As Long
            Duration = 10 ' needs to be in seconds!
            'if your cell has a real datetime then use
            Duration = .Range("A13").Value * 24 * 60 * 60
    
            Dim TimerStart As Double
            TimerStart = Timer()
    
            Do While Timer <= TimerStart + Duration
                .Range("A13").Value = TimeSerial(0, 0, TimerStart + Duration - Timer)
                DoEvents
            Loop
    
            ThisWorkbook.Worksheets("Countdown").Range("A13:H17").ClearContents
        End With
    End Sub
    

    【讨论】:

    • 感谢您的帮助。你能解释一下为什么Application.OnTime 在这种情况下不起作用吗?
    • @jen 因为它会注册,所以 Excel 应该在特定时间运行宏。在此之前,当前宏将继续处理并在运行OnTime 宏的时间到来时再次停止。然后它将运行该宏,在它之后,它将继续暂停的宏。此行为是由于 VBA 不支持多线程这一事实。一次只能运行一个宏。不可能同时运行 2 个宏。 • 我使用的循环会一直循环直到时间结束。因此,您的其他宏在此期间会停止。
    猜你喜欢
    • 2016-11-04
    • 2014-01-07
    • 1970-01-01
    • 2014-07-30
    • 2023-04-10
    • 1970-01-01
    • 2015-05-12
    • 2020-07-02
    • 2019-11-29
    相关资源
    最近更新 更多