首先,您需要将代码放入UserForm
. 然后你需要添加一个类来处理所有的按钮点击事件。如果您搜索“vba userform add controls runtime”,您会找到一些很好的答案,甚至在 SO 上也有一些答案。以下是您针对特定情况所做的事情:
首先在 VBE 中插入一个新的Class module
并将其命名为“ clsButton ”。在此模块中,您将添加以下代码:
Public WithEvents btn As MSForms.CommandButton
Private Sub btn_Click()
If btn.Caption = "Cancel" Then
MsgBox "Cancel"
ElseIf btn.Caption = "Enter" Then
MsgBox "Enter"
End If
End Sub
WithEvents 关键字声明了一个btn
在单击时触发事件的对象。您可以使用Caption
上面的属性,或者使用Tag
属性来区分哪个按钮实际触发了事件。
现在您需要将修改后的代码添加到用户窗体:
Public cButton As clsButton
Public coll As New Collection
Private Sub UserForm_Activate()
Dim controlbutton As CommandButton
Set controlbutton = Me.Controls.Add("Forms.CommandButton.1", "Enter", True)
With controlbutton
.Caption = "Enter"
.Name = "Enter"
.Left = 45
.Top = 80
.Height = 30
.Width = 50
.Visible = True
Set cButton = New clsButton
Set cButton.btn = controlbutton
coll.Add cButton
End With
Set controlbutton = Me.Controls.Add("Forms.CommandButton.1", "CancelButton", True)
With controlbutton
.Caption = "Cancel"
.Left = 105
.Top = 80
.Height = 30
.Width = 50
.Visible = True
Set cButton = New clsButton
Set cButton.btn = controlbutton
coll.Add cButton
End With
End Sub
我们声明了两个公共变量,一个用于保存我们刚刚创建的类的实例,另一个用于在用户窗体的生命周期中保存类实例。在 UserForm_Activate 事件中,我们为每个按钮实例化一个新的类实例并将其添加到集合中。
然后只需运行表单并单击按钮。
编辑:这是对您将 a 添加到组合中的请求的回应ComboBox
。此代码添加一个 ComboBoxclsButton
并更改Enter
按钮以显示 ComboBox 的当前值:
Public WithEvents btn As msforms.CommandButton
Public cbo As msforms.ComboBox
Private Sub btn_Click()
If btn.Caption = "Cancel" Then
MsgBox "Cancel"
ElseIf btn.Caption = "Enter" Then
MsgBox cbo.Value
End If
End Sub
更改表单代码以创建 ComboBox,用一些值填充它,并将选择设置为其项目。然后在Enter
创建按钮时cbo
为其类实例设置属性。取消按钮代码不变:
Public cButton As clsButton
Public coll As New Collection
Private Sub UserForm_Activate()
Dim controlButton As msforms.CommandButton
Dim controlCombo As msforms.ComboBox
Dim i As Long
Set controlCombo = Me.Controls.Add("Forms.ComboBox.1", "Combo", True)
With controlCombo
For i = 1 To 10
.AddItem i
Next i
.ListIndex = 0
End With
Set controlButton = Me.Controls.Add("Forms.CommandButton.1", "Enter", True)
With controlButton
.Caption = "Enter"
.Name = "Enter"
.Left = 45
.Top = 80
.Height = 30
.Width = 50
.Visible = True
Set cButton = New clsButton
Set cButton.btn = controlButton
Set cButton.cbo = controlCombo
coll.Add cButton
End With
Set controlButton = Me.Controls.Add("Forms.CommandButton.1", "CancelButton", True)
With controlButton
.Caption = "Cancel"
.Left = 105
.Top = 80
.Height = 30
.Width = 50
.Visible = True
Set cButton = New clsButton
Set cButton.btn = controlButton
coll.Add cButton
End With
End Sub
因此,总而言之,我们在类中添加了一个 ComboBox,并将其添加到 Enter 按钮的类实例中,以便 btn 可以与它“对话”。