Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA: Using WithEvents on UserForms

Tags:

I have a Word userform with 60+ controls of varying types. I would like to evaluate the form every time a control_change event is triggered and change the enabled state of the form's submit button. However, I really don't want to write and maintain 60 on change event handlers.

like image 879
user51498 Avatar asked Jul 05 '09 07:07

user51498


People also ask

How do I add text to Userforms?

Add the TextOnce you have the label, look to the Properties window and change the Caption property. This controls what text appears in the label. If you don't see the properties window, make sure you clicked the Label and hit F4. This is the simplest way to add text to a UserForm.

What does .show do in VBA?

When the . Show method is called, VBA will direct the program flow to the UserForm_Initialize event. Here, you can make numerous customizations. You can edit the userform controls, like the caption on the command button.

How do you unload a form in VBA?

How to Close UserForm in Excel VBA? Once the purpose of the user form is done, there is a point in keep showing the userform in front of the user, so we need to close the userform. We can close the userform by using the “Unload Me” statement and “UserForm. Hide” statements.


1 Answers

You can create an event-sink class that will contain the event-handling code for all of your controls of a particular type.

For example, create the a class called TextBoxEventHandler as follows:

Private WithEvents m_oTextBox as TextBox  Public Property Set TextBox(ByVal oTextBox as TextBox)     Set m_oTextBox = oTextBox End Property  Private Sub m_oTextBox_Change()     ' Do something End Sub 

Now you need to create & hook up an instance of that class for each control of the appropriate type on your form:

Private m_oCollectionOfEventHandlers As Collection  Private Sub UserForm_Initialise()      Set m_oCollectionOfEventHandlers = New Collection      Dim oControl As Control     For Each oControl In Me.Controls          If TypeName(oControl) = "TextBox" Then              Dim oEventHandler As TextBoxEventHandler             Set oEventHandler = New TextBoxEventHandler              Set oEventHandler.TextBox = oControl              m_oCollectionOfEventHandlers.Add oEventHandler          End If      Next oControl  End Sub 

Note that the reason you need to add the event handler instances to a collection is simply to ensure that they remain referenced and thus don't get discarded by the garbage collector before you're finished with them.

Clearly this technique can be extended to deal with other types of control. You could either have separate event handler classes for each type, or you could use a single class that has a member variable (and associated property & event handler) for each of the control types you need to handle.

like image 82
Gary McGill Avatar answered Oct 14 '22 13:10

Gary McGill