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

问题描述 投票:1回答:1

我在Userform的框架内有一个动态范围的OptionButtons。 OptionButton的数量根据表中的列数而变化。每个按钮都根据列标签进行标记。当一个人选择一个选项时,我需要一个ListBox来填充该表列中找到的项目。填充选项按钮和ListBox非常简单。我知道如何在已知的Userformobjects上检测鼠标按下事件。但按钮只能通过编码存在而且会有所不同。如何检测实际不存在的对象上的MouseDown?我已经尝试了为Frame创建MouseDown类的代码

excel vba userform mousedown
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.