Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pass form variable to module in Excel VBA

Status
Not open for further replies.

bmquiroz

IS-IT--Management
Sep 26, 2003
207
US
Hi all,

I have a form that uses option buttons to store parameters. I need to access these parameters as variables from a module then pass them to a procedure. Problem is that I lose the variable when UserForm1 gets unloaded. I have declared the variable as Public but nothing. Can someone shed some light?

Thanks.

-B

Heres an example:

Code:
'UserForm1

Option Explicit
Public myOption As String 'Need to pass this to Module1

Private Sub cmdSubmit_Click()
    'MsgBox myOption
    Unload Me
End Sub

Private Sub optButton1_Click()
    myOption = "1"
End Sub

Private Sub optButton2_Click()
    myOption = "2"
End Sub

'Module1

Option Explicit
Public myOption As String

Sub Option_Test()

MsgBox myOption 'No variable, MsgBox is blank

End Sub
 
'Need to pass this to Module1
so, define it as Public in Module1 instead.

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Module 1
Code:
Option Explicit

Public myOption As String


Sub test()
MsgBox myOption
End Sub

Userform - nothing on it but a commandbutton. It sets the variable and unloads.
Code:
Private Sub CommandButton1_Click()
myOption = "hello world"
Unload Me
End Sub

The userform must be run FIRST. It sets the variable value. Then the Sub test() in Module 1 will return "hello world".

Look up Scope in Help.

Gerry
My paintings and sculpture
 
OOps, sorry for the typo:
so, define it as Public in Module1 only.

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
I'm getting a compile error "Ambiguous name: myOption" in UserForm1.

Anyway, what I've done as a workaround is written the variable to a cell in the worksheet under cmdSubmit_Click then retrieving it by checking the cells value in my module procedure. Messy but it works.
 
"Ambiguous name: myOption"
myOption should be defined only ONCE, in Module1.

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
As PH mentions, ambiguous name usually means a name has been used twice. In your code you had myOption declared in both the userform, and the module.

It does not have to be messy. There is a correct way to do it.

Again, look up Scope in Help.

Gerry
My paintings and sculpture
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top