Link to home
Start Free TrialLog in
Avatar of winson
winson

asked on

passing a value from a form to another form

i had problem passing a value that had obtain in a form
then i had to use the value in another form
how do i do that ?
i know that i can declare it in the first form
but the value of the variable can't be send to another form
please help me
ASKER CERTIFIED SOLUTION
Avatar of deighton
deighton
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of caraf_g
caraf_g

deighton's answer works, but I spotted a small typing error
it should read:
- in form2, reference the variable as form1.Myvar
- msgbox cstr(form1.Myvar)

With this minor modification, his code works, and for that he deserves to have his answer accepted.

Another solution might be to define Myvar in an ordinary VB module, and define it as a Public or a Global variable:
Public Myvar As Integer 'or
Global Myvar As Integer
That way it is available to both form1 and form2

There are some "advanced" VB considerations that are not be a problem to you if you are only beginning to learn VB but could become more important later.

"form1" and "form2" should be regarded as "Classes" defined in VB.

From a "purist" point of view you are doing something iffy when you are referring to the "Class names" form1 and form2 as if they are actual object variables. That is what you are doing when you are using form1 and form2 in statements such as
form1.Show
form1.Myvar = Value

But VB does allow you to do it, so it's OK.

If you want to start using multiple instances of a form however, it becomes very important to avoid using this "implicit" behaviour. A couple of rules of thumb:

1 Only use "form1" (or whatever you decided to name the form) after an "As", and declare object variables to refer to instances of this class:
   Dim objFrmMain As Form1
   Public objX As Form1
   Private objY As New Form1

2 If you haven't used the New keyword in the declaration, you must use it in a Set statement before you can start using one of these object variables:
    Set objX = New Form1

3 Within the code module for form1, use the Me keyword whenever you have to refer to the current instance of this class:
   Unload Me  ', not Unload form1

4 When you need to access variables such as the variable Myvar in your example, refer to the correct object variable
   objY.Myvar