DoEvents Function
Description
Yields execution so that the operating system can process other events.
Syntax
DoEvents( )
Remarks
The DoEvents function returns an Integer representing the number of open forms in stand-alone versions of Visual Basic, such as Visual Basic, Standard Edition. DoEvents returns zero in all other applications.
DoEvents passes control to the operating system. Control is returned after the operating system has finished processing the events in its queue and all keys in the SendKeys queue have been sent.
DoEvents is most useful for simple things like allowing a user to cancel a process after it has started, for example a search for a file. For long-running processes, yielding the processor is better accomplished by using a Timer or delegating the task to an ActiveX EXE component. In the latter case, the task can continue completely independent of your application, and the operating system takes case of multitasking and time slicing.
Caution make sure the procedure is not executed again from a different part of your code before the first call returns; this could cause unpredictable results. In addition, do not use DoEvents if other applications could possibly interact with your procedure in unforeseen ways during the time you have yielded control.
See Also
SendKeys statement.
Specifics (Microsoft Access)
In Microsoft Access, the DoEvents function is ignored if you use it in:
- A user-defined function or a procedure that calculates a field in a query, form, or report.
- A user-defined function that creates a list to fill a combo box, a list box, or an OLE object.
If you include the DoEvents function in any of these, Microsoft Access will not relinquish control to the operating system.
Example
This example uses the DoEvents function to cause execution to yield to the operating system once every 1000 iterations of the loop. DoEvents returns the number of open Visual Basic forms, but only when the host application is Visual Basic.
' Create a variable to hold number of Visual Basic forms loaded
' and visible.
Dim I, OpenForms
For I = 1 To 150000 ' Start loop.
If I Mod 1000 = 0 Then ' If loop has repeated 1000 times.
OpenForms = DoEvents ' Yield to operating system.
End If
Next I ' Increment loop counter.
Example (Microsoft Access)
The following example uses the DoEvents function to return control to the operating system while a loop is executing. The DoEvents function always returns 0.
Sub LongLoop()
Dim intI As Integer
For intI = 1 To 1500 ' Start loop.
If intI Mod 100 = 0 Then ' If loop has repeated 100 times.
DoEvents ' Yield to operating system.
Debug.Print intI
End If
Next intI ' Increment loop counter.
End Sub