What is a Constant in VBA?
In VBA, a constant is a storage box that is itself stored in your system and it can store a value in it for you, but the value which you assign to it cannot be changed during the execution of the code. In VBA there are two different kinds of constants that you can use:
- Intrinsic Constants
- User-Defined Constants
Intrinsic constants are those which are built into the VBA language itself (for example, the built-in constant vbOKCancel which you use in the message box), and on the other hand, user-defined constants are those which you can create by assigning a value to it.
Declare a Constant in VBA
- Use the keyword “Const”.
- Specify a name for the constant.
- Use the keyword “As” after the name.
- Specify the “Data Type” for the constant according to the value you want to assign to it.
- Equals to “=” sign.
- In the end, the value you want to assign to it.
Above is a constant that stores a birthdate. Now if you think, a birth date is something that is supposed to be fixed and for this kind of value, you can use a constant.
Scope of a Constant
Constant has the same scope as variables. When you declare a constant, it has a procedure-level scope, which means you can use it anywhere within the procedure. But you can declare a constant using a private or public scope.
A private constant is available only to the procedure where it is declared as a constant. To declare a private constant, you need to use the keywords “Private”, just like the following example.
Private Const iName As String = “Puneet”
And in the same way, you need to use the keyword “Public” when you need to declare a constant as public.
Public Const iPrice As String = “$3.99”