Search code examples
vbauserform

VBA - Userform name to cell value


help me: I have 2 UserForms: UF123 and UF456
I want call name from Sheet6.Cells(11, 12) = UF123 or UF456 : UForm = Sheet6.Cells(11, 12).Value
I want set UserForms(UForm).ComboBox5.Value = abc but it not run.

Dim UForm As String 
UForm = Sheet6.Cells(11, 12).Value           
UserForms(UForm).ComboBox5.Value = 5

Solution

  • Note that this cannot work as UserForms only contains userforms that are actually shown at the moment.

    You can easily test this by

    Debug.Print VBA.UserForms.Count
    

    it will show 0 if no userform is shown and if you do

    UF123.Show vbModeless
    Debug.Print VBA.UserForms.Count
    

    it will show 1.

    Also you cannot access it by its name using UserForms("UF123") this is not supported.
    So there is only a workaround:

    Dim UForm As Object
    
    Select Case Sheet6.Cells(11, 12).Value
        Case "UF123"
            Set UForm = New UF123
            
        Case "UF456"
            Set UForm = New UF456
            
        Case Else
            MsgBox "not found"
    End Select
    
    UForm.ComboBox5.Value = 5
    UForm.Show
    
    Set UForm = Nothing