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
10000000
20000000
30000000
40000000
50000000
60000000
70000000
80000000
90000000
100000000
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 Posts

Looping Through a Recordset
Loops – Do Until / Do While / Do
Loops – For Each
Loops – For Next
Loops – While Wend
Nested Loops
What are Recordsets

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Visit Us On TwitterVisit Us On FacebookVisit Us On Youtube