MS-Access / Getting Started

Declaring Constants and Variables

The following sections show the syntax of the statements you can use to define constants and variables in your modules and procedures.

Const Statement

Use a Const statement to define a constant.

Syntax

[Public | Private] Const {constantname [As datatype] = <const expression>},...

Notes

Include the Public keyword in the Declarations section of a standard module to define a constant that is available to all procedures in all modules in your database. Include the Private keyword to declare constants that are available only within the module where the declaration is made. Constants are private by default, and a constant defined within a procedure is always private. You cannot define a Public constant in a class module. (All constants in a class module are private.)

Valid datatype entries can be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String, or Variant. You cannot declare a constant as an object. Use a separate As datatype clause for each constant being declared. If you don't declare a type, Visual Basic assigns the data type that is most appropriate for the expression provided. (You should always explicitly declare the data type of your constants.)

The <const expression> item cannot include variables, user-defined functions, or Visual Basic built-in functions (such as Chr). You can include simple literals and other previously defined constants.

Example

To define the constant PI to be available to all procedures in all modules, enter the following in the Declarations section of any standard module:

Public Const PI As Double = 3.14159
It's a good idea to give all variable names you create a prefix notation that indicates the data type of the variable, particularly if you create complex procedures. This helps ensure that you aren't attempting to assign or calculate incompatible data types. (For example, the names will make it obvious that you're creating a potential error if you try to assign the contents of a long integer variable to an integer variable.) It also helps ensure that you pass variables of the correct data type to procedures. Finally, including a prefix helps ensure that you do not create a variable name that is the same as an Access or Visual Basic reserved word. The following table suggests data type prefixes that you can use for many of the most common data types.
Data TypePrefixData TypePrefix
BooleanbolDocumentdoc
BytebyteFieldfld
CurrencycurFromfrm
DoubledblIndexidx
Integerintkeykey
LonglngParameterprm
SinglesglProcedureprc
StringstrPropertyprp
User-defined (using the Type statement)usrQueryDefqdf
VariantvarRecordsetrst
CatalogcatReportrpt
ColumncolTabletbl
CommandcmdTableDeftbl
ConnectioncnViewvew
ControlctlWorkspacewks
Databasedb
[Previous] [Contents] [Next]