Const
- Last UpdatedJul 18, 2023
- 2 minute read
Assigns a symbolic name to a constant value using the following syntax:
Const VarName [As DataType] = Expression
A constant must be defined before it is used. Unlike variables, constants are assigned values when initialized and retain that same value during the life of the constant.
Constant statements can only be declared and assigned using simple expressions. Constants can NOT be assigned values from variables, user-defined functions, intrinsic VBA functions (such as Chr), or from any expression that involves an operator.
Constants declared in a Sub or Function procedure are local to that procedure. A constant declared outside a procedure has modular scope to all procedures within the same VBA file module. See Scope of VBA.
Constants can be used anywhere in your VBA code where you could use a VBA expression.
If you use Const outside a procedure its scope becomes global.
A type declaration character may also be used. However if none is used, VBA will automatically assign one of the following data types to the constant: long (if it is a long or integer); Double (if a decimal place is present); or String (if it is a string).
Syntax
Const(VarName, Exp)
VarName:
A string representing a valid variable name.
Exp:
A valid string, number or Variant containing a value recognizable as a string or number.
Related Functions
Example
' Correct declaration examples
' long assignment
Const Seven = 7
' double assignment
Const Pi = 3.14159
' string assignment
Const Lab = "Laboratory"
' Incorrect declaration examples
' NOTE that the following declarations demonstrate incorrect
assignments
' because each contains an operator
Const conPi = 4 * Atn(1)
' will cause a VBA compile error
Const conDegToRad = (conPi / 180)
' will cause a VBA compile error