View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
Chip Pearson Chip Pearson is offline
external usenet poster
 
Posts: 7,247
Default Running UserForm1 routines from UserForm 2

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]










On Fri, 12 Feb 2010 12:41:42 -0800 (PST), chuckm
wrote:

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