DoEvents

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

As always, a site wouldn't be anything without its users so please feel free to comment! We welcome any comments you have on the material and any suggestions you may have for future content.


In our humble opinion, it is worth commenting just so you can play with Fun Captcha below!

2 Trackbacks

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>