Initialising

All local variables are automatically initialised to a Default Value when they are declared.
Once a variable has been declared, changing the value later means Assigning a new value.
Unlike a lot of other programming languages you cannot declare and initialise on the same line.


Declare and Initialise

In VBA it is not possible to declare and initialise a variable in one line.
You must declare your variable on one line and then assign the value on a new line.
Explicitly assigning a value to a local variable after it has been declared is recommended.

Dim lMyNumber As Long 
lMyNumber = 500

Using a Colon Separator to put these on one line makes your code harder to read.

Dim lMyNumber As Long: lMyNumber = 500 

Boolean Variables

These default to False

Dim bMyVariable As Boolean 

Numeric Variables

Integer, Long, Single, Double and Currency are all initialised to zero.

Dim iInteger As Integer 
Dim lMyNumber As Long
Dim sngMyNumber As Single
Dim dbMyNumber As Double
Dim cMyNumber As Currency
'automatic initialisation will assign the value to 0

Variable Length Strings

These are initialised to a zero-length (or empty) string.

Dim sFirstName As String 
'automatic initialisation will assign the value to the empty string ""

Fixed Length Strings

These are initialised with the character represented by the ASCII code 0, or Chr(0).

Dim sFirstName As String * 10 

Variant Variables

These default to Empty

Dim vAnything As Variant 

Object Variables

These default to Nothing

Dim vMyObject As Object 

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext