Search code examples
vbaexcelcommandbutton

VBA name of CommandButton?


The following code succesfully creates a commandbutton in the initialisation of a form:

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

I think the above created commandbutton is named: "commandbuttondone", and when it is clicked I want it to do something, so in the code for the sheet, I created a sub:

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

And nothing happens, not even the msgbox(nr_of_zeros). What don't I comprehend in this matter? Does the form not allow a msgbox to pop up, or did I get the name wrong?


Solution

  • You can create the CommandButton at run-time with setting by defining a variable with Dim Cb As MSForms.CommandButton , and then later set it with Set Cb = UserForm1.Controls.Add("Forms.CommandButton.1", "commandbuttondone", True) , this will set-up a new Command-button named "commandbuttondone" to your User_Form1.

    Then once you click on it, use the code below just to display a message box with the Command button's name:

    "commandbuttondone" code:

    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