![]() |
Variable Declaration |
Background
The Dim statement is used to declare variables and arrays. When a variable is declared, VB allocates the appropriate memory to it.
It is good practice to declare variable before using them.
Syntax
Dim var_name As var_type
Dim Total As Integer
Dim Age As Byte
Dim Forename As String
An array is a variable made up of many elements.
e.g. Dim Numbers (5) As Integer
This declares the Number variable with 6 elements (0 to 5)
You can declare an array starting from any number to any number e.g.:
Dim Numbers (1 to 100) as Integer
Dim Years(1970 to 2020) as Integer
2 Dimensional Arrays
You can declare an array in 2D:
Dim X (1 To 10, 1 To 4) as integer
This would give you an array 10 rows down, by 4 columns.
To put data in the 9th row, 3rd column you could write: X (9,3)= 53
Resizing arrays
When you run a program, you may not know how big an array to create. You can declare an array with no size, then use the ReDim command to set the size later.
Example
To declare an array with no size
Dim X() as integer
If the user input the size required into variable MaxSize, the redim command can be used:
ReDim X ( 1 to MaxSize)
Note: using the Redim command loses all data in the array. You can prevent this from happening. For example, if the Redim command had been used to set the array to size 100, you could use the following to resize it again, but this time keep the contents of elements 1 to 100:
Redim Preserve X (1 to 200)
Note: the data type doesn't have to be specified as that has already been specified in the original declaration