以下代码成功地在窗体初始化过程中创建了一个命令按钮:
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我认为上面创建的命令按钮的名称是:“命令按钮”,当单击它时,我希望它做一些事情,所以在工作表的代码中,我创建了一个子:
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,还是我弄错了名称?
发布于 2016-12-11 18:39:36
您可以在运行时通过使用Dim Cb As MSForms.CommandButton定义变量来创建Dim Cb As MSForms.CommandButton,然后用Set Cb = UserForm1.Controls.Add("Forms.CommandButton.1", "commandbuttondone", True)设置它,这将为User_Form1设置一个新的命令按钮,名为“命令按钮”。
然后单击它,使用下面的代码显示一个带有命令按钮名称的消息框:
“命令按钮”代码
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 Subhttps://stackoverflow.com/questions/41087942
复制相似问题