-
Hi,
This should be a simple question, hopefully I get a reply :)
I have 2 forms, and I need to pass a variable from one form to the other form.
How do I do this?
For example, in form2, this is the screen where I ask a user to enter file location..... ie: C:\Mydocuments\text.txt
I want this information to be available in my form1.
How do I write the code? I'm not using modules, just forms...
-
Store it in the form's Tag property. For example, make a Form with a CommandButton on it.
Code:
Private Sub Command1_Click()
Form2.Tag = "C:\MyFile"
Form2.Show
End Sub
On Form2, make another CommandButton and put this code in it.
Code:
Private Sub Command1_Click()
Print Me.Tag
End Sub
-
variable
just declare a public variable to store your info
'main form
Option Explicit
Public strHolder as string
you can give it value from either form
and it will retain it's value over both
strHolder = text1.text '("C:\Mydocuments\text.txt")
It's now available to all...
-
Using Tag is better, because you no need to declare any public variable.
-
Both ways work!
You can declare it through "Tag" property, but it will be hard to keep track in the future if your program is large.
You can declare it as "Public" but it will take up resource for the variable.
You have a choice between
-being Resource Saving
or
-being Organize.
I would go for "Public" if you are not advance with VB yet.
Make sure if you use "Public", make good practice to declare in a separate module strictly for global and constant variables. This will keep it organize.
-
If you are only going to store one Public variable, than making a seperate module just to store one variable is not necessary. It'll be better to use the Tag in this case.
-
If Form2 has not been unloaded (it can be hidden), the simplest thing to do is to directly refer to contents of the field on Form2. So assuming that your user enters data into Text1 just do something like MsgBox "Path = " & Form2.Text1.Text
-
A variation on Martin's answer is to do the following ...
.
.
.
form2.txtName = strName
form2.show 1
.
.
.
VB will automatically load form2 when the control is referenced on it and you can avoid the use of either tag or a global variable. However, if the value is not going into a field on form2 then use the tag property, it's 'cleaner'.