Maximilian brutus III
Maximilian brutus III

Reputation: 703

Loading different Userforms sequentially

I am confused by the procedure to call two different userforms at different times from different modules.

I have the following two userforms named: "UserForm1" and "UserForm2", on "UserForm1" I also have a static button with code named: "Private Sub UserForm_Click()"

The subs from the forms contain the following code:

Via name: UserForm1:

[On userform1 I have a button:]

private sub OKButton_Click()
msgbox("OKButton_Click via 1")
End Sub

Public Sub UserForm1_Initialize()
msgbox("UserForm1_Initialize via 1")
'dynamic form initialisation
End Sub

Private Sub UserForm_Click()
msgbox("UserForm_Click via 1")
End Sub

VIA name: UserForm2

Public Sub UserForm_Initialize()
msgbox("UserForm_Initialize via 2")
'dynamic form initialisation
End Sub

And I call the two userforms in:

Module57
Sub Vitamins()
UserForm2.Show 'Initialising Userform2
end sub

Module53
Sub fix_ratios()
UserForm1.Show 'Initialising Userform1
end sub

The problem occurs when I call either one, at first I could not call Userform2 when UserForm1 worked fine, so I altered the name and code of UserForm2 by doubleclicking the object of UserForm2, which then created the new code:

Private Sub UserForm_Initialize()

End Sub

So I pasted my code for initializing UserForm2 in there, it worked fine. But I now realise that it just steals the "UserForm_Initialize()" from the first UserForm.

So I tried altering the subnames to:

Public Sub UserForm1_Initialize()

end sub

and

Public Sub UserForm2_Initialize()

end sub

But then it won't call the UserForms anymore. Would anyone have a suggestion, or be able to tell me what I'm doing wrong?

Upvotes: 0

Views: 1514

Answers (1)

Maximilian brutus III
Maximilian brutus III

Reputation: 703

The solution was like tlemaster suggested:

Having the seperate subs for each form in the form which it belongs in. (This is not a module, but visual in the top view of the editor displaying " -[UserFormx (code)].

On top of that, once you use: userformx.show in a different module, it will first excecute:

Sub Userform_Initialize()

Then once that has been completed it will show the userformx.

If the Sub Userform_Initialize() is named Sub Userform_Initialise() it will not excecute the sub, and it will simply show the uninitialized sub.

If you click "view object" on the userform, and then doubleclick the form template, it will generate/go to the code:

Sub userform(x?)_clicked()

This will also not be executed before displaying the userformx.

On top of that, one can have two identically named subs:

Sub Userform_Initialize()

Sub Userform_Initialize()

As long as they are in different "Forms" /Form codes then Excel will automatically execute the initialisation of the form that is called from any random unrelated module with: "UserformY.Show"

Enjoy.

Upvotes: 1

Related Questions