Search code examples
vbadynamicuserform

Change value of dynamically created UserForm element


This is a followup on my first question:

Through a click event, I dynamically added some elements (txtBox01 and cmdButton01) to the previously empty (static) UserForm1. Now I want to change the textbox's content through the click event of cmdButton01. How exactly do I have to reference cmdButton01?

Here's how I create the dynamic elements (simplified!):

Private Sub CommandButton1_Click()    
    
    Dim cmdArray() As New Class1
    i = 1       
        
        'Layout for static Form
            'Set Formsize / Formtitle
                UserForm1.Height = 130
                UserForm1.Width = 300

            'Create Form-Elements (TextBox1)
                Dim txtBox01 As MSForms.TextBox
                Set txtBox01 = UserForm1.Controls.Add("Forms.TextBox.1", "dynTxtBox_01")
                txtBox01.Top = 10
                txtBox01.Left = 10
                txtBox01.Width = 200
                txtBox01.Text = "something"

            'Create Form-Elements (Commandbutton)
                Dim cmdButton01 As MSForms.CommandButton
                Set cmdButton01 = UserForm13.Controls.Add("Forms.CommandButton.1", "dynCmdButton01", False)
                cmdButton01.Top = 70
                cmdButton01.Left = 10
                cmdButton01.Width = 200
                cmdButton01.Caption = "Save"
                cmdButton01.Visible = True

                ReDim Preserve cmdArray(1 To i)
                Set cmdArray(i).CmdEvents = cmdButton01
                Set cmdButton01 = Nothing                    

        'Show Form
            UserForm1.Show

    End Sub

I assigned the code for the click event through the following code. But I'm not sure how to reference the dynamic elements on the static form. I tried a few examples I found on the web but nothing worked:

Public WithEvents CmdEvents As MSForms.CommandButton    
Private Sub CmdEvents_Click()

    'Simple Test (works fine)
        MsgBox "Test1"

    'Change the Text of TextBox01 (this one is PSEUDO code to illustrate what I want to do)
         UserForm1.txtBox01.Text= "123"       
         '=> how should I reference the dynamic form element to make this work??
         
     'Close Form
        UserForm1.Hide

    End Sub

Solution

  • To answer your specific question, the syntax would be like the following:

    UserForm1.Controls("dynTxtBox_01").Text = "123"