VBA 命令按钮的名称?

VBA name of CommandButton?

以下代码在表单初始化时成功创建了一个命令按钮:

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",当它被点击时我希望它做一些事情,所以在 sheet 的代码中,我创建了一个子:

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)。这件事我有什么不明白的?是表单不允许弹出消息框,还是我写错了名字?

您可以在 运行 时通过使用 Dim Cb As MSForms.CommandButton 定义变量来创建 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