Return to VBA Code Examples
In this Article
- What is a Constant
- Data Types used by Constants
- Declaring a Constant within a Procedure
- Declaring a Constant within a Module
- Declaring Constants at a Global Level
This tutorial will demonstrate the use of VBA Constants.
A constant is similar to a variable and is declared in a similar way. There is, however, a major difference between them!
What is a Constant
A constant is a value that we declare in our code and consequently it is reserved in our computer’s memory and stored. We have to name our constant and it’s good practice to declare the data type of our constant. When we declare the data type, we are telling the program what type of data needs to be stored by our constant .
We will use the constant in our code, and the program will also access our constant. Unlike a variable, where the actual value can change while the code is running, a constant value never changes.
Data Types used by Constants
Constants use the same data type as Variables. The most common data types for Constants are as follows:
• String – this is used to store text values.
• Boolean – this is used to store TRUE or FALSE values.
• Integer – this is used to store whole number values.
• Double – this is used to store numbers with decimals.
• Date – this is used to store dates.
To see a complete list of all data types used by Variables and Constants in VBA, click here.
In VBA, we have to use a Const statement in order to declare a Constant. We can declare constants in a similar way to declaring Variables – at Procedure Level, at Module Level and at a Global Level.
Declaring a Constant within a Procedure
To declare a Constant at Procedure level, we declare it inside the procedure.
Sub CompanyDetails()
Const strCompany As String = "ABC Suppliers"
Const strAddress As String = "213 Oak Lane, Highgate"
MsgBox strCompany & vbCrLf & strAddress
End Sub
When we run the code, the message box will return the constant values.
Because the Constant is declared at Procedure level, we can declare a Constant with the same name in a different Procedure.
If we run the second Procedure, the Constant value stored in that Procedure is returned.
Declaring a Constant within a Module
If we want a Constant value to be available to all Procedures within a Module, we need to declare the constant at Module level.
This will make the same constant available to multiple procedures WITHIN that module only.
Should you use the Constant in a different module, an error will occur.
Declaring Constants at a Global Level
You can declare Constants at a Global Level which would then mean you can use them in all the Modules contained in your entire VBA Project.
To declare a Constant as a Global Constant, we need to put the word PUBLIC in front of the declaration statement.
For example:
Public Const strCompany as string = "ABC Suppliers"
This will allow the Constant to be used in all the modules regardless of where is is declared.
NOTE: you can ONLY declare a public constant at a Module level, you CANNOT declare a public constant within a procedure.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
Home / VBA / VBA Constants
What is a Constant in VBA?
In VBA, a constant is a storage box that is itself stored in your system and it can store a value in it for you, but the value which you assign to it cannot be changed during the execution of the code. In VBA there are two different kinds of constants that you can use:
- Intrinsic Constants
- User-Defined Constants
Intrinsic constants are those which are built into the VBA language itself (for example, the built-in constant vbOKCancel which you use in the message box), and on the other hand, user-defined constants are those which you can create by assigning a value to it.
Declare a Constant in VBA
- Use the keyword “Const”.
- Specify a name for the constant.
- Use the keyword “As” after the name.
- Specify the “Data Type” for the constant according to the value you want to assign to it.
- Equals to “=” sign.
- In the end, the value you want to assign to it.
Above is a constant that stores a birthdate. Now if you think, a birth date is something that is supposed to be fixed and for this kind of value, you can use a constant.
Scope of a Constant
Constant has the same scope as variables. When you declare a constant, it has a procedure-level scope, which means you can use it anywhere within the procedure. But you can declare a constant using a private or public scope.
A private constant is available only to the procedure where it is declared as a constant. To declare a private constant, you need to use the keywords “Private”, just like the following example.
Private Const iName As String = “Puneet”
And in the same way, you need to use the keyword “Public” when you need to declare a constant as public.
Public Const iPrice As String = “$3.99”
The Pi’s value is 3.14, the gravitation pull of the Earth is 9.8 m/s2, you have an interest in VBA, etc. These all are constants and they don’t change.
In VBA you can define variables whose value can’t be changed in the program. The VBA programmer defines these constant values by themselves in the program to use them again and again.
How to Define a Constant Value in VBA?
We use the keyword Const to declare a constant in VBA.
The syntax of declaring a constant variable in VBA is:
[<Scope Specifier>] Const <VarName> as <variable_type> = <value>
[<Scope Specifier>]: The scope specifier is optional. You specify the scope of the constant (public or private) if you want, otherwise don’t declare it. By default, the scope of a constant is private. You can read about Scope Specifiers here.
Note: We never use the Dim keyword to declare a constant in VBA.
<VarName>: It is the name of the constant variable.
<variable_type>: The type of the constant. For example, Integer, String, Date, etc.
<value>: The value of the constant variable.
A simple example of the Constant Variable is:
Const pi as double = 3.14
Here we declared the constant value of pi in a variable named pi. Now we can use this pi in our program. The value will always be 3.14. If you try to change the value of a constant variable, the Excel VBA will pop up an error message.
VBA Constant Variable Examples
Study the below code:
Const pi As Double = 3.14 Const rad As Double = 6371 Sub Earth() sArea = 4 * pi * Sqr(rad) Debug.Print sArea End Sub Sub Mars() rad = 3389.5 sArea = 4 * pi * Sqr(rad) Debug.Print sArea End Sub
Here, we have defined two constants, pi, and the rad. The pi’s value is 3.14 and rad is 6371 which is the earth’s radius.
Now, when we run the first sub the Earth, it works perfectly fine and prints the surface area of the Earth.
In the next sub-Mars, we redefined the constant rad as the radius of mars is different. When we run this program, it throws an error saying, «Assignment to constant is not permitted«.
How to reinitialize a constant in VBA
As you have seen in the above example that we can’t assign new values to a constant. Yes, you can’t.
But if you still need to use the same name as a different fixed value, just use the Const keyword before the assignment.
The below code will work perfectly.
Const pi As Double = 3.14 Const rad As Double = 6371 Sub Earth() sArea = 4 * pi * Sqr(rad) Debug.Print sArea End Sub Sub Mars() Const rad = 3389.5 sArea = 4 * pi * Sqr(rad) Debug.Print sArea End Sub
The above subroutine will work perfectly without any errors. But I don’t recommend this approach. The best way is to identify the public and private constants and define them separately. And this brings us to our next segment.
Public and Private Constants in VBA
As we learned in the above examples, some constants may be universal and some may differ for different objects. Like, the pi value is constant for the entire universe, but the number of planets very solar system to solar system and radius of planets varies planet to planet.
As the Earth’s radius is constant for it, not for the universe. Similarly, in programs, there will be some constants will be private to sub’s and module’s and some will be public constant for the entire VBA project. Your job is to identify them and declare them differently.
Let’s take another example:
Public Const pi As Double = 3.14 ' This can be accessed from any module in the project Private Const planets As Integer = 8 ' this is private to this module Sub Earth() Const rad As Double = 6371 'Private to this subroutine. Can't be accessed outside sArea = 4 * pi * Sqr(rad) Debug.Print sArea End Sub Sub Mars() Const rad As Double = 3389.5 'Private to this subroutine. Can't be accessed outside sArea = 4 * pi * Sqr(rad) Debug.Print sArea End Sub
This is a simple variable scope specifying. You can read about the variable scope setting here in detail.
So yeah guys, this is how you declare and use constants in Excel VBA. I tried to explain in a creative way. I hope I was explanatory enough. If you have any doubt, ask in the comments section below. I will be happy to hear and reply to you.
Related Articles:
Excel VBA Variable Scope | we have variable access specifiers that define from where a defined variable can be accessed. Excel VBA is no Exception. VBA too has scope specifiers. These scope specifiers can be used to set the visibility/scope of a variable in Excel VBA.
ByRef and ByVal Arguments |When an argument is passed as a ByRef argument to a different sub or function, the reference of the actual variable is sent. Any changes made into the copy of the variable, will reflect in original argument.
Delete sheets without confirmation prompts using VBA in Microsoft Excel|Since you are deleting sheets using VBA, you know what you are doing. You would like to tell Excel not to show this warning and delete the damn sheet.
Add And Save New Workbook Using VBA In Microsoft Excel 2016|In this code, we first created a reference to a workbook object. And then we initialized it with a new workbook object. The benefit of this approach is that you can do operations on this new workbook easily. Like saving, closing, deleting, etc
Display A Message On The Excel VBA Status Bar The status bar in excel can be used as a code monitor. When your VBA code is lengthy and you do several tasks using VBA, you often disable the screen update so that you don’t see that screen flickering
Turn Off Warning Messages Using VBA In Microsoft Excel 2016|This code not only disables VBA alerts but also increases the time efficiency of the code. Let’s see how.
Popular Articles:
50 Excel Shortcuts to Increase Your Productivity | Get faster at your task. These 50 shortcuts will make you work even faster on Excel.
The VLOOKUP Function in Excel | This is one of the most used and popular functions of excel that is used to lookup value from different ranges and sheets.
COUNTIF in Excel 2016 | Count values with conditions using this amazing function. You don’t need to filter your data to count specific value. Countif function is essential to prepare your dashboard.
How to Use SUMIF Function in Excel | This is another dashboard essential function. This helps you sum up values on specific conditions.
What is VBA Const (Constants)?
Variables are the heart and soul of any programming language. We have never seen a coder or developer who does not rely on variables in their project or program. As a coder, no one is not different from others. We use variables 99% of the time. We all use the “Dim” statement; we declare VBA variablesVariable declaration is necessary in VBA to define a variable for a specific data type so that it can hold values; any variable that is not defined in VBA cannot hold values.read more. Our articles have shown you about declaring variables through the “Dim” statement. But we declare variables using another way as well. This article will show you the alternative route of declaring variables, i.e., the “VBA Constant” method.
“Const” stands for “Constants” in VBA. Using the VBA “Const” word, we can declare variables like how we declare variables using the “Dim” keyword. We can display this variable at the top of the module, between the module, in any subroutine in VBASUB in VBA is a procedure which contains all the code which automatically gives the statement of end sub and the middle portion is used for coding. Sub statement can be both public and private and the name of the subprocedure is mandatory in VBA.read more and function procedure, and the class module.
To declare the variable, we need to use the word “Const” to display the constant value. Once the variable is declared and assigned a cost, we cannot change the weight throughout the script.
Table of contents
- What is VBA Const (Constants)?
- Syntax of Const Statement in VBA
- Condition of Constants in VBA
- Examples of Const Statement in VBA
- Make Constants Available Across Modules
- Difference Between VBA Dim Statement & Const Statement
- Recommended Articles
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Const (wallstreetmojo.com)
Syntax of Const Statement in VBA
The Const statement is slightly different from the “Dim” statement. To understand it better, let us look at the well-written syntax of the VBA Const statement.
Const [Variable Name] As [Data Type] = [Variable Value]
- Const: With this word, we initialize the process of declaring the constants.
- Variable Name: This is as usual as naming the variable. We rather call it Const Name instead of Variable Name.
- Data Type: What kind of value our declared variable is going to hold.
- Variable Name: Next and final part is what is the value we are going to assign to the variable we have declared. The given weight should be as per the data type.
Condition of Constants in VBA
- The name of the constant we are declaring can contain a maximum of 256 characters in length.
- The constant’s name cannot start with a number; rather, it should begin with the alphabet.
- We cannot VBA reserved keywords to declare the constants.
- The constant name should not contain any space or special characters except the underscore character.
- One can declare multiple constants with a single statement.
Examples of Const Statement in VBA
Let’s declare your first variable through the VBA Const statement. After that, we can declare constants at the subprocedure, module, and project levels.
Now, look at how to declare at the sub procedure level.
In the above example, we declared constant “k” inside the sub procedure named Const_Example1(). And we have assigned the value as 75.
Now, look at the module level Constant declaration.
At the top of the module, we have declared three constants in the module “Module 1”.
These VBA constants can be accessed in “Module 1” at any sub procedures within this module, i.e., “Module 1.”
Make Constants Available Across Modules
We can access those constants within the module with all the subprocedures when we declare the constants at the top of the VBA class moduleUsers have the ability to construct their own VBA Objects in VBA Class Modules. The objects created in this module can be used in any VBA project.read more.
But how can we make them available with all the modules in the workbook?
To make them available across modules, we need to declare them with the word “Public.”
Now, the above variable is not only available with “Module 1.” Instead, we can use “Module 2” as well.
Difference Between VBA Dim Statement & Const Statement
It would help if you doubted the difference between the traditional “Dim” statement and the new “Const” statement in VBA.
We have one difference with these, i.e., look at the below image.
In the first image, as soon as we declare a variable, we have assigned some values to them.
But in the second image, using the “Dim” statement first, we have declared variables.
After declaring a variable, we have assigned values separately in the different lines.
Like this, we can use the VBA “Const” statement to declare constants, which is a similar way of communicating variables with the “Dim” statement.
Recommended Articles
This article has been a guide to VBA Const (Constants). Here we discuss how to use the Constant statement in VBA along with examples and its critical differences with Dim information. Below are some useful Excel articles related to VBA: –
- VBA Do Loop
- VBA DoEvents
- VBA Option Explicit
- VBA Text
A constant is a named value that does not change. The value of a constant is determined at design-time and cannot be altered during the execution of a program. Constants should be used instead of hard-coding literal values and should be used instead of variables when the value should not change.
Creating Constants
To create a constant in VBA use the Const keyword, give the constant a name, give the constant an optional type, and assign the constant a value. Constants must be assigned a value on the same line they are declared. Constants cannot be used with objects, arrays, or user-defined types. Constants can be declared Public or Private outside of a procedure, giving them Public or Module scope respectively, but cannot be declared Public inside Class modules. Constants can be declared inside a procedure and have procedure scope.
Constant declaration syntax: [Public|Private] Const CONSTANT_NAME [As Type] = Value
Option Explicit
Public Const A As Long = 1 'Public Scope
Private Const B As Long = 2 'Module Scope
Const C As Long = 3 'Module Scope
Public Sub Example()
Const PI As Double = 3.14159265359 'Procedure Scope
End Sub
Constants are normally defined using a literal value but they can also be defined in terms of other previously declared constants.
Const PI As Double = 3.14159265359
Const PI2 As Double = PI * 2
Where to Use Constants
A constant should be used whenever a program needs to use a value that will not change. Literal values should be replaced with constants and constants should be used in place of variables when the value of the variable should not change.
In Place of Literals
Hard-coded literal values make code difficult to read, understand, and maintain. A hard-coded literal can lack context which opens up the possibility to lose track of what the literal value means. To an outsider reading the code, the origin and purpose of a literal value may be completely unknown, which can cause confusion. Another major problem with using hard-coded literal values is that they can repeat throughout the body of code and if the value ever needs to be updated it can be extremely difficult to track down and accurately update every place it was used. Literal values may also overlap, so a literal value that happens to be the same as another may be mistakenly changed even though they represent something different. Constants are more descriptive and flexible than literal values. The origin and purpose of a constant is more clearly defined. If the constant ever needs to be updated it only needs to be updated once where it is defined and there is no ambiguity with other values that happen to be the same literal value but serve a different purpose.
Note: The example below is trivial so it appears like overkill to use constants this way but as the complexity of an application grows it greatly simplifies code and makes the code more secure.
Option Explicit
Public Sub Example()
Dim i As Long
For i = 2 To 100
If Cells(i, 1).Value = "Hello, World!" Then
MsgBox "Hello, World!"
End If
Next i
End Sub
Option Explicit
Public Const HEADER_ROW As Long = 1
Public Enum SpreadsheetColumns
MessageColumn = 1
FlagColumn
End Enum
Public Sub Example()
Const SEARCH_MESSAGE As String = "Hello, World!"
Const OUTPUT_MESSAGE As String = "Hello, World!"
Dim LastRow As Long
LastRow = Cells(Rows.Count, MessageColumn).End(xlUp).Row
'Rewritten with constants instead of literals
Dim i As Long
For i = HEADER_ROW + 1 To LastRow
If Cells(i, MessageColumn).Value = SEARCH_MESSAGE Then
MsgBox OUTPUT_MESSAGE
End If
Next i
End Sub
When a Variable Should Not Change
Constants should be used in place of variables when the value should never change. Using variables to represent constant values opens up the possibility that the value will be updated accidentally or intentionally when it should never be changed.
Public Function Circumference(Radius As Double)
'RETURNS WRONG ANSWER
Dim PI As Double
PI = 3.14159265359
'Whoops. PI should never change so this should not be allowed. Function is wrong.
PI = 1
Circumference = 2 * PI * Radius
End Sub
Public Function Circumference(Radius As Double)
'CAUSES COMPILE ERROR
Const PI = 3.14159265359
'Whoops. PI is immutable and this will cause a compile error. Function will not run.
PI = 1
Circumference = 2 * PI * Radius
End Sub
Enums
Enums can be used to store related integer constants together under a common type. Enums will be discussed in greater detail in the Enums section.
Option Explicit
Public Enum FavoriteColors
White = &HFFFFFF
Black = &H0&
Red = &HFF&
Orange = &HC0FF&
Yellow = &HFFFF&
Green = &H50B000
Blue = &HFF0000
Indigo = &H82004B
Violet = &HFF008F
End Enum
Public Sub Example()
Range("A1").Interior.Color = FavoriteColors.Green
End Sub
Built-In Constants
VBA has a number of built-in constants and enums which can be used with VBA functions. Most libraries used with VBA define their own constants and enums which are used with the classes and functions in those libraries.
VBA Library Constants Modules
- Constants
- KeyCodeConstants
- ColorConstants
- SystemColorConstants
VBA Library Enums
- FormShowConstants
- VbAppWinStyle
- VbCalendar
- VbCallType
- VbCompareMethod
- VbDateTimeFormat
- VbDayOfWeek
- VbFileAttribute
- VbFirstWeekOfYear
- VbIMEStatus
- VbMsgBoxResult
- VbMsgBoxStyle
- VbQueryClose
- VbStrConv
- VbTriState
- VbVarType