| VB 6: Using variables in different forms | |||||||||||||
| Question: How can I use the value of a variable in one form from another form? | |||||||||||||
![]() 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." |
|||||||||||||
In general, there are two ways for variables to be available for use in different forms. 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. |
|||||||||||||


