以下代码在表单初始化中成功创建了一个命令按钮:
create button
Dim Obj As Object
Set Obj = UserForm1.Controls.Add("Forms.CommandButton.1", "commandbuttondone", True)
With Obj
.Caption = "filled in"
.Left = 550
.Height = 40
.Width = 35
.Top = 5
End With
我认为上面创建的命令按钮命名为:" commandbuttondone",当它被点击时我希望它做某事,所以在工作表的代码中,我创建了一个子:
Private Sub commandbuttondone_Click()
'Private Sub commandbutton_Click()
'Private Sub commandbutton1_Click()
'Sub commandbuttondone_Click()
'Sub commandbutton_Click()
'Sub commandbutton1_Click()
MsgBox (nr_of_zeros)
For test1 = 1 To nr_of_zeros + 1 'create textboxes
Dim ctrl As Control
Dim absorb_text As String
' stack suggestion:
' loop through all control in user form
For Each ctrl In Me.Controls
' check if control is type TextBox
If TypeName(ctrl) = "TextBox" Then
' if control name is 1 (first created TextBox in your array)
If ctrl.name = "1" Then
absorb_text = ctrl.Text
'the message box is for debug only
MsgBox absorb_text
End If
End If
Next ctrl
Next test1
End Sub
没有任何事情发生,甚至不是msgbox(nr_of_zeros)
。在这件事上我不理解什么?表单是否不允许弹出msgbox,或者我的名字是否错误?
答案 0 :(得分:1)
您可以在运行时通过使用CommandButton
定义变量来设置Dim Cb As MSForms.CommandButton
,然后将其设置为Set Cb = UserForm1.Controls.Add("Forms.CommandButton.1", "commandbuttondone", True)
,这将设置一个新的命令 - 名为“commandbuttondone”的按钮到您的User_Form1
。
然后一旦你点击它,使用下面的代码只显示一个带有命令按钮名称的消息框:
“commandbuttondone”代码:
Option Explicit
Private Sub commandbuttondone_Click()
Dim CBctrl As Control
Dim absorb_text As String
' loop through all control in user form
For Each CBctrl In Me.Controls
' check if control is type Command button
If TypeName(CBctrl) = "CommandButton" Then
' if control name is "commandbuttondone"
If CBctrl.Name = "commandbuttondone" Then
absorb_text = CBctrl.Name
'the message box is for debug only
MsgBox absorb_text
End If
End If
Next CBctrl
End Sub