user3470747
user3470747

Reputation: 117

How would I declare a global variable in Visual Basic?

I want to create a variable that can be used across multiple forms.

It's going to be a temporary storage place for integers.

Upvotes: 11

Views: 88669

Answers (3)

C.P. Williams
C.P. Williams

Reputation: 1

You can just add it as Public to any Module

Example:

Module Module1
    'Global variables
    Public glbtxtTemplateName As String     'GLOBAL VARIABLE FOR TEMPLATE
End Module

VB loads the Modals first as a class and all Public items therein are shared directly. Think about it this way:

Lets say we have a Module called "MY_PROCESSES"

When you declare a Sub or a Function in "MY_PROCESSES" if you want it to be used outside of "MY_PROCESSES" you declare as Public like this:

Public Sub LOAD_TEMPLATE()

To get to LOAD_TEMPLATE you just call it in your code from anywhere:

LOAD_TEMPLATE()

So if I need to set or use the global variable that I made public in my module I just refer to it by name:

glbtxtTemplateName="TEMPLATE_NAME"

If glbtxtTemplateName = "" Then LOAD_TEMPLATE()

I do like building the class as above because you can reference it faster without remembering the variable but if you only need 1 or 2 global variables you can name them like we used to with Hungarian Notation style name.

This method is really quite simple and elegant. Old is new and New is Old.

Upvotes: 0

Yusuf Efendy
Yusuf Efendy

Reputation: 11

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"

Upvotes: 1

competent_tech
competent_tech

Reputation: 44931

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.

Upvotes: 23

Related Questions