vba 用户表单中的倒计时由函数触发

countdown in vba userform triggered by a function

我想从 运行 代码开始倒计时表格。问题是如果我说

> TimerForm.Show

然后显示用户表单,但未触发倒计时。我怎样才能简单地从用户表单 TimerLabel 中显示倒计时的函数触发倒计时,如下所示

TimerForm.TimerLabel.Caption = Format(TimeSerial(0, 0, nTime), "hh:mm:ss") & " seconds "

nTime 然后将从 30 秒的初始值减少。

下面的答案完全解决了问题。定时器的取消按钮应该是

    Private Sub CancelTimer_Click()

Application.OnTime EarliestTime:=earliest, _
                       Procedure:=handler, _
                       schedule:=False
Unload Me
End
End Sub

如果不是,Application.OnTime 在后台继续 运行。

不知道题主理解的对不对,这里有一些想法。 HTH

Standard module code

Option Explicit

Public Sub test()
    ' One possibility with modeless user form
    ' In this case it is possible to start timer after 
    ' timer form was displayed, because the form is modeless
    ' TimerForm.Show vbModeless
    ' TimerForm.StartTimer

    ' Other possiblity with modal user form
    ' In this case the StartTimer has to be called 
    ' from inside of user form because the form is modal.
    TimerForm.Show
End Sub

Public Sub TimerElapsed()
    TimerForm.OnTimerElapsed
End Sub

TimerForm class module code

' More info about OnTime:
' http://www.cpearson.com/excel/ontime.aspx

Option Explicit

Private Const interval As Integer = 1 ' second
Private Const countdownInit As Integer = 30 ' seconds
Private Const handler As String = "TimerElapsed"
Private earliest As Double
Private countdown As Integer

Private Sub UserForm_Initialize()
    countdown = countdownInit
    StartTimer
End Sub

Private Sub Cancel_Click()
    StopTimer
    Unload Me
End Sub

Public Sub StartTimer()
    earliest = Now + TimeSerial(0, 0, interval)

    Application.OnTime EarliestTime:=earliest, _
                       Procedure:=handler, _
                       Schedule:=True
End Sub

Public Sub StopTimer()
    On Error Resume Next
    countdown = 0
    Application.OnTime EarliestTime:=earliest, _
                       Procedure:=handler, _
                       Schedule:=False
End Sub

Public Sub OnTimerElapsed()
    If countdown <= 0 Then
        Me.TimerLabel.Caption = "00:00:00 seconds "
        Exit Sub
    End If

    Dim timerInfo As String
    timerInfo = Format(TimeSerial(0, 0, countdown), "hh:mm:ss")
    Me.TimerLabel.Caption = timerInfo & " seconds "
    countdown = countdown - interval

    StartTimer ' <--- 'How can I trigger a countdown simply 
               ' from a function where the countdown is shown
               ' in the user form TimerLabel ...' 
               ' Here the OnTime is re-scheduled for next call.
End Sub