VBA Constant

Constant is a memory location used to hold value like a variable, but you cannot be changed or modify it during the script execution.

If the user tries to change a Constant value, the script execution ends up with an error. Constants are declared the same way the variables are declared. To maintain a constant use the keyword Const in VBA.

There are some rules for naming a constant, such as:

  • You must use a letter as the first character.
  • You cannot use space, period (.), exclamation marks and the characters in the name.
  • It cannot exceed 255 characters in length.
  • You cannot use the reserved keywords of visual basic as the variable name.

There are two types of constant.

  1. Built-in or intrinsic provided by the application.
  2. Symbolic or user-defined.

You can specify the scope as private (by default) or the public.

For example, Public Const TotalDays = 365
                        Private Const WorkDays = 250

Syntax

We need to assign a value to declare the constant in VBA. If we try to change the value of the constant, then it’s through an error.

Example

Let’s see how to work with constants step by step, such as:

First, we will create or insert a command button.

Step 1: Click on the Developer tab.

Step 2: Then, click on the Insert drop-down box.

Step 3: Select a Command Button, as shown in the below screenshot.

VBA Constant

Step 4: You will get the Dialogue window.

1. Enter the Macro name.

2. Click on the New button.

VBA Constant

3. You will get the code window and enter the following code.

VBA Constant

Step 5: It creates a button named Button1.

VBA Constant

Step 6: Click on the button such as Button1, then you will get the output of the code as shown in the below screenshot.

VBA Constant


Next TopicVBA Arrays