vba - 监听运行时创建的控件的事件

标签 vba excel events event-handling

我创建了一个类,当给定一个用户窗体作为参数时,应该在该用户窗体上放置一个控件并监听其事件。

简化的类是这样的:

eventsTestItem

Private WithEvents formControl As MSForms.Image
Private parentUF As MSForms.UserForm

Private Sub formControl_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
MsgBox "clicked"
End Sub

Public Property Let Visible(ByVal makeVisible As Boolean)
    '(make) and show if true, otherwise delete
    If makeVisible Then
        ImageBase.Visible = True
    Else
        ParentForm.Controls.Remove ImageBase.Name
    End If
End Property

Public Property Set ItemParentUF(ByVal value As MSForms.UserForm)
    Set parentUF = value
End Property

Private Property Get ParentForm() As MSForms.UserForm
    If parentUF Is Nothing Then
        Err.Description = "Grid Item Requires parent Form to be set"
        Err.Raise 5                              'no parent uf set yet
    Else
        Set ParentForm = parentUF
    End If
End Property

Public Property Get ImageBase() As MSForms.Image
    If formControl Is Nothing Then
        Set formControl = ParentForm.Controls.Add("Forms.Image.1", Name:="TestImage", Visible:=False)
    End If
    Set ImageBase = formControl
End Property

Public Property Set ImageBase(value As MSForms.Image)
    Set formControl = value
End Property

我希望制作一个 Image 控件,我可以调整其事件。

为了测试,我使用以下代码创建了一个空用户表单:

Private Sub UserForm_Initialize()

    Dim testItem As New eventsTestItem  'create event listener class
    With testItem
        Set .ItemParentUF = Me   'tell it which userform to create a new control on
        .Visible = True     'Make and display the control
    End With
    Debug.Assert Me.Controls.Count = 1 'check if control added

End Sub

运行时没有错误(即控件已创建,它在表单上也可见)。

但是事件监听器没有按预期工作,当我单击图像时应该引发该事件。我在这里缺少什么?

最佳答案

一旦 UserForm_Initialize 返回,您的 testItem 实例就会被释放。

要使其正常工作,您必须将实例存储在过程范围之外。例如,您可以将其声明为Static以保持实例处于事件状态:

Private Sub UserForm_Click()
    Static testItem As Class1

    Set testItem = New Class1  'create event listener class
    With testItem
        Set .ItemParentUF = Me   'tell it which userform to create a new control on
        .Visible = True     'Make and display the control
    End With
    Debug.Assert Me.Controls.Count = 1 'check if control added

End Sub

关于vba - 监听运行时创建的控件的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49522215/

相关文章:

c# - 在没有用户输入的情况下触发 "Click"事件

python gui 事件乱序

excel - 从所有工作表中复制范围并将它们粘贴到新的工作表中

excel - 循环遍历列表并附加结果 VBA

excel - 如何设置文本验证?

excel - 如何从工作表中的所有单元格中删除特殊字符

excel - VBA 使用递归而不是循环

excel - 如何在vba中的另一个函数中使用一个函数的变量?

excel - 如何循环复制列中空白单元格后面的数据并将其粘贴到最后一个空列?

events - 如何使用值变化监听器