问题
I have a Userform with several TextBox
, and I need to check their values so I have created a single event handler using a class module with a WithEvent
private object.
The Change
event handler works just fine, but not the AfterUpdate
handler (the same goes for BeforeEvent
, Enter
, Exit
).
Here's a short example of the problem:
' class name is NumberBox
Private WithEvents nbTextBox As MSForms.TextBox
Public Property Set TextBox(ByVal t As MSForms.TextBox)
Set nbTextBox = t
End Property
Private Sub nbTextBox_Change()
Debug.Print "Change " & nbTextBox.Value ' Working
End Sub
Private Sub nbTextBox_AfterUpdate()
Debug.Print "AfterUpdate " & nbTextBox.Value 'not working
End Sub
The UserForm code looks like this:
Private col As Collection
Private Sub UserForm_Initialize()
Set col = New Collection
Dim c1 As MSForms.TextBox, c2 As MSForms.TextBox
Dim tb1 As NumberBox, tb2 As NumberBox
Set c1 = Controls("TextBox1")
Set c2 = Controls("TextBox2")
Set tb1 = New NumberBox
Set tb2 = New NumberBox
Set tb1.TextBox = c1
Set tb2.TextBox = c2
col.Add tb1
col.Add tb2
End Sub
I have tried to change UserForm.TextBox
to UserForm.Control
but I get a object or class does not support the set of events
, even though Userform.Control
is the class which define the AfterUpdate
event according to the documentation.
回答1:
I don't know if you ever got an answer to this question, but your observations are correct. The events available to WithEvents controls are only a subset of the events normally available to that type of control. As you note, the Enter, Exit, BeforeUpdate and AfterUpdate events aren't available to variables declared as WithEvents.
I don't see any authoritative website on this, even in Chip Pearson's page that covers WithEvents, but if you search on "vba withevents no enter afterupdate exit event" you'll find several discussions (including this one, which I landed on while looking for an authoritative page for a blog post reference).
You can tell which events are available by clicking on the control and event dropdowns in the class:
回答2:
Private WithEvents Control1 As MSForms.Control
Will allow you to bind to events common to all controls: Enter, Exit, BeforeUpdate and AfterUpdate
Correction. This does not work, and creates a run time error.
来源:https://stackoverflow.com/questions/23995931/unable-to-capture-afterupdate-event-with-a-custom-event-handler