Search code examples
excelvbauserform

Display alternate UserForm dependent on variable


I want to display a specific UserForm dependent on the UserName environment variable. I update the userform in various places throughout the code so I thought it would be easiest (and trivial) to create two independent userforms (with wildly different designs) then use logic to "Set" a UserForm object variable at the beginning of the code. I'm clearly misunderstanding something here, cause when it gets to the .Show command, VBA errors:

Dim usrForm As UserForm

If Environ("UserName") = "redacted" Then
    Set usrForm = LlamaForm 'for specific user, form styled differently including picture of Llama
Else
    Set usrForm = NormalForm 'for EVERYONE ELSE, normal professional looking form
End If

With usrForm 'initialize UserForm and display wait message
    .Cancelbutton.Visible = False
    .Proceedbutton.Visible = False
    .Exitbutton.Visible = False 
    .labmsg.Caption = Chr(10) & Chr(10) & Chr(10) & "Starting background processes, please wait..."
    .Show vbModeless
End With

Am I making this too complicated? I was really hoping to just change the referenced form object at the beginning rather than introducing logic with redundant code each time I need to update the user. Any ideas or improvement would be appreciated. Caveat is, because they are wildly different layout/design, I would really like to keep two separate userforms rather than manipulating a single one (which I know can be done, but that is more work at this point compared to understanding why my method above isn't working.)


Solution

  • You can use a generic object, but you lose the early binding features

    Try this code

    Option Explicit
    
    Public Sub ShowUserForm()
    
        ' You can use a generic object, but you lose the early binding features
        Dim myUserForm As Object
    
        If Environ("UserName") = "redacted" Then
            Set myUserForm = New LlamaForm 
        Else
            Set myUserForm = New NormalForm 
        End If
    
        myUserForm.Show
    
    End Sub
    

    Let me know if it works