I’m using an enum defined in a class module in Excel VBA. This has been working fine, but I’ve started getting a compile error on every time I do a comparison on enum variables:
In class CExample:
Enum MyEnum
Foo
Bar
End Enum
Elsewhere:
If someValue = myEnum.Foo Then
The text .Foo
will be highlighted, and a «Compile error: Constant expression required» message pops up.
A search on Google suggests that this can randomly happen, and fixes such as restarting the IDE or adding a space after the enum declaration can make it start working again.
- http://www.tek-tips.com/viewthread.cfm?qid=1355882
- http://www.vbforums.com/showthread.php?405564-RESOLVED-Constant-Expression-Required-Error-when-checking-Enum
Is this really a known bug in VBA? Is there anything I can do to avoid it happening, or reliably get VBA working again if it does crop up?
In my case, closing and reopening Excel hasn’t helped. Excuse me while I reboot my PC.
Update after reboot:
The problem persisted after rebooting my machine, which is surprising. I tried adding Public
in front of the enum definition (they’re meant to be public by default but I thought I’d give it a try), and the error disappeared. I’ve removed the Public
keyword (so we’re back to my original code) and it still compiles and runs fine.
It does look like this is a random bug in VBA. I’d be interested to know if experienced developers have found this comes up often — would you advise not using enums? Or does it pop up once in a blue moon and I was just unlucky?
Update after 6 weeks of further development:
The problem didn’t recur during the rest of my time developing this project, so it looks like it is a rare problem.
Permalink
Cannot retrieve contributors at this time
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Constant expression required |
vblr6.chm1040114 |
vblr6.chm1040114 |
office |
e0493fe4-8f50-c935-391f-0ffaca726b2b |
06/08/2017 |
medium |
A constant must be initialized. This error has the following causes and solutions:
-
You tried to initialize a constant with a variable, an instance of a user-defined type, an object, or the return value of a function call.
Initialize constants with literals, previously declared constants, or literals and constants joined by operators (except the Is logical operator).
-
array
To declare a dynamic array within a procedure, declare the array with ReDim and specify the number of elements with a variable.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
[!includeSupport and feedback]
Return to VBA Code Examples
We covered arrays, static arrays and dynamic arrays in a previous tutorial. We are going to look at a common error associated with static arrays called Constant Expression Required. This error is generated when you try to use a static array instead of a dynamic array as shown in the code below:
The static array needs to have constants used to set it since it is fixed.
The way to resolve this error is to use a Dynamic array variable instead. You would use the ReDim keyword every time you want to resize the array. This is shown in the code below:
Sub UsingReDim()
Dim value1 As Integer
Dim value2 As Integer
Dim value3 As Integer
value1 = 3
value2 = 9
value3 = 15
Dim listofvalues() As Integer
ReDim listofvalues(value1)
End Sub
Read more about Dynamic array variables in our Array variable tutorial.
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!
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
(No installation required!)
Free Download
The «Constant Expression Required» error in Microsoft Excel VBA often occurs when using enums in your code. Enums are used to define a set of named constants, but in some cases, they may not be recognized as constants by Excel VBA. This error can occur due to a variety of reasons, including incorrect syntax or mismatched data types. In this article, we will explore several methods for resolving this error and ensuring your enums are properly recognized in your VBA code.
Method 1: Use Constants Instead of Enums
When using Enums in VBA, you may encounter an occasional «Constant Expression Required» error. This can be frustrating, but there is a workaround: using constants instead of enums. Here’s how it works:
- Define your constants at the top of your module. For example:
Const MY_CONSTANT_1 As Integer = 1
Const MY_CONSTANT_2 As Integer = 2
- Replace any instances of your enum with the corresponding constant. For example:
' Before
myEnum = MY_ENUM_VALUE
' After
myEnum = MY_CONSTANT_1
- If you need to use the constants in a Select Case statement, you can use the Case Is operator. For example:
Select Case myVariable
Case Is = MY_CONSTANT_1
' Do something
Case Is = MY_CONSTANT_2
' Do something else
End Select
- If you need to pass the constants as arguments to a function, you can use the ByVal keyword to pass them by value. For example:
Sub mySubroutine(ByVal myConstant As Integer)
' Do something with myConstant
End Sub
' Call the subroutine with a constant
mySubroutine(MY_CONSTANT_1)
By using constants instead of enums, you can avoid the «Constant Expression Required» error in VBA. This can save you time and frustration in your development work.
Method 2: Specify a Data Type for Your Enum
One way to fix the «Constant Expression Required» error in VBA enums is to specify a data type for your enum. This will ensure that the values assigned to the enum are of the correct data type and can be used as constant expressions.
Here’s an example of how to specify a data type for your enum:
Public Enum MyEnum As Long
Value1 = 1
Value2 = 2
Value3 = 3
End Enum
In this example, the data type for the enum is specified as Long. The values assigned to the enum are also of type Long, which ensures that they can be used as constant expressions.
You can also use other data types for your enum, such as Integer or Byte, depending on your specific needs.
Here’s another example of how to use an enum with a specified data type in a function:
Public Function MyFunction(ByVal value As MyEnum) As String
Select Case value
Case Value1
MyFunction = "Value 1"
Case Value2
MyFunction = "Value 2"
Case Value3
MyFunction = "Value 3"
Case Else
MyFunction = "Unknown Value"
End Select
End Function
In this example, the MyFunction function takes a parameter of type MyEnum, which ensures that only valid enum values can be passed to the function. The function then uses a Select Case statement to determine the appropriate string value to return based on the enum value passed to it.
Overall, specifying a data type for your enum can help to prevent «Constant Expression Required» errors in VBA and ensure that your code is more robust and reliable.
Method 3: Use Option Explicit Statement
When working with VBA enums in Excel, you may occasionally encounter «Constant Expression Required» errors. These errors occur when you try to assign a non-constant value to an enum. One way to fix this issue is to use the «Use Option Explicit Statement» in your VBA code.
Step 1: Add Option Explicit Statement
The first step is to add the «Option Explicit» statement at the beginning of your VBA code. This statement forces you to declare all variables before using them, including enums.
Option Explicit
Public Enum Color
Red = 1
Green = 2
Blue = 3
End Enum
Step 2: Declare Enum Variables
Next, you need to declare your enum variables explicitly. This means that you need to specify the data type of the variable and the enum type.
Option Explicit
Public Enum Color
Red = 1
Green = 2
Blue = 3
End Enum
Public Sub Example()
Dim myColor As Color
myColor = Color.Red
End Sub
Step 3: Use Enum Values
Finally, you can use the enum values in your code without encountering «Constant Expression Required» errors.
Option Explicit
Public Enum Color
Red = 1
Green = 2
Blue = 3
End Enum
Public Sub Example()
Dim myColor As Color
myColor = Color.Red
If myColor = Color.Green Then
Debug.Print "Green"
ElseIf myColor = Color.Blue Then
Debug.Print "Blue"
Else
Debug.Print "Red"
End If
End Sub
By using the «Option Explicit» statement and declaring your enum variables explicitly, you can avoid «Constant Expression Required» errors and use enums in your VBA code more efficiently.
Method 4: Check for Typos in Enum Names
One common cause of «Constant Expression Required» errors in VBA enums is typos in the enum names. To fix this, you can use the following steps:
- Check for typos in the enum names by using the built-in VBA function
IsEnum
. This function returnsTrue
if the specified name is an enum, andFalse
otherwise.
If Not IsEnum("myEnum") Then
MsgBox "Invalid enum name: myEnum"
Exit Sub
End If
- If
IsEnum
returnsTrue
, use theEnum
keyword to define the enum and its values. Make sure that the enum names match the names used in the rest of your code.
Enum myEnum
Value1 = 1
Value2 = 2
End Enum
- Use the enum values in your code. You can refer to them by their names or by their values.
Dim myValue As myEnum
myValue = Value1
If myValue = Value2 Then
MsgBox "The value is 2"
End If
By following these steps and checking for typos in your enum names, you can avoid «Constant Expression Required» errors in your VBA code.
Method 5: Check for Conflicting Declarations of Enum
To fix the «Constant Expression Required» error in VBA enums, you can use the «Check for Conflicting Declarations of Enum» method. This method involves checking if there are any conflicting declarations of the same enum in your code.
Here’s an example code:
Enum Colors
Red = 1
Green = 2
Blue = 3
End Enum
Enum Sizes
Small = 1
Medium = 2
Large = 3
End Enum
Sub Example()
Dim myColor As Colors
myColor = Red
Dim mySize As Sizes
mySize = Medium
End Sub
In the above code, we have two enums — Colors and Sizes. Both of them have a value of 1, which can cause a conflict. To fix this, we can add the «Option Explicit» statement at the top of the module, which will force us to declare all variables.
Option Explicit
Enum Colors
Red = 1
Green = 2
Blue = 3
End Enum
Enum Sizes
Small = 1
Medium = 2
Large = 3
End Enum
Sub Example()
Dim myColor As Colors
myColor = Red
Dim mySize As Sizes
mySize = Medium
End Sub
Now, if we try to run the code, we will get an error message saying «Ambiguous name detected: Small». This means that the value 1 is already assigned to the «Red» color in the Colors enum. To fix this, we can change the value of the Sizes enum to avoid conflicts.
Option Explicit
Enum Colors
Red = 1
Green = 2
Blue = 3
End Enum
Enum Sizes
Small = 4
Medium = 5
Large = 6
End Enum
Sub Example()
Dim myColor As Colors
myColor = Red
Dim mySize As Sizes
mySize = Medium
End Sub
Now, the code will run without any errors.
In summary, to fix the «Constant Expression Required» error in VBA enums, you can use the «Check for Conflicting Declarations of Enum» method by adding the «Option Explicit» statement at the top of the module and checking for conflicting enum declarations.
Go to vba
TIP: If you get «Compile Error: Constant Expression Required»
…this is a very difficult question to Google, because most of the questions/answers you find are due to people LEGITIMATELY misusing non-constant statements. If your code looks like this:
Dim i As Long i = 5 Dim arr(i) As String
…then VBA will (rightly) complain that you can’t use a non-constant expression to declare an array. Or, if you do this:
Dim Pi As Double Pi = 3.1415 Const Two_Pi As Double = Pi * 2
…then, again, VBA will complain that you NEED to use a constant there. That’s NOT what I’m talking about here…I’m talking about times when your code is perfectly fine:
Dim taskcount As Long taskcount = 10 For i = 1 to taskcount Debug.Print i Next i
…but VBA complains about it anyway, and flags that third line «taskcount» variable, saying «Constant Expression Required», when we all know that a constant expression is NOT required there. I have no idea why this occurs, but it just randomly pops up from time to time, and recompiling the project doesn’t do anything…even restarting the program, or the entire computer, does not help. As it turns out, all you need to do is this:
Ctrl+A
Ctrl+X
Ctrl+V
That’s right…just cut all the code out of the module and paste it back in. I have NO idea why this works, but I guess it just forces VBA to re-evaluate the code, and that somehow makes it realize that it was fine all along.
If anyone has any good explanation about why this issue occurs, or why this fixes it, I’d be really interested to know. Also, let me know if you are getting this error and this does NOT fix it…you may have legitimate code issues, or maybe this just doesn’t always work.