Search code examples
excelvbauserform

Userform not initializating despite proper header


I'm attempting to write a new UserForm that loads controls upon initialization.

For whatever reason the test module I've written does not load anything within the UserForm on runtime although the UserForm itself does appear.

Module code:

Sub test()

Dim check As New UserForm1

Load check
check.Show

End Sub

UserForm code:

Private Sub UserForm_Initialize()

Dim submit As MSForms.CommandButton
Set submit = UserForm1.Controls.Add("Forms.CommandButton.1", "Submit")

With submit
    .Caption = "Submit"
End With

End Sub

No button appears when I run the module, however, when I run the UserForm code directly it initializes properly. Any advice?


Solution

  • Set submit = UserForm1.Controls.Add("Forms.CommandButton.1", "Submit")
    

    That is adding the button... just not on the check instance.

    See UserForm1.Show; by referencing UserForm1 in the UserForm1 module, you've referred to that form's default instance, which may or may not be the instance that's currently being initialized.

    This should fix it:

    Set submit = Me.Controls.Add("Forms.CommandButton.1", "Submit")
    

    A UserForm module is a class, with a visual designer component and a VB_PredeclaredId attribute value set to True. The predeclared instance is the result of that hidden VB_PredeclaredId attribute value, and as per language specifications its name matches the name of the class itself, i.e. UserForm1. By using Me as a qualifier instead of UserForm1, you refer to whatever instance is currently running, as opposed to the class' default instance.

    Avoid referring to the default instance in a form's code-behind.