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 derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do you share a variable to different forms?(I a newbie) 7

Status
Not open for further replies.
Declare them as Common or Global in a module.
VCA.gif

Alt255@Vorpalcom.Intranets.com
 
Hi

I'm not so sure if Common will work as I've never come across that Visual Basic Keyword before. My apologies to ALT255 if it does indeed exist in your version of VB.

As ALT255 suggested you could declare it as Global within
a module. For example

Module1 ->
Code:
Public x As Integer 'u can use Global as well

Form1 ->
Code:
Msgbox x
Form2 ->
Code:
Msgbox x

Using that method you can then reference the variable directly by it's name. (It's probably the easiest method)

Another way is to declare the variable as Public within a form. For example
Form1 ->
Code:
Public x As Integer
Form2 ->
Code:
Msgbox Form1.x

Another way is to declare the variable as Private within
the Form and use Public Property Get/Let to access the value.For example

Form1 ->
Code:
Private x As Integer
Form1 ->
Code:
Public Property Get SharedVariable() As Integer
Form1 ->
Code:
SharedVariable = x
Form1 ->
Code:
End Property

Form2 ->
Code:
Msgbox Form1.SharedVariable

The choice is up to you :)

Have fun
caf
 
Sorry about that. I was in a hurry, had a VB window a QB45 window and Tek-Tips open at the same time.

A little confusion with the QB COMMON declaration and the VB Global.

Don't laugh too hard, guys. It could happen to you.
VCA.gif

Alt255@Vorpalcom.Intranets.com
 
You could also add a module to your application, if you plan on using one anyways.
Just put

Code:
Public varname as vartype

put it in the declarations section, then you can access it from anywhere in the program just by typing its name.

The only drawback to this is that you might accidently change that variable someplace else and not relize it. lol, I've done it.
DarkMercenary
darkmercenary44@earthlink.net

In the real world

As in dreams

Nothing is quite

What it seems

:Book of Counted Sorrows
 
Declaring a global variable to transfer information between forms is the easiest, but certainly not the best way.  This is especially true in complex projects.

Look for an alternative method using form properties:

1. Declare a Public Property in the First form with Property Get/Let procedure.
2. Initialize that variable

3. Accept that property of the first form in the initialize event of the second one.

4. Unload the first form.

Sample code below shows ho to transfer the contents of a textbox (txtOne) on frmOne to a label (lblTwo) on frmTwo.
The property is called FormValue and declared as a Variant. (adapt name and type to suit your needs)

Code for frmOne:

Option Explicit
Private m_vntFormValue As Variant

Public Property Get FormValue() As Variant
FormValue = m_vntFormValue
End Property

Public Property Let FormValue(fv As Variant)
m_vntFormValue = fv
End Property

Private Sub cmdTranfer_Click()
Me.FormValue = txtOne.TextLoad
frmTwofrmTwo.Show vbModal
Unload Me
End Sub

Code for frmTwo:

Option Explicit
Private Sub Form_Initialize()
lblTwo.Caption = frmOne.FormValue
End Sub

It does take some more time to code, but your value is protected against accidental modifications by other forms or modules, which results in huge savings at maintenance time.  Of course this pre-supposes that your program will be subjected to maintenance at some future time, which is not un unreasable supposition...
robert


Declaring a global variable to transfer information between forms is the easiest, but certainly not the best way.  This is especially true in complex projects.

Look for an alternative method using form properties:

1. Declare a Public Property in the First form with Property Get/Let procedure.
2. Initialize that variable

3. Accept that property of the first form in the initialize event of the second one.

4. Unload the first form.

Sample code below shows ho to transfer the contents of a textbox (txtOne) on frmOne to a label (lblTwo) on frmTwo.
The property is called FormValue and declared as a Variant. (adapt name and type to suit your needs)

Code for frmOne:

Option Explicit
Private m_vntFormValue As Variant

Public Property Get FormValue() As Variant
FormValue = m_vntFormValue
End Property

Public Property Let FormValue(fv As Variant)
m_vntFormValue = fv
End Property

Private Sub cmdTranfer_Click()
Me.FormValue = txtOne.TextLoad
frmTwofrmTwo.Show vbModal
Unload Me
End Sub

Code for frmTwo:

Option Explicit
Private Sub Form_Initialize()
lblTwo.Caption = frmOne.FormValue
End Sub

It does take some more time to code, but your value is protected against accidental modifications by other forms or modules, which results in huge savings at maintenance time.  Of course this pre-supposes that your program will be subjected to maintenance at some future time, which is not un unreasable supposition...
robert


 
You heard the word. I couldn't contribute much but we had a visitor walk away with the right tools in his hand.

Makes me feel all warm and fuzzy. (Seriously)
VCA.gif

Alt255@Vorpalcom.Intranets.com
 
My two cents

Another nice thing about using Property Let/Get is that you can reference those properties without that Form's Form_Load event executing and loding it in memory

In other words (code is worth a thousand words) ;-)

You have Form1 & Module1

Form1's Code

Option Explicit

Private m_SomeVariable As String

