VBA Constant

VBA Constant. A constant is a named memory location that holds a value that cannot be changed during script execution. If a user tries to modify a Constant value, the script execution ends in an error. The same principle applies to constants, as to variables.

Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well

The constants are treated just like regular variables except that their Values cannot be modified after their definition.

Below are Some Rules for Naming a Constant

  • You must use a letter as the first character.
  • You can’t use space, period (.), an exclamation mark (!), or the characters #, $, &, @, * in the name.
  • Constant should be written in uppercase characters separated by underscores. E.g. ( a-z, A-Z, 0_9, and _)
  • The name cannot exceed 255 characters in length.
  • You cannot use Visual Basic reserved keywords as variable names.

Example

In VBA you are allowed to declare constants as values can be defined only once and cannot be modified. Let’s start with a constant declaration

  • Const myVar As Integer = 10
  • Dim x as Integer
  • x = myVar + 1 ‘OK!
  • myVar = 11 ‘ERROR! Constants cannot be redefined

Syntax

In VBA, we must assign a value to the declared constants, since if we attempt to modify the value of the constant, an error is thrown.

Const constant_name As constant_type = constant_value

Example

Let’s check out some steps to work with constants:

Firstly, we will create or insert a command button.

Step 1: Click on the Developer Tab to open a drop-down from the ribbon.

Step 2: Click on the insert drop-down box at the top of your screen.

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

VBA Constant

 

Step 4: A new dialogue window will appear.

1.  Right click on the Command Buttonas shown in the below screenshot.

VBA Constant

 

2.  You will get the code and enter the following code.

VBA Constant

 

Step 5: In the screenshot below you will see that button named CommandButton1 has been created.

VBA Constant

 

Step 6: Click on a button such as CommandButton1, then the output of the code will be revealed. You can check the below screenshot to confirm.

Leave a Comment

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

Scroll to Top