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.
peat Пользователь Сообщений: 119 |
#1 30.04.2013 18:35:30 Доброго времени суток! Надеюсь на вашу помощь)
Srok глобально объявлен как целое,
проблем с вызовом в каждой процедуре не было, но в каждую приходится писать эти вот строчки. Хотелось бы в сааааамом начале проекта его вычислить и вставлять по ходу действа, когда нужен. С другой переменной, тоже задающейся в самом начале, попробовал такую вот штуку:
заругалась «constant expression required». Найденные в сети варианты с Set… тоже успехом не увенчались. у меня вся эта байда во вкладке «Modules», где у меня описание всех кнопок, функции и тп. Мб куда в другое место надо перенести объявление глобальных переменных/констант? |
||||||
Юрий М Модератор Сообщений: 60780 Контакты см. в профиле |
Где у Вас объявлены глобальные переменные? Нужно в области деклараций стандартного модуля. Т.е. ПЕРЕД ними не должно никаких процедур. А значения им присваивайте в процедуре, которая выполняется самой первой. |
peat Пользователь Сообщений: 119 |
#3 30.04.2013 19:20:58 Юрий М, на самом верху, да:
перед ними ничего нет. Если в первой процедуре Srok получит значение 100500, то при любых дальнейших вызовов этой переменной, ее значение будет равно 100500? Изменено: peat — 30.04.2013 19:24:41 |
||
Юрий М Модератор Сообщений: 60780 Контакты см. в профиле |
Если затем это значение (100500) не менялось, то оно так и останется таким. И переменная будет доступна в любом модуле. |
The_Prist Пользователь Сообщений: 14265 Профессиональная разработка приложений для MS Office |
#5 30.04.2013 19:34:03 Вынесите присвоение переменным значений в отдельную процедуру(скажем InitPublic). Затем при открытии книги запускайте эту процедуру:
Так же на всякий случай в каждой процедуре, в которой переменная может понадобиться, можно делать проверку:
Так же можете почитать про переменные: Что такое переменная и как правильно её объявить? А то Вы их объявляете неверно(Юрий уже указал Вам на это). Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||||
Hugo Пользователь Сообщений: 23374 |
Ну и вместо integer пишите Long — оно оправданнее в новых версиях VBA, и кроме того у Вас с integer не будет работать на весь лист (ругнётся на LastRow (As Integer)). |
peat Пользователь Сообщений: 119 |
Юрий М, The_Prist, Hugo, спасибо Вам всем большое! ценные советы не знающим vba) |
peat Пользователь Сообщений: 119 |
#8 01.05.2013 01:10:30 The_Prist, сделал, как вы описали. Весь код в модулях прекрасно понимает глобальную переменную, но вот код в юзер форме отказывается это делать.
При дебагере эта процедура вызывается, но Srok все равно empty после прохождения. Изменено: peat — 01.05.2013 01:11:07 |
||
Юрий М Модератор Сообщений: 60780 Контакты см. в профиле |
А что у Вас в процедуре InitPublic? Где она? И может есть смысл показать небольшой файл, где всё это происходит? |
peat Пользователь Сообщений: 119 |
#10 01.05.2013 01:45:56 Юрий М, видимо, она не там… Она в самом верху модуля, в котором бОльшая часть кода.
Вероятно, она не там висит. Если не в этом дело, накрамсаю файл для примера. |
||
Юрий М Модератор Сообщений: 60780 Контакты см. в профиле |
И процедура InitPublic в модуле книги на событие открытия? Давайте лучше небольшой пример… |
The_Prist Пользователь Сообщений: 14265 Профессиональная разработка приложений для MS Office |
InitPublic должна быть расположена в стандартном модуле. Так же как и объявление Public переменных. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
peat Пользователь Сообщений: 119 |
нашел проблему — у меня не один стандартный модуль. При удалении других модулей глобальная переменная Srok спокойно работает в юзерформе. Надо создать какой-то другой модуль? читал по вашей ссылке про модуи классов — мне туда? Изменено: peat — 01.05.2013 11:48:49 |
The_Prist Пользователь Сообщений: 14265 Профессиональная разработка приложений для MS Office |
peat, Вы считаете необходимым пустое сообщение писать? Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
peat Пользователь Сообщений: 119 |
#15 01.05.2013 11:59:38 The_Prist, нет, просто надо было его удалить — не нашел кнопки) попробовал создать модуль класса, запихнул туда
не помогло — в юзер форме Srok = empty, если call InitPublic — то не находит ее.. |
||
The_Prist Пользователь Сообщений: 14265 Профессиональная разработка приложений для MS Office |
Необходимо поместить в один стандартный модуль — ЛЮБОЙ. СТАНДАРТНЫЙ. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
peat Пользователь Сообщений: 119 |
конечно, сам создал) но с вашей помощь сам и решил — в другом модуле эта же переменная тоже объявлялась, как паблик, в этом проблема и была)еще раз спасибо |
Юрий М Модератор Сообщений: 60780 Контакты см. в профиле |
Не понимаю — почему люди так упорно не желают показывать файлы-примеры?.. Давно бы получили правильный ответ. |
peat Пользователь Сообщений: 119 |
у меня достаточно большой файл, в нем много кода. он не сложный, никуда не претендует, но его много) надо бОльшую часть удалить, чтобы не мешала поиску проблему — лениво немного) и выкладывать как-то стремновато — диплом все ж таки) хотя пока подготавливал файл к выкладыванию, нашел ошибку) |
Юрий М Модератор Сообщений: 60780 Контакты см. в профиле |
#20 01.05.2013 13:08:47
Вам лениво готовить небольшой файл, а нам не лениво искать Вашу ошибку по описанию? С таким подходом помогающих у Вас поубавится… |
||
The_Prist Пользователь Сообщений: 14265 Профессиональная разработка приложений для MS Office |
На мой взгляд это как раз тот случай, когда размер не имеет значения Ошибка-то явно в объявлении, а не в самих кодах. Поэтому даже большой проект можно просмотреть бегло только в нужных местах, не ковыряясь в кодах. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
peat Пользователь Сообщений: 119 |
#22 01.05.2013 14:04:23 The_Prist, да вот именно, что я не один раз объявлял ее в этих самых кодах и, чистя их, нашел понял в чем ошибка)
мне казалось, скачивать файл еще муторней) В итоге, Вы и помогли по описанию |
||
sm_ph Пользователь Сообщений: 1 |
#23 26.06.2019 13:49:50 У меня работает так:
Изменено: sm_ph — 26.06.2019 13:51:44 |
||