更新时间:2023-12-01 22:41:22
您可以创建一个事件接收器类,该类将包含特定类型的所有控件的事件处理代码.
You can create an event-sink class that will contain the event-handling code for all of your controls of a particular type.
例如,创建一个名为 TextBoxEventHandler
的类,如下所示:
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.