我正在编写一段VBA代码以显示倒数计时器。 Excel工作表1列出了事件的时间和描述,工作表2显示了倒数计时。
这个想法是,一旦第一个事件成功倒计时,它会检查第二个事件的日期,如果是今天,它将继续倒数第二个事件,依此类推。倒数计时方面第一次成功并成功进行了说明,但是当倒计时到第一个事件时,它将完全停止。
有3个子项,第一个子项可以算出该事件是否为今天以及需要倒计时多长时间。第一个调用第二个,它通过减去TimeSerial(0,0,1)
进行递减计数,而第三个是计时器。我承认,我从网上找到的写得很好的文章中借了第二和第三名(谢谢谁写的,谢谢)。
我简化了下面的内容:
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
我在第一个子菜单中调用Countdowntimer之后放置了一个消息框,并能够确定它显示了倒计时的时间,然后显示该消息框并循环显示i
的每个值。只有THEN才真正开始倒计时。
关于如何使for循环完全暂停直到被调用子的倒计时完成的任何建议?
任何建议,谢谢
问题是使用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