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 ...

Get VB & VBA in a Nutshell: The Language now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.