分配给动态创建的按钮的事件在
showmodal=True
时起作用。
我需要在用户表单打开时使用应用程序。
下面是子模块和类模块。
Sub tests()
Dim i As Integer
Dim MyB As MSForms.Control
Dim btnEvent As MyCustomButton
Dim colButtons As Collection
Set colButtons = New Collection
For i = 1 To 7
Set MyB = UserForm1.Controls.Add("Forms.CommandButton.1")
With MyB
.Name = "dugme" & i
.Caption = "Captiones" & i
.Left = 10
.Top = 25 * i
.Width = 75
.Height = 20
.Tag = "tagi" & i
End With
Set btnEvent = New MyCustomButton
Set btnEvent.btn = MyB
Set btnEvent.frm = UserForm1
colButtons.Add btnEvent
Next i
UserForm1.Show
End Sub
--- 类模块 MyCustomButton--------
Public WithEvents btn As MSForms.CommandButton
Public frm As UserForm
Private Sub btn_Click()
MsgBox btn.Name
End Sub
我尝试理解并实现此处建议的解决方案:功能化事件驱动的无模式用户表单类
我的情况应该简单得多。
我想我的评论不够清楚。当然,还必须删除或替换
Set colButtons = New Collection
,否则总是会创建集合的一个新实例(这是正确的英文单词吗?)。
我的完整建议是更改发布的代码如下
Option Explicit
' the New keyword will take care that a new instance is created if needed
Dim colButtons As New Collection
Sub tests()
Dim i As Integer
Dim MyB As MSForms.Control
Dim btnEvent As MyCustomButton
' Dim colButtons As Collection
' Set colButtons = New Collection
For i = 1 To 7
Set MyB = UserForm1.Controls.Add("Forms.CommandButton.1")
With MyB
.Name = "dugme" & i
.Caption = "Captiones" & i
.Left = 10
.Top = 25 * i
.Width = 75
.Height = 20
.Tag = "tagi" & i
End With
Set btnEvent = New MyCustomButton
Set btnEvent.btn = MyB
Set btnEvent.frm = UserForm1
colButtons.Add btnEvent
Next i
UserForm1.Show vbModeless
End Sub
另一种方法是检查是否已经存在这样的活动实例
Option Explicit
Dim colButtons As Collection
Sub tests()
Dim i As Integer
Dim MyB As MSForms.Control
Dim btnEvent As MyCustomButton
' Dim colButtons As Collection
' Set colButtons = New Collection
If colButtons Is Nothing Then
Set colButtons = New Collection
End If
For i = 1 To 7
Set MyB = UserForm1.Controls.Add("Forms.CommandButton.1")
With MyB
.Name = "dugme" & i
.Caption = "Captiones" & i
.Left = 10
.Top = 25 * i
.Width = 75
.Height = 20
.Tag = "tagi" & i
End With
Set btnEvent = New MyCustomButton
Set btnEvent.btn = MyB
Set btnEvent.frm = UserForm1
colButtons.Add btnEvent
Next i
UserForm1.Show vbModeless
End Sub
的内容