VBA Constants

VBA Constants in Excel VBA

Constants has a meaningful name and assigned or set a value to it. Once constant value is declared, we can’t changed or assigned to a new value throughout the script execution. We use Const keyword to declare a constant value. We can declare a constant variable any where in the module. It can be declared at Module level or procedure level or class module. We can also use private or public while declaring constant variable.

Syntax of VBA Constant in Excel

Here is the syntax of VBA Constant syntax in Excel.

Const constant_name As constant_type = constant_value

Where Constant_Name: It represents a constant name which has meaningful.
Constant_Type: It represents type of data.
Constant_Value: It represents a constant value. Once value declared, the value can’t be changed or assigned througout execution.

Rules to Naming a Constants in VBA

We must follow the following rules while declaring a constant variable.

  1. Constant Name must be less than 256 characters length
  2. Constant first letter in name must be a character
  3. VBA keywords or reserved words cannot use as a constant Name
  4. We cann’t use reserved words as a constant name.
  5. Constant name doesn’t allow period(.)
  6. We cannot use special characters like @,#,$.%,&,!, etc. when declaring a constant name.
  7. We can declare multiple constants in one statement.

Declare Constant Values

We can declare constants at module level or project level. We can also use Private and Public keywords along with constants. Constants can accept any type of data.
Module Level Constants:
Let us see how we can declare a constant at module level. In the below example the constant iCnt can be accessed from any procedure in the current module. We can’t access procedures which are in other modules. Module level constants are private by default.

Const iCnt As Integer = 222
'or
Private Const iCnt As Integer = 222

Project Level Constants:
Let us see how we can declare a constant at project level.In the below example the constant iCnt can be accessed from any procedure in any module in the project. Project level constants are public by default.

Public Const iCnt As Integer = 222

Example on Constant variable in Excel VBA

Let us see the example on constant variables in VBA. Constants can accept any type of data.

Sub VBAF1_Constant_Declaration()
     
    'Constant Variable Declaration
    Const iCnt As Integer = 444
    Const dDate As Date = #1/1/2019#
    Const sMonth As String = "March"
    Const cSalary As Currency = "40000"
    
End Sub

Other Useful Links:

Please click on below links to have a knowledge on specific topics.

VBA Tutorial VBA Data Types VBA Variables

Leave a Comment

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