In VBA, DoEvents returns 0; in the retail version of VB, it returns the number of open forms.
Allows the operating system to process events and messages waiting in the message queue. For example, you can allow a user to click a Cancel button while a processor-intensive operation is executing. In this scenario, without DoEvents, the click event wouldn't be processed until after the operation had completed; with DoEvents, the Cancel button's Click event can be fired and its event handler executed even though the processor-intensive operation is still executing.
Rules at a Glance
Control is returned automatically to your program or the procedure that called DoEvents once the operating system has processed the message queue.
The following example uses a UserForm with two command buttons to illustrate how DoEvents interrupts a running process:
Option Explicit Private lngCtr As Long Private blnFlag As Boolean
Private Sub CommandButton1_Click()
blnFlag = True
Do While blnFlag lngCtr = lngCtr + 1 DoEvents Loop
MsgBox "Loop interrupted after " & lngCtr & _ " iterations."
Private Sub CommandButton2_Click()
DoEvents Function 241
blnFlag = False
End Sub Programming Tips & Gotchas
• You may consider using the retail version of VB to create standalone ActiveX EXEs that handle very intensive or long processes. These can then be called from your VBA code. This allows you to pass the responsibility of time slicing and multitasking to the operating system.
• Make sure that during the time you have passed control to the operating system with DoEvents, the procedure calling DoEvents isn't called from another part of the application or from another application, since the return from DoEvents may be compromised. For the same reason, you must not use the DoEvents function within VB in-process ActiveX DLLs.
• While DoEvents can be essential for increasing the responsiveness of your program, it should at the same time be used judiciously, since it entails an enormous performance penalty. For example, the following table compares the number of seconds required for a simple For...Next loop to iterate one million times when DoEvents isn't called, on the one hand, and when it's called on each iteration of the loop, on the other:
If most of a procedure's processing occurs inside a loop, one way of avoiding far-too-frequent calls to DoEvents is to call it conditionally every hundred or thousand iterations of the loop. For example:
Dim lngCtr As Long
For lngCtr = 0 To 1000000
DoEvents End If Next
Was this article helpful?
This is the 2nd volume of a 9 volume series called the Webmasters Toolbox package. Search engines are the number one way that internet users find websites. In most cases, a listing in a search engine is free. So, it's no surprise that Search Engine Optimization SEO is often the first priority when marketing a website.