Constant variable in VBA

Constant variable in VBA

Constant is a type of Variable.

Like variable the constant variable is also used to hold data in memory. But the value of the variable can be changed during the execution of the program. Whereas the value of the constant variable never changes during the execution of the program.

So, when we require that the value of variable never change at that time we can use Constant variable.

Again, remember one essential thing, Value of Constant variable never change.

Declaration of the constant variable is same as other variable but have to use “Const” keyword instead of “Dim”.

Another important thing is that initialize a variable at the time of variable declaration.

Constant variable in VBA Video in Hindi


Syntax to declare Constant variable.

Const <variable_name> As <variable_DataType> = constant_value

Important naming rules for Constant in VBA          

  • Length of the variable name is Maximum 255 character
  • Fist letter must be an alphabet.
  • Cannot use space between the name
  • Cannot use any symbol except underscore “_”
  • Cannot use VBA reserved keyword as a variable name.
  • Within a single program or procedure all variable names must be unique.

Example of Constant in VBA

In the below example “PI” is a constant variable that is initialized at the time of declaration.

Private Sub cmdBttnClick_Click()
    Const PI As Double = 3.14
    MsgBox ("Value of PI = " & PI)
End Sub

Output:

Example of Constant in MS Excel VBA

Some of the important rules to keep in mind while using Constant

  • Important naming rules for Constant in VBA
  • Some of the important rules to keep in mind while using Constant
  • Initialize the constant variables with the declaration.
  • The constant variable cannot be dynamically initialized.
  • The value of the Constant variable cannot be changed throughout the program.

Leave a Reply

Your email address will not be published. Required fields are marked *

*