Visual Basic Variables

A variable is a name given to a particular area in memory that stores a value, which can later be reused. When creating a variable in Visual Basic it is necessary to specify the type of data to be stored within the variable, for example, whether it is a string, integer or floating-point number. The value of a variable can be changed as much as is necessary once it has been created.

When naming variables in Visual Basic it should be noted that the names are not case sensitive. Variable names must start with a letter, but can then be followed by either letters, numbers or underscores and cannot exceed 255 characters in length. One further restriction is that a variable name cannot be the same as a reserved word. Reserved words are those that have a specific purpose in Visual Basic and therefore cannot be used for anything else.

When declaring a variable, it takes the following format.

Dim variable_name As variable_type

The words in blue above are examples of reserved words in Visual Basic. Variable name is the name given to the variable in memory, which can be used to reference it later. Variable type refers to the type of data that can be stored in a variable. The most commonly used data types in Visual Basic are ‘String’, ‘Boolean’, ‘Integer’, ‘Double’ and ‘Date’, where ‘String’ contains a string of characters, ‘Boolean’ is either ‘True’ or ‘False’, ‘Integer’ is a whole number, ‘Double’ refers to a number that can contain decimal places, such as 1.5, and ‘Date’, which can contain a date and time.

Below are examples of variable declarations.

Dim firstName As String
Dim age As Integer
Dim price As Double
Dim result As Boolean
Dim current As Date

Once a variable has been declared, a value can be assigned to it. Note that the ‘current’ variable is set to the current date and time, the format of which may vary depending on the Operating System regional settings.

firstName = "Fred"
age = 30
price = 12.99
result = True
current = DateTime.Now

Instead of declaring a variable and then assigning a value to it on a separate line, the two operations can be combined, so the above can be re-written as follows.

Dim firstName As String = "Fred"
Dim age As Integer = 30
Dim price As Double = 12.99
Dim result As Boolean = True
Dim current As Date = DateTime.Now

The examples shown here are just a small number of the types of variables that are available.

Further Reading