我有一个用户表单,可以动态地将commandButton
放到用户表单上,但我似乎无法正确设置动态事件处理程序:下面显示了我如何设置动态按钮的代码:
Set cButton = Me.Controls.Add("Forms.CommandButton.1")
With cButton
.Left = 150
.Top = 0
.Width = 300
.Height = 140
End With
我还在任何子程序或过程之外定义了dim WithEvents cButton as Commandbutton
,然后我最终得到了动态按钮的事件处理程序,我现在只想输出一条消息:
Private Sub cButton_Click()
MsgBox "Dynamic Handler functioning correctly"
End Sub
现在我能够为单个控件创建动态事件的事件处理程序,但是我创建了多个控件并且它们都具有相同的名称cButton
所以我如何才能为每个控件创建单独的事件处理程序他们下面显示了用于创建多个控件的代码:
If TextBox1 <> vbNullString Then
For i = 1 To TextBox1.Value
Set cButton = Me.Controls.Add("Forms.CommandButton.1")
With cButton
.Left = 150
.Top = 0
.Width = 300
.Height = 140
End With
Next i
End IF
答案 0 :(得分:2)
cButton
只应声明一次:
Dim WithEvents cButton As CommandButton
Sub UserForm_Initialize()
Set cButton = Me.Controls.Add("Forms.CommandButton.1")
With cButton
.Left = 150
.Top = 0
.Width = 300
.Height = 140
End With
End Sub
Private Sub cButton_Click()
MsgBox "Dynamic Handler functioning correctly"
End Sub