In many situations, the DoEvents keyword can be a real boon. As you may know, this keyword yields operation to the operating system so that it can process other events. Many times after initiating a procedure, you may want to pause execution to gather further information from an end user via a form. For example, consider a project with two forms. The main form performs a calculation and displays the results. The second form lets an end user manually enter two numbers for the calculation. When you click the second form's Submit button, the main form multiplies the user-entered numbers and displays the results.
Typically, to handle this feature, you might use DoEvents to wait until the
user has entered the two numbers. For instance, you might set up a looping
procedure like so:
Private Sub Command1_Click()
Dim Myform as frmEntry
Set Myform = New frmEntry
With Myform
.Show
Do
DoEvents
Loop Until Myform.Ready
'Do some calculations based on the entry
txtResults = .txtNum1 * .txtNum2
End With
Unload frm
Set frm = Nothing
End Sub
This code assumes that you've also declared a public variable named Ready in the
entry form, and that the entry form sets it equal to True when the user
completes the entry process. Unfortunately, the DoEvents keyword comes with a
price, especially when you place it inside a loop. It consumes a lot of system
resources.
As a better alternative, consider creating a custom event that the entry form
triggers when the user finishes entering data, like so:
Public Event NumbersSubmitted()
Public NumOne As Long
Public NumTwo As Long
Private Sub cmdSubmit_Click()
NumOne = CLng(txtNum1)
NumTwo = CLng(txtNum2)
Unload Me
RaiseEvent NumbersSubmitted
End Sub
Then, you can add code that reacts to this event in the original form, as in:
Private Sub frmNumEntry_NumbersSubmitted()
With frmNumEntry
txtResults = .NumOne * .NumTwo
Set frmNumEntry = Nothing
End With
End Sub
Here, frmNumEntry is a variable with form-level scope and declared WithEvents in the main form's general declaration section, like this:
Dim WithEvents frmNumEntry As frmNumberEntry
Comments