Variables and Constants

Variable

A variable is a named location in the RAM (Random Access Memory) used by a program to store data.  It has a name and a data type.  Its value can be changed while a program is running.

        Dim stName As String

 

        stName = “Kevin”

 

        MsgBox(stName)

 

        stName = “Sally”

 

        MsgBox(stName)

Constant

A constant is similar to a variable in that it is a named location in the RAM with a specific data type.  It is assigned a value when it is declared but its contents cannot be modified by the program later.

        Const VAT_RATE As Double = 0.2

        Dim Price As Double

 

        Dim dblUnitCost As Double

        Dim iQuantity As Integer

 

        dblUnitCost = Me.txtUnitCost.Text

        iQuantity = Me.txtQuantity.Text

 

        Price = dblUnitCost * VAT_RATE 

Variable Scope

This refers to the visibility of a variable, namely which sub procedures and functions can use it.

If a variable is declared within a sub procedure or function, it has local scope and can only be accessed by that procedure or function.

If a variable is declared at the top of a module (using Dim in Visual Basic), it has module level scope and can be accessed by all of the procedures and functions within that module.

If a variable is declared at the top of a module using the keyword Global or Public, it has global scope and can be accessed by all of the procedures and functions within an application (including external library files).

Variable Lifetime

A variable with local scope only exists for the lifetime of the procedure of function in which it was declared. When the procedure or function ends, the memory used by the variable is released.

Array Variable

An array variable is a named group of contiguous memory locations in the RAM. Individual elements of an array can be accessed by means of an index number.  Arrays are normally manipulated using iteration constructs.