gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:40:23 25 4
gpt4 key购买 nike

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

简化的类是这样的:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com