Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

VBA Timer Using Do Loop

I am trying to make a countdown in VBA, that displays the seconds in a textbox1. I am using this code below, but nothing happens and the textbox doesn't increment each second. I have tried doing Endtick / 1000 too because it's ms, but to still now avail. Is this the right method I should be using?

Other stuff is happening in the app as the timer is running, so I can't use the WAIT function.

Private Sub CommandButton2_Click()
    timer (10)
End Sub




Sub timer(Finish As Long)
 
    Dim NowTick As Long
    Dim EndTick As Long
 
    EndTick = GetTickCount + (Finish * 1000)
     
    Do
 
        NowTick = GetTickCount
        DoEvents
        UserForm1.TextBox1.Text = GetTickCount
        
 
    Loop Until NowTick >= EndTick
    msgbox("Time is up")
 
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Add this to a module, separate from the userform code:

Option Explicit

#If Win64 Then
    Public Declare PtrSafe Function GetTickCount Lib "kernel32" () As Long
#Else
    Public Declare Function GetTickCount Lib "kernel32" () As Long
#End If

Sub timer(Finish As Long)
    Dim EndTick As Long
    EndTick = GetTickCount + (Finish * 1000)
    Do
        DoEvents
        UserForm1.TextBox1.Text = (EndTick - GetTickCount) / 1000
    Loop Until GetTickCount >= EndTick
    UserForm1.TextBox1.Text = 0
    MsgBox ("Time is up")
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...