I want to create a variable that can be used across multiple forms.
It's going to be a temporary storage place for integers.
The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.
Option Explicit statement You can implicitly declare a variable in Visual Basic simply by using it in an assignment statement. All variables that are implicitly declared are of type Variant. Variables of type Variant require more memory resources than most other variables.
Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program.
There are a couple of ways to do this in VB: a VB-specific way and a non-VB specific way (i.e. one that could also be implemented in C#.
The VB-specific way is to create a module and place the variable in the module:
Public Module GlobalVariables
Public MyGlobalString As String
End Module
The non-VB-specific way is to create a class with shared properties:
Public Class GlobalVariables
Public Shared Property MyGlobalString As String
End Class
The primary difference between the two approaches is how you access the global variables.
Assuming you are using the same namespace throughout, the VB-specific way allows you to access the variable without a class qualifier:
MyGlobalString = "Test"
For the non-VB-specific way, you must prefix the global variable with the class:
GlobalVariables.MyGlobalString = "Test"
Although it is more verbose, I strongly recommend the non-VB-specific way because if you ever want to transition your code or skillset to C#, the VB-specific way is not portable.
IN VB6 just declare on top code
public GlobalVariable as string
then you can use GlobalVariable in any form as you like.
like
GlobalVariable = "house"
then you can use /call in other form
text1 = GlobalVariable
will show value "house"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With