VBA Constants Explained

What Constitutes a VBA Constant?

In the realm of VBA (Visual Basic for Applications), a constant serves as a designated storage container residing within your system. It is adept at holding a value, yet crucially, once assigned, this value remains unalterable throughout the execution of the code. recognizes two distinct categories of constants:

Intrinsic Constants:

These constants are inherently embedded in language itself. A prime example is the built-in constant “vbOKCancel,” frequently employed in message box prompts.

User-Defined Constants:

User-defined constants are created by assigning a specific value to them, granting you flexibility in customization.

Declaring a Constant in VBA: To initiate a constant in VBA, adhere to the following protocol:

  • Utilize the “Const” keyword.
  • Specify a designated name for the constant.
  • Incorporate the “As” keyword followed by the data type aligned with the intended value.
  • Utilize the “=” sign to indicate the assigned value.

The illustrated example demonstrates a constant designed to store a birthdate. Constants are particularly apt for values deemed unchanging, such as a birth date.

Scope Considerations: Similar to variables, constants exhibit varying scopes. Upon declaration, a constant defaults to a procedure-level scope, allowing usage throughout the entire procedure. Nevertheless, constants can be declared with private or public scopes.

Private Constant:

  • Exclusive to the procedure of declaration, a private constant is delineated using the “Private” keyword. An instance is provided below:
    Private Const iName As String = "Puneet"

Public Constant:

  • In contrast, a public constant, declared using the “Public” keyword, extends its accessibility beyond the declaring procedure. An example is presented below:
    Public Const iPrice As String = "$3.99"

Understanding the scope nuances empowers you to tailor constants for optimal utility in your VBA projects.

Compare items
  • Total (0)
Shopping cart