Continue to Site

Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

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

How to use one variable created in form1 in another form (form2)

Status
Not open for further replies.

esteva

Mechanical
Jun 28, 2001
20

I have been making some basic programs in Visual Basic. One of the problems I have and I havent solved is when I create a variable (example variable "a") in my first form (form1), then when I create another form. If I want to use the value calculated in form1 for the "a" variable in my new form2 to calculate another variable "b". How can I pass one varible from one form to another?
 
Replies continue below

Recommended for you

Declare the variable as global in your main module. Then, you can set the value in Form1 and use the value in Form2.
Code:
'Main Module

Public VarA As Single

Sub Main()

    Form1.Show 1

    Form2.Show 1

End Sub

'Form 1
Private Sub cmdOK_Click()
    'Get the value for A
    VarA = CSng(Text1.Text)
End Sub

'Form 2
Private Sub Form_Load()
    'Calculate value B and show it
    VarB = Sqr(VarA)
    Text1.Text = Format(VarB,"##0.0##)
End Sub
DimensionalSolutions@Core.com
While I welcome e-mail messages, please post all thread activity in these forums for the benefit of all members.
 
Do I have to show both forms at the begining?. Can I show the form2 after getting value a?
Sub Main()

Form1.Show 1

Form2.Show 1

End Sub
 
Yes, that is what the example was to represent. To expand on the previous example, try this test project. It will show a form (Form1) and allow you to enter a number (VarA). Then, it will calculate a new value (VarB) and show the result in Form2.

Insert a Module and this code:
Code:
Public VarA As Single
Public VarB As Single

Sub Main()

    Form1.Show 1

    VarB = 2 * VarA

    Form2.Show 1

    End

End Sub
Insert a Form (name it Form1)
Insert a Label with the string "Enter a Number:"
Insert a TextBox (Text1)
Insert a Command Button (cmdOK)
Insert this code:
Code:
Private Sub cmdOK_Click()
    'Get the value for A
    VarA = CSng(Text1.Text)

    Unload Me
End Sub
Insert a Form (name it Form2)
Insert a Label with the string "New Value:"
Insert a TextBox (Text1)
Insert a Command Button (cmdOK)
Insert this code:
Code:
Private Sub Form_Load()
    'Show the New Value (B)
    Text1.Text = CStr(VarB)
End Sub

Private Sub cmdOK_Click()
    Unload Me
End Sub
DimensionalSolutions@Core.com
While I welcome e-mail messages, please post all thread activity in these forums for the benefit of all members.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor