Running UserForm1 routines from UserForm 2

C

chuckm

Hi,
I have 2 userforms. Userform1 works great and now I'm creating
userform2. In userform 2 I'd like to call a couple of the routines
from Userform1. Is this possible? and if yes, how should I
approach it.
Thanks
Chuck
 
R

Robert Crandal

By default, userform subroutines are private, which I think means
that they cannot be called from outside that userform module.
However, you can rename the Userform subroutines from
"Private" to "Public". (Not sure if this is a good idea or not)

Once the userform subroutine is "Public", you can simply call
any userform module as follows from anywhere:

Call UserForm1.UserForm_Activate
Call UserForm1.UserForm_Initialize

etc.... etc....
 
P

paul.robinson

Hi
In a normal code module have

Public mysub(parameterlist)
'stuff
End Sub

For each Userform simply do

Sub userform1_initialize() 'or whatever
Call mysub parameterlist
End sub

regards
Paul

Userform1 might
 
C

Chip Pearson

To do it right, you should have a reference in UserForm2 that points
back to UserForm1. For example, in UserForm1, place a command button
on the form to call up UserForm2:

' in UserForm1
Private Sub btnShowForm2_Click()
Load UserForm2
Set UserForm2.Form1Ref = Me
UserForm2.Show
End Sub

Then, in the UserForm1's code module, mark as Public the method(s) in
UserForm1 that you want to call from UserForm2. E.g.,

' in UserForm1
Public Function SquareRoot(D As Double) As Double
SquareRoot = D ^ (1 / 2)
End Function

Then, in UserForm2, create a Public variable to hold the reference to
UserForm1:

' In UserForm2
Public Form1Ref As UserForm1

Now, you can call the method in UserForm1 from code in UserForm2. The
following command button code calls SquareRoot in UserForm1.

' In UserForm2
Private Sub btnCallBackTo1_Click()
Dim D As Double
Dim E As Double
D = 9
E = Form1Ref.SquareRoot(D)
MsgBox E
End Sub

The actual linkage between the forms objects is in the line

Set UserForm2.Form1Ref = Me

Here, Form1Ref is defined as type UserForm1 and Me refers to the
instance of the object that contains the keyword Me, which is, of
course, Userform1.

All of this said, I would agree with the other replies that it might
be better to take the code out of the userform's modules and put it in
a standard module. However, if the code in UserForm1 that is called
from UserForm2 needs data that resides on UserForm1, then the
mechanism outline above would be the better approach.



Cordially,
Chip Pearson
Microsoft MVP 1998 - 2010
Pearson Software Consulting, LLC
www.cpearson.com
[email on web site]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top