Home / MS-Access / Getting Started

Variables, Arrays, Constants and Data Types

Although the concept of having places to store data while the program is running is fairly straightforward, variables, arrays, and constants have some fairly complicated rules.

Variables

Building up a structure of variables is a bit like building up a filing cabinet at home. You might have files for your job, insurance policies, taxation, and personal documents such as passports. These files can grow in size. Some may only hold a single document, such as an insurance policy, while others can carry quite a lot of information, such as a tax file. The important thing is that each file has a particular category of document. You would not file your passport in with your tax papers, for example. You need to know which file holds which papers for quick and easy reference.

Think of a variable as being similar to a particular file holding a specific type of information. The variable may just be a single number or a piece of text that the program needs to hold and refer to while it is running. It could also be a whole array of information, almost like a spreadsheet. A spreadsheet has many cells that can hold information, and an array can be set up to have many cells or locations in exactly the same way.

A variable can have its value changed by the program when running, which is why it is called a variable. The same rules apply from the filing cabinet example, in that you do not mix the data types between the variables. If a variable has been defined as a certain type, it will not accept data specified as another type. For example, if you have defined a variable as an integer (whole) number, you cannot put text into it, or if you put a floating point number (with decimal places) into an integer, you will lose the decimal places.

As your program runs, you often need a place to store data temporarily. Use variables to store values while your code is executing. Within a procedure, you declare a variable using the Dim statement, supplying a name for the variable:

Dim variablename [As type]

Variable names must follow these rules:

  • They must begin with a letter.
  • They must contain only letters, numbers, or the underscore character-no spaces!
  • They must not exceed 40 characters.
  • They must not be a reserved word (see the section "Reserved Words" at the end of this tutorial).

The optional As type clause allows you to define the data type of the variable you are declaring. If you omit the type, it defaults to the Variant data type discussed in the next section.

Dim MyInteger as Integer