Is it possible in Excel VBA to apply some sort of a global change event handler for a specified userform for all textboxes and comboboxes.
Because of how event handlers are wired to event sources in VBA, the answer is "no".
However...
Add a new class module to your project, call it DynamicTextBox
(you could have another for a DynamicComboBox
).
Option Explicit
Private WithEvents encapsulated As MSForms.TextBox
Public Sub Initialize(ByVal ctrl As MSForms.TextBox)
Set encapsulated = ctrl
End Sub
Private Sub encapsulated_Change()
'handle textbox changed here
End Sub
Now in your form, have a Collection
of DynamicTextBox
class instances - you'll want to have a New
instance for each TextBox
you want to handle the Change
event for.
Option Explicit
Private handlers As VBA.Collection
Private Sub UserForm_Initialize()
Set handlers = New VBA.Collection
Dim ctrl As MSForms.Control
For Each ctrl In Me.Controls
If TypeOf ctrl Is MSForms.TextBox Then
Dim textBoxHandler As DynamicTextBox
Set textBoxHandler = New DynamicTextBox
textBoxHandler.Initialize ctrl
handlers.Add textBoxHandler
'ElseIf TypeOf ctrl Is MSForms.ComboBox Then
' Dim comboBoxHandler As DynamicComboBox
' Set comboBoxHandler = New DynamicComboBox
' comboBoxHandler.Initialize ctrl
' handlers.Add comboBoxHandler
End If
Next
End Sub
Note, this technique of encapsulating a WithEvents
MSForms control in a class instance, can also be used for handling events of controls that are added dynamically at run-time.
The key is to keep the MSForms controls in scope - that's what the module-level Collection
does.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…