| DoEvents Function |
Named Arguments
No
Syntax
DoEvents()
Return Value
In VBA, DoEvents returns 0; in the retail version of VB, it returns the number of open forms.
Description
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.
Example
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."
End Sub
Private Sub CommandButton2_Click()
blnFlag = False
End Sub
Programming Tips and 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access