1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

VB 6: Using variables in different forms
Question: How can I use the value of a variable in one form from another form?
Message Boxes

Ricky asked, "I assign a value to a variable in one form, but I need to use the value in different form. When I use the same name in the second form, Visual Basic tells me that the variable hasn't been assigned a value."

 Join the Discussion
Add to the FAQ!
Discuss this at the
About.Com Forum
 Related Articles
• The TicTacToe Game
A VB6 Example that uses Global variables


In general, there are two ways for variables to be available for use in different forms.

  1. Increase the scope of the variable so it is known to both objects.
  2. Pass the variable as a parameter when the object is referenced.
Project Explorer

Method 1 is the Global variable. Add a module to your project. Then declare the variable as a Public variable in the Declarations section of a module that you add you your project and it will be available in both forms.

Method 2 is normally a function or subroutine call. This is preferred in most cases because the value assigned to all variables is carefully controlled and it's not as easy for bugs to sneak into your program.

The following example shows both methods. First, the variable GlobalVar which is declared in Module1 is assigned a value in Form1 and displayed in a message box from Form2. Then a string value in the parameter Y is passed to the function MyFunction in Form2 and displayed there. Finally, the function return value assigned in Form2 is passed back to Form1 and displayed there.

Code for Forms and Module

©2017 About.com. All rights reserved.