Public Property Get SomeValue() As String
SomeValue = m_SomeVariable
End Property

Public Property Let SomeValue(sv As String)
m_SomeVariable = sv
End Property

Here's Module1 Code

Option Explicit

Private Sub Main()

With Form1
.SomeValue = "Craig"
End With

Msgbox Form1.SomeValue

End Sub

'The above code will go ahead without loading Form1
'You can test it by placing a breakpoint(or msgbox) in the
'Form_Load event

Please note that if you should reference a text box or some other intrinsic control/property then the Form_Load fires

The example I provided doesn't make sense in the real world it's just an example. You obviously have to something more than that for your program to be more useful.

For instance say the form you're about to show need some information to be passed to it

You can use Property Let's so that if an error occurs you don't sit with a loaded form that's hidden and you wonder why your app hangs

DO NOT use End to terminate your program
Force is a crime ;-)

 
hi, i also have a related doubt on sharing a variable´s content among forms. here´s the deal: i have to evaluate a process based on the user´s answers, each stored on a variable which are on different forms, at the end of the program the results must be added and the result displayed, now, i have already the program, the issue is that i can´t import the variables to the last form to add the pre-results. i´ld appreciate if anyone could HELP ME !!!!

happy.gif
 
after starting with STANDARD EXE, go to PROJECT menu , add module in your project by clicking "add module" menuitem .
then u will get "module1" in your project explorer. click on "module1", now in code window , declare some variable as
PUBLIC MYVAR1 AS INTEGER
variable declaration must be having PUBLIC access specifier.
after this , you can access MYVAR1 in any of your forms.

if you want to initialize it to some value before using in any other form,
In "module1",
add on subroutine main, for example,
****************
sub main()
var1=24
end sub
***************
after this, whenever u will access this MYVAR1 in any of your forms, its default value will be 24, but it can be manipulated.
 
golososo, w_raj,

You should NOT use Public variables to share data between forms. The following sample code shows how to solve the Subtotals problem: The first code section is for the form into which the subtotal is entered or generated. It contains a Public Property Get procedure, which is used to transfer the Subtotal value to the Main (Total) form. There is NO Public Property LET procedure to avoid modifying this value from the outside.

Option Explicit
Private m_intSubTotal As Integer

Public Property Get Subtotal() As Integer
Subtotal = m_intSubTotal
End Property

Private Sub Form_Unload(Cancel As Integer)
With txtSubTotal
Select Case IsNumeric(.Text)
Case True
m_intSubTotal = CInt(.Text)
Case False
MsgBox "Non-Numeric Entry, Rejected", , Me.Caption
m_intSubTotal = 0
End Select
End With
End Sub

After entering a numeric value, close the form.

The Main procedure will generate three Subforms and Total the Values. It contains a label (for displaying the total) and a command button to activate the process:

Private Sub cmdSum_Click()
Dim frm As frmSubTotal
Dim intTotal As Integer
intTotal = 0
lblTotal.Caption = "0"

MsgBox "Three Forms Will be Shown" & vbCrLf & _
"Enter a valid Integer in each"

'Calculate Running Total on the fly
Dim intIndex As Integer
For intIndex = 1 To 3
Set frm = New frmSubTotal
frm.Caption = "#" & CStr(intIndex)
frm.Show vbModal
intTotal = intTotal + frm.Subtotal
Next intIndex
lblTotal.Caption = CStr(intTotal)
End Sub

The procedures are deliberately kept simple to show the method. Try it, You'll be amazed by its flexibility.
 
That's pretty sneaky, rvBasic. Could you summarize the benefits obtained by the good programming practice of maintaining private variables?

This is something many of us neglect. We were raised in programming environments that called for a "top down" program flow. The value of any variable was predictable at any point. Our world is much more complex now and we tend to take shortcuts to simplify matters.

I think the subject would make a good FAQ.
VCA.gif

Alt255@Vorpalcom.Intranets.com
 
The subject you are talking about, in OOP (Object Oriented Programming for the neophytes) is called "Data Hiding".

The basic idea is that almost all objects have certain data that should be manipulated by other objects, but they also have data that is used internally and should not be modified , or possibly even seen (called exposed).

An example is an order entry object. Internally it may maintain a private Order_ID value. This order_ID value is maintained at the database level and never needs to be accessed by higher level functions. It exposes (read_only) the Order_Number that is associated with that order, which is human readable, but still shouldn't be modified by other processes. It also exposes (read/write) the customer_number, which can be changed by other objects. Order_date would be exposed read_only as well.

There are a number of reasons this is done.
First it protects the programmer from having to wade through possibly hundreds of properties that they can't use anyway, and second makes it possible to share those properties with objects that really need them, which are known as "Friends". It helps to eliminate bugs where you aren't sure where in the program something changed an important variable that should not have been modified. And lastly, and probably most importantly, it makes the program more readable.

Hope that helps..
 
I think the subject would make a good FAQ.

You mean the value of hiding data? Because I've already written a FAQ on transferring values from one form to another.

Chip H.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top