I have a userform that dynamically places a commandButton
onto the user form but I can't seem to get the dynamic event handler set up properly: Below shows the code for how I have set up the dynamic button:
我有一个userform,它动态地将commandButton放到用户表单上,但我似乎无法正确设置动态事件处理程序:下面显示了我如何设置动态按钮的代码:
Set cButton = Me.Controls.Add("Forms.CommandButton.1")
With cButton
.Left = 150
.Top = 0
.Width = 300
.Height = 140
End With
I have also defined dim WithEvents cButton as Commandbutton
outside of any sub or procedure and then finally I have the event handler for the dynamic button, which I simply want to output a message for now:
我还在任何子程序或过程之外定义了dim WithEvents cButton作为Command按钮,然后最后我有动态按钮的事件处理程序,我现在只想输出一条消息:
Private Sub cButton_Click()
MsgBox "Dynamic Handler functioning correctly"
End Sub
Now that I am able to create event handlers for dynamic events for individual controls, however I am creating multiple controls and they all have the same name cButton
so how would I be able to create individual event handlers for each of them. Below shows the code that is used to create the multiple controls:
既然我能够为单个控件创建动态事件的事件处理程序,但是我创建了多个控件并且它们都具有相同的名称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
1 个解决方案
#1
2
cButton
should only be declared once:
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
#1
2
cButton
should only be declared once:
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