Constants are used in much the same way as a variable except that, as their name indicates, a constant's value doesn't change unless you explicitly and physically change the value of the constant in your source code.
Constants are private by default. When declared within a procedure, they are always private and can't be seen by code outside the procedure. When declared at the module level however, constants can be declared as public and, therefore, can be seen by procedures located in other modules. Here are some sample constant declarations.
' Declare public module level constants
Public Const APP_NAME As String = "My Excel Application"
Public Const APP_VERSION As String = "1.0.0"
' Declare private, module level constant Private Const FTE_HOURS_WEEK = 40
' Declare private, module level constant ' If not specified, constants are private by default Const SECONDS_PER_MINUTE = 60
Naming constants using all capitals is a widely used naming convention. Note that if you don't specify a type for the constant using the As statement, VBA chooses a type that is appropriate to the value specified for the constant.
Constants can make your code easier to read and modify and are recommended in instances where you find yourself hard coding, or physically entering literal values throughout your code.
Was this article helpful?