听取在运行时创建的控件中的事件



我做了一个类,当将用户形式作为参数时,应该对该用户进行控制并收听其事件。

简化的类是:

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

正在发生的事情是,testItem一旦初始化表单就会出现范围。

Private Sub UserForm_Initialize()
    Dim testItem As New eventsTestItem  'procedure-scoped
    '...
End Sub

将声明移至模块级,以使其生活在适当的范围中。

相关内容

  • 没有找到相关文章

最新更新