Vba constant expression required ошибка

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.

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:

  1. 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
  1. Replace any instances of your enum with the corresponding constant. For example:
' Before
myEnum = MY_ENUM_VALUE

' After
myEnum = MY_CONSTANT_1
  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
  1. 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:

  1. Check for typos in the enum names by using the built-in VBA function IsEnum. This function returns True if the specified name is an enum, and False otherwise.
If Not IsEnum("myEnum") Then
    MsgBox "Invalid enum name: myEnum"
    Exit Sub
End If
  1. If IsEnum returns True, use the Enum 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
  1. 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.

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:

Static array instead of dynamic array

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!
vba save as

Learn More!

vba-free-addin

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

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Правка макроса (constant expression required)

Leojse

Дата: Понедельник, 21.07.2014, 21:10 |
Сообщение № 1

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 148


Репутация:

1

±

Замечаний:
0% ±


2010/2013

Добрый вечер, уважаемые форумчане!
Стыдно уже писать на форуме, но пока не вижу для себя другого выхода.
Пытаюсь из двух столбцов с помощью макроса в столбец G вывести значения, которые отсутствуют в столбцах А и В. В примере диапазон ограничивается от 1 до 16. Но диапазон «от» и «до» постоянно меняется. Можно, вообщем-то прописывать этот диапазон каждый раз вручную, правя код, но хочется узнать, возможно ли с помощью InputBox вводить значение «от» и значение «до» при каждом запуске макроса? Также, хочу спросить, возможно ли, чтобы результат вносился в столбец G не с первой ячейки?
Попытался сам что-то сделать, но ничего не получилось. Выделяет переменную b и пишет «constant expression required».
И, как обычно, заранее спасибо и много «+»!

К сообщению приложен файл:

7109334.xls
(36.0 Kb)

 

Ответить

_Boroda_

Дата: Понедельник, 21.07.2014, 21:34 |
Сообщение № 2

Группа: Модераторы

Ранг: Местный житель

Сообщений: 16620


Репутация:

6465

±

Замечаний:
0% ±


2003; 2007; 2010; 2013 RUS

Если Вы хотите именно этот макрос, то его можно переделать так
[vba]

Код

Sub Numbers()
Dim a, b
Dim Num() As Boolean, RA As Range, n&, r&, r0&
On Error Resume Next
a = InputBox(«Введите начальное число», «Ввод первого числа»)
b = InputBox(«Введите конечное число», «Ввод второго числа»)
ReDim Num(a To b)
On Error Resume Next
For Each RA In Selection
       Num(RA.Value) = True
Next
r0 = 5’Начальная строка
For n = LBound(Num) To UBound(Num)
       If Num(n) = False Then r = r + 1: Cells(r + r0-1, «G») = n
Next
Erase Num
End Sub

[/vba]


Скажи мне, кудесник, любимец ба’гов…
Платная помощь:
Boroda_Excel@mail.ru
Яндекс-деньги: 41001632713405 | Webmoney: R289877159277; Z102172301748; E177867141995

 

Ответить

Leojse

Дата: Понедельник, 21.07.2014, 21:41 |
Сообщение № 3

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 148


Репутация:

1

±

Замечаний:
0% ±


2010/2013

_Boroda_, спасибо Вам огромное! А можно чисто теоретический вопрос? Можно в одном окне InputBox вводить сразу 2 значения?
[offtop]Я только сейчас начал основательно вникать во всё это… Имею ввиду процедуры, методы, классы, свойства, и т.д. И откуда Вы всё это знаете?)

 

Ответить

_Boroda_

Дата: Понедельник, 21.07.2014, 21:51 |
Сообщение № 4

Группа: Модераторы

Ранг: Местный житель

Сообщений: 16620


Репутация:

6465

±

Замечаний:
0% ±


2003; 2007; 2010; 2013 RUS

Можно в одном окне InputBox вводить сразу 2 значения?

Например, так можно
[vba]

Код

Sub Numbers()
Dim a, b, aa
Dim Num() As Boolean, RA As Range, n&, r&, r0&
On Error Resume Next
aa = InputBox(«Введите начальное и конечное числа через запятую»)
a = Int(—aa)
b = WorksheetFunction.Substitute(aa — a, «0,», «»)
ReDim Num(a To b)
On Error Resume Next
For Each RA In Selection
        Num(RA.Value) = True
Next
r0 = 5
For n = LBound(Num) To UBound(Num)
        If Num(n) = False Then r = r + 1: Cells(r + r0, «G») = n
Next
Erase Num
End Sub

[/vba]

И откуда Вы всё это знаете?

Это почти как у Сократа: чем больше я знаю, тем больше я понимаю, что знаю очень мало.
Где-то когда-то вычитал (вольная цитата): знание — это шар, чем он больше, тем у него больше площадь соприкосновения с неведомым.


Скажи мне, кудесник, любимец ба’гов…
Платная помощь:
Boroda_Excel@mail.ru
Яндекс-деньги: 41001632713405 | Webmoney: R289877159277; Z102172301748; E177867141995

 

Ответить

Skif-F

Дата: Понедельник, 21.07.2014, 21:53 |
Сообщение № 5

Группа: Проверенные

Ранг: Участник

Сообщений: 73


Репутация:

14

±

Замечаний:
0% ±


Excel 2007, 2010, 2013, 2016

Можно ввести значения, например, через какой-то разделитель (слэш, пробел, запятая, точка с запятой — как Вам удобнее), а потом программно разделить полученную строку на 2 значения:
[vba]

Код

Sub Numbers()
     Dim a, b, c As String
     Dim Num() As Boolean, RA As Range, n&, r&, r0&
     c = InputBox(«Введите два числа через косую черту» & vbCr & «Например: 2/3», «Ввод чисел»)
     a = CInt(Left(c, InStr(1, c, «/») — 1))
     b = CInt(Right(c, Len(c) — InStr(1, c, «/»)))
     ReDim Num(a To b)
     On Error Resume Next
     For Each RA In Selection
         Num(RA.Value) = True
     Next
     r0 = 5 ‘Начальная строка
     For n = LBound(Num) To UBound(Num)
         If Num(n) = False Then r = r + 1: Cells(r + r0 — 1, «G») = n
     Next
     Erase Num
End Sub

[/vba]

 

Ответить

Leojse

Дата: Понедельник, 21.07.2014, 21:55 |
Сообщение № 6

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 148


Репутация:

1

±

Замечаний:
0% ±


2010/2013

Skif-F, Большое спасибо!!!

Сообщение отредактировал LeojseПонедельник, 21.07.2014, 21:56

 

Ответить

Leojse

Дата: Понедельник, 21.07.2014, 21:57 |
Сообщение № 7

Группа: Проверенные

Ранг: Форумчанин

Сообщений: 148


Репутация:

1

±

Замечаний:
0% ±


2010/2013

_Boroda_, И Вам преогромнейшее спасибо еще раз!)

 

Ответить

Понравилась статья? Поделить с друзьями:
  • Vehicule a controller ошибка рено сценик 3
  • Vba 1004 ошибка как исправить
  • Vegas160 exe системная ошибка
  • Vavada ошибка платежа при оплате
  • Vaporesso target pm80 short atomizer ошибка