在用户窗体中检测动态对象上的鼠标按下事件

时间:2019-05-01 00:17:41

标签: excel vba userform mousedown

我在用户窗体的框架内有一个动态范围的OptionButton。 OptionButton的数量根据表中的列数而变化。每个按钮均根据列标签进行了标记。当一个人选择一个选项时,我需要用该表列中找到的项目填充一个ListBox。 填充选项按钮和ListBox很容易。我知道如何检测已知Userform对象上的鼠标按下事件。但是按钮仅通过编码而存在并且有所不同。如何检测实际上不存在的对象上的MouseDown? 我已经尝试过为框架创建MouseDown类的代码

1 个答案:

答案 0 :(得分:1)

您需要将控件包装在类模块中-例如DynamicOptionButton

Option Explicit
Private WithEvents ControlEvents As MSForms.OptionButton

Public Sub Initialize(ByVal ctrl As MSForms.OptionButton)
    If Not ControlEvents Is Nothing Then ThrowAlreadyInitialized
    Set ControlEvents = ctrl
End Property

Private Property Get AsControl() As MSForms.Control
    Set AsControl = ControlEvents
End Property

Private Sub ThrowAlreadyInitialized()
    Err.Raise 5, TypeName(Me), "Invalid Operation: This control is already initialized."
End Sub

Private Sub ControlEvents_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
    Dim parentForm As UserForm1 'todo: use your actual UserForm subtype
    Set parentForm = AsControl.Parent 
    'handle mousedown here.
End Sub

创建动态控件时,您需要一个模块级 Collection来容纳DynamicOptionButton实例-否则它们将退出范围(当达到End Sub时,您将永远无法处理他们的任何事件。

Private DynamicControls As Collection

Private Sub Class_Initialize()
    Set DynamicControls = New Collection
    'todo invoke CreateOptionButton
End Sub

Private Sub CreateOptionButton() 'todo parameterize
    Dim ctrl As MSForms.OptionButton
    Set ctrl = Me.Controls.Add(...)

    Dim wrapper As DynamicOptionButton
    Set wrapper = New DynamicOptionButton
    wrapper.Initialize ctrl

    DynamicControls.Add wrapper
End Sub