我正在编写一段VBA代码来显示倒计时计时器。Excel工作表1列出事件的时间和描述,第2页显示倒计时。
这个想法是,一旦第一个事件成功地被计算下来,它就会检查第二个事件的日期,如果是今天,它就会继续计数到第二个事件,以此类推。倒计时方面第一次成功地工作和描述,但当它完成计数到第一个事件,它完全停止。
有三个替补,第一个计算出事件是否是今天,以及它需要计算下来多长时间。第一个调用第二个,它通过减去一个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
的每个值。直到那时,它才真正开始倒计时。
对于如何使for循环完全暂停,直到被叫子的倒计时结束有任何建议吗?
如有任何建议请见谅
发布于 2020-03-31 07:03:28
问题是使用Application.OnTime
,对于倒计时器,使用带有DoEvents
的Do
循环来计数。
就像这样:
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
https://stackoverflow.com/questions/60952901
复制