VBA:在UserForms上使用WithEvents [英] VBA: Using WithEvents on UserForms
问题描述
你可以创建一个事件接收器该类将包含特定类型的所有控件的事件处理代码。
例如,创建一个名为 TextBoxEventHandler
如下:
私有WithEvents m_oTextBox为TextBox
公共属性集TextBox (ByVal oTextBox as TextBox)
设置m_oTextBox = oTextBox
结束属性
私有子m_oTextBox_Change()
'做某事
End Sub
现在,您需要创建&为您的表单上适当类型的每个控件连接该类的实例:
私有m_oCollectionOfEventHandlers作为集合
Private Sub UserForm_Initialise()
设置m_oCollectionOfEventHandlers =新集合
Dim oControl As Control
对于每个oControl在Me.Controls
如果TypeName(oControl)=TextBox然后
Dim oEventHandler As TextBoxEventHandler
设置oEventHandler = New TextBoxEventHandler
设置oEventHandler.TextBox = oControl
m_oCollectionOfEventHandlers.Add oEventHandler
结束如果
下一个oControl
End Sub
请注意,您需要将事件处理程序实例添加到集合的原因只是确保它们保持引用,因此不会被丢弃垃圾收集器在你完成他们之前/ p>
显然,这种技术可以扩展到处理其他类型的控制。您可以为每种类型分别设置事件处理程序类,也可以使用一个具有成员变量(以及关联属性和事件处理程序)的类,用于需要处理的每个控件类型。
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.
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.
这篇关于VBA:在UserForms上使用WithEvents的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!