Search code examples
excelvbauserform

Refer to ComboBox that is just created after user input


i am trying to have VBA create a user form and based off of what selection you choose populate more selections.

the following code is my initial user form and i have it adding Comboboxes Based on whatever selection is chosen.

Private Sub UserForm_Initialize()
   ComboBox1.AddItem "Selection1"
   ComboBox1.AddItem "Selection2"
   ComboBox1.AddItem "Selection3"
   ComboBox1.FontSize = 13
End Sub

But i have it going to comboboxchange to do so

Private Sub ComboBox1_Change()

'Here i have some Working Code That Adds another ComboBox
Dim MsgType As Control

Set MsgType = UserForm2.Controls.Add("Forms.ComboBox.1")
With MsgType
.Height = 25
.Width = 300
.Top = 75
.Left = 20
.FontSize = 13
.Name = "vmtype"
.AddItem "Selection1"
.AddItem "Selection2"

Debug.Print .Value
End With

EndSub

I now need to have a private sub refer to this combo box just as "Private Sub ComboBox1_Change()" had. that way i can add more items depending on that selection.

What i have so far is the following.

Private Sub ComboBox2_Change()

 Dim Notetype As String
 Notetype = ComboBox1.Value
 Debug.Print Notetype

End Sub

But it is not actually refering to the newly created Combo Box any idea how i can Fix this?


Solution

  • Use WithEvents to listen for dynamically added controls.

    Here is a simple example where you are just adding a single control:

    Private WithEvents vmtype As MSForms.ComboBox
    
    Private Sub vmtype_Change()
        Debug.Print MsgType
    End Sub
    
    Private Sub ComboBox1_Change()
    
        Set vmtype = UserForm2.Controls.Add("Forms.ComboBox.1")
        With vmtype
            .Height = 25
            .Width = 300
            .Top = 75
            .Left = 20
            .FontSize = 13
            .Name = "vmtype"
            .AddItem "Selection1"
            .AddItem "Selection2"
        End With
    
    End Sub
    

    Consider using a custom class when adding many control. See my post: Responding to Events of Dynamically added Controls