In this blog post we discuss the DoEvents method in VBA.
DoEvents is a simple command that pauses a loop and allows the operating system to carry out any tasks that have been queued.
If you have a loop that can take a significant time to fire, DoEvents enables the loop to pause at periodic intervals. In the code below, we have created a very long loop and added in a DoEvents command every 1 second or so.
Sub CPUTask() Dim t As Double, zzz As Single Debug.Print "CPUTask2 Start Now() = " & Now() For t = 1 To 100000000 'We create a loop that will take 5-10 seconds to 'complete zzz = zzz + (t / 2) If (t Mod 10000000) = 0 Then DoEvents 'DoEvents pauses the loop so the operating 'system can perform queued functions Debug.Print t End If Next Debug.Print "CPUTask End Now() = " & Now() End Sub
|CPUTask Start Now() = 25/12/2012 14:52:07
CPUTask End Now() = 25/12/2012 14:52:18
DoEvents is a useful function so you can create long loops that don’t hold up the operating system.
Related PostsLooping Through a Recordset
Loops – Do Until / Do While / Do
Loops – For Each
Loops – For Next
Loops – While Wend
What are Recordsets