A variable can be thought of as a box to hold information that you want to use somewhere else in the program

The variable (userName) stores the value of the name - in this case 'Fred'.

Visual Basic has strict rules for handling variables.  

RULES FOR NAMING VARIABLES

You can name your variables anything you like within the rules (see below), and you can store anything you like in them.  However....  unless you use sensible names you will find it very difficult to understand your program as you write it, and impossible to understand it 6 months later when you may want to change something.


VARIABLE TYPES

As well as containing numbers, variables can contain strings. Strings are any combination of letters, numbers or symbols that you want your program to treat literally.  

To assign a number to a variable, you do not use quote marks.  eg total = 234

To assign a string to a variable, enclose it in quote marks.  eg userName = "Bill"

So if you had a phone number written as 6223-3456, the computer would treat it as 6223 minus 3456 unless you assigned it as a string type variable. To tell the program to treat strings literally, always surround your string with quote marks like this "6223-3456"

      Phone = "6223-3456"

If you forget to put in the quote marks, Visual Basic would try to subtract 3456 form 6223 and put the value in Phone.

There are a number of other data types.  Some examples are:

Boolean True or False
Date Dates between Jan 1, 100 and Dec 31, 9999
Integer -32,768 to 32,767
Long -2,147,483,648 to 2,147,483,647

DECLARING VARIABLES

Before you use a variable, you should declare it. That tells the program about it.  

Examples of variable declarations:

If you do not state the data type when you declare a variable, it is treated as 'Variant' type, which can hold numbers or strings (of almost any length).


VARIABLE SCOPE

Variable scope is where in your program your variables can be seen.  Sometimes you want your variables to be seen by all the procedures within your project, and at other times you want them to be only available within a particular procedure. Where you declare a variable determines which procedures can see and use it.

A variable declared in the declarations section (this coding section can be found by pulling down the left combo box of the coding form) has a global scope and can be accessed anywhere in your project.

While a variable that is declared inside your code, between the Sub and the End Sub, can only be accessed in that sub.

eg Private Sub askName

Dim userName, userAge   .....

The variables userName and userAge can only be used within the procedure askName