Enumerations are often used in various languages to list certain variable variations within a single object to make them easy to find or list. The VBA Enum is a equally valuable construct – allowing you to clean up your mess by grouping a collection of constants into a single object you can easily explore. In this post I will also try to compare an alternative approach with the use of VBA Modules – also allowing you to enumerate constants but in a different fashion.
What is an Enum and why use it?
What is an Enum (enumeration)? It is a type that contains an enumeration of constants. A good example of an enumeration is a list of types of cars e.g. Sedan, Hatchback, SUV, Truck etc. Enumerations make it easy to group these values. Enums can be used as variable, however, an Enum is in fact a numeric variable (Long), which at any time represents one of items in the enumeration.
Why would you want to use enums? In most cases you might as well live without enums, but they are very useful! Imagine your application can throw multiple status message numbers, like errors or warnings. In most programming languages like C# or Java you can keep them in separate resource files. In VBA this is not the case. One way of grouping these messages would be to create constants:
Const msg_Welcome = 1 Const msg_Error = 2 Const msg_Warning = 3 Sub SomeProcedure '... Debug.Print "Message number: " & msg_Welcome '... End Sub
Seems ok, right? WRONG! When searching through your VBA code this is what you might see (on the right).
Your enumerated message numbers will get mixed up in a mumbo-jumbo of different variables. Well you can group these messages into a single Enumeration type like this:
'Declare the Enum Enum Messages Welcome = 1 Error = 2 Warning = 3 End Enum 'Example usage of Enum Sub SomeProcedure '... MsgBox "Message number: " & Messages.Welcome '... End Sub
Instead of the above, you can browse just your list of enumerations, without stumbling across other functions and variables.
Syntax of the VBA Enum
Let’s get introduced to the sytax of the VBA enum. First and foremost remember that the Enum is in fact a numeric variable (Long). A Enum variable represents one of its items (possible values).
Enum EnumName EnumValue [= LongValue] EnumValue [= LongValue] [[_EnumValue]] [= LongValue] '... End Enum
The VBA Enum needs to have specified enum values. These can optionally be defined with a certain long value. Each enum value is assigned a certain numeric value. The numbering starts at 0. If an enum item is unassigned with a long value it will be automatically assigned the increment of the previous item.
Enums allow you to hide elements using and underscore and brackets like this [_SomeValue]. These items won’t be visible using VBA “intellisense”.
Valid examples
The below are perfectly valid examples of VBA enumerations.
Assigning values to enums
Enum CarType Sedan 'Value = 0 HatchBack = 2 'Value = 2 SUV = 10 'Value = 10 Truck 'Value = 11 End Enum
An enum without any items assigned
Enum CarType Sedan 'Value = 0 HatchBack 'Value = 1 SUV 'Value = 2 Truck 'Value = 3 End Enum
Enumerating a VBA Enum
Funny as it sounds sometimes this is really what we want to do. Imagine you get a number representing one of your enum values (say one of 200 languages on the list). You want to know which item is being referenced. To do this we need to introduce the invisible enum values [_First] and [_Last] and loop through them to find our value.
Enum Language [_First] Albanian Armenian '... French English '... [_Last] End Enum
Finding our enum value:
Dim enumVal as Long, unknownEnumValue as Language For enumVal = Language.[_First] To Language.[_Last] If unknownEnumValue = enumVal Then 'Found it! '...Code here... Exit For End If Next enumVal
Type vs Module vs Enum
Most VBA users are often lost when having to distinguish the differences between Types, Modules and Enums. This is totally understandable thus let us clear out these misunderstandings.
Type
A Type in VBA is a custom data type that can be defined. It can only contain variables, not functions nor procedures. Types consist of multiple associated variables (like Classes), while an Enum is simply a numeric value that represents one of it’s possible items.
Type MyType SomeString as String SomeLong as Long End Type Sub Main() Dim t as MyType t.SomeString = "Hello" t.SomeLong = 10 End Sub
Module
A Module in VBA is simply a separate “section” of a VBA Project and can contain variables, constants and procedures. Module names can be used to select variables or procedures, thus making then an alternative to Enums when wanting to group enumerations of strings or other non-numeric data types.
VBA Enum
Enum is abbreviated as enumeration. It is a process in which we mention something one by one. Similarly, we have enumerations in every programming language be it JAVA, C or excel VBA. In VBA we have some inbuilt enumerations which starts with VB like VBnewLine is used to insert a new line. It is an enumeration. In Excel VBA we can also create our own custom enumerations.
In VBA, Enum is actually a variable just like integer or string and others. We can make a list of elements in VBA and use the variables. Enums are made to make things easier to use or easy to find. For example for a motorbike company like Bajaj enumeration will be a list of bikes they produce such as pulsar, Avenger, dominar, etc. The one thing which we need to keep in mind is that enum is like a numeric variable which can be used as a representation of one interpretation. There is also another way to use status messages by using constant but they can be tiresome because they are not grouped and come along with all the other enumerated variables of VBA. But with using VBA ENUM we can group our enumerations in one group and use them whenever we like.
Syntax of Enum in Excel VBA
The syntax to use ENUM in excel VBA is as follows:
Enum EnumName EnumValue [= LongValue] EnumValue [= LongValue] [[_EnumValue]] [= LongValue] End Enum
An important thing to remember is that the values specified in ENUM should have specific values but if we do not provide any value to it VBA automatically gives the first enum value as 0 and the next one as 1 and so on.
So as above I said about a motorbike company manufacturing bikes the enumeration for it will be such as follows.
ENUM Bikes Pulsar Avenger = 4 Dominar End ENUM
Now in the above sample enum, I have assigned values to only Avenger so by default pulsar is zero and dominar is 5 as the previous list value was 4. This is how values are assigned to ENUM values.
First, let us understand why enumerations are important in VBA then we will move to examples on how to make custom enumerations in VBA.
For a demonstration in VBA code try to refer to cell A1 and as soon as we use the dot operator we can see that many other enumerations pop up which may or may be not required for us. Have a look at the screenshot below.
We can see that in the above screenshot that there are many enumerations starting from A. Those are inbuilt VBA enumerations.
Now let us learn how to make custom enumerations in VBA by few examples of ourselves.
Note: In order to use Excel VBA ensure to have the developer’s tab enabled from the files tab and options section.
How to Make Custom Enumerations in Excel VBA
We will learn how to make custom Enumerations (Enum) with a few examples in Excel VBA.
You can download this VBA Enum Excel Template here – VBA Enum Excel Template
Excel VBA Enum – Example #1
Let us make a very simple enumeration first. In this example, we will define the greetings of the day as some numbers and display them as a personalized message.
Follow the below steps to use VBA Enum:
Step 1: In the developer’s tab click on Visual Basic to open VB Editor.
Step 2: Insert a new module from the insert tab in the VB Editor.
Step 3: Declare the Enum function with an enum name.
Code:
Enum Greetings End Enum
Step 4: Declare the enum values as follows,
Code:
Enum Greetings Morning = 1 Afternoon = 2 Evening = 3 Night = 4 End Enum
Step 5: Now declare a sub-function below the enum function to use the enum.
Code:
Enum Greetings Morning = 1 Afternoon = 2 Evening = 3 Night = 4 End Enum Sub UseEnum() End Sub
Step 6: Display a personalized message using msgbox function.
Code:
Enum Greetings Morning = 1 Afternoon = 2 Evening = 3 Night = 4 End Enum Sub UseEnum() MsgBox "Greeting Number" End Sub
Step 7: To display the greeting number we use the enum as follows,
Code:
Enum Greetings Morning = 1 Afternoon = 2 Evening = 3 Night = 4 End Enum Sub UseEnum() MsgBox "Greeting Number" & Greetings. End Sub
Step 8: Choose any of the greetings values as follows.
Code:
Enum Greetings Morning = 1 Afternoon = 2 Evening = 3 Night = 4 End Enum Sub UseEnum() MsgBox "Greeting Number" & Greetings.Afternoon End Sub
Step 9: Once done, compile and run the complete code by clicking on the play button which is located just below to the menu bar. When we run the code we see the following result.
It was very easy to create an enumeration and use them this is clear from the above example.
Excel VBA Enum – Example #2
Now in this example let us use enumeration to store the data in an excel sheet. We will use the example of motorbikes used in the introduction section.
We have some sort of pre-written calculation in sheet 1 as follows.
We will fill the cells of a count of motorbikes using enumerations and which will calculate the total cost of these bikes.
For this, Follow the below steps to use VBA Enum:
Step 1: Go to the developer’s tab to click on visual basic in order to open the VB Editor.
Step 2: Insert a new module from the insert tab in the VB Editor.
Step 3: Declare the enum function as motorbikes.
Code:
Enum Motorbikes End Enum
Step 4: Declare the enum list as follows,
Code:
Enum Motorbikes Pulsar = 20 Avenger = 15 Dominar = 10 Platina = 25 End Enum
Step 5: Now declare a sub-function to use these enumerations.
Code:
Enum Motorbikes Pulsar = 20 Avenger = 15 Dominar = 10 Platina = 25 End Enum Sub TotalCalculation() End Sub
Step 6: We know in order to use sheet 1 properties we need to activate the sheet first by the following code.
Code:
Enum Motorbikes Pulsar = 20 Avenger = 15 Dominar = 10 Platina = 25 End Enum Sub TotalCalculation() Worksheets("Sheet1").Activate End Sub
Step 7: Now assign the values of the cell by using enumeration as follows,
Code:
Enum Motorbikes Pulsar = 20 Avenger = 15 Dominar = 10 Platina = 25 End Enum Sub TotalCalculation() Worksheets("Sheet1").Activate Range("B2").Value = Motorbikes.Pulsar Range("B3").Value = Motorbikes.Avenger Range("B4").Value = Motorbikes.Dominar Range("B5").Value = Motorbikes.Platina End Sub
Step 8: Run the above code by the run button or press F5 and see the following result in sheet 1.
We can see in the above example that we have added values to the cells using VBA enumeration.
Now by the above examples, it is very clear to us what an ENUM in VBA is. ENUM is a numeric variable in VBA which is used to make data and referring to specific values easily. In Enum, we group the messages so that they can be used effectively.
Things to Remember
- ENUM is a numeric variable which can be custom built but it is also inbuilt in VBA.
- If we do not assign any values to ENUM values VBA automatically assigns values to them.
- To use the VBA enumerations in our code we refer them by enum name.
Recommended Articles
This has been a guide to VBA Enum. Here we discussed how to make custom enumerations in excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Range
- VBA Month
- VBA Active Cell
- VBA Login
Enum is a short form for enumerations. Almost in every programming language, we have enumerations. Some are pre-defined, and some are user-defined enumerations. Like in VBA, Vbnewline is an enumeration. We can make our enumerations using the Enum statement.
Table of contents
- VBA Enumerations (Enum)
- What is VBA Enum?
- The formula of VBA Enum
- Examples of VBA Enum
- Using VBA Enumeration Variables to Store the Data
- Recommended Articles
VBA Enumerations (Enum)
We usually declare variables and assign data types to them. We use common data types: Integer, Long, Single, Double, Variant, and String. But, we have one more data type, VBA “Enum.” You must think about what this is and looks like a strange thing. But to clear all your doubts, we are presenting this article on “VBA Enumerations.”
What is VBA Enum?
“Enum” means enumerations. Enum is a variable type just like our string, integer, or any other data type, but here we create a list element using the Excel VBA Enum statement. Enumeration means “the action of mentioning several things one by one.”
In Excel, VBA Enum is a type that contains an enumeration of constants. Enumerations create a list of items and make them in a group. For example, types of mobiles: Redmi, Samsung, Apple, Vivo, Oppo.
Using enumerations, we can group all of them under a single value. For example, one can use the Enum as a variable in VBA, a numeric variable data type of Long.
The formula of VBA Enum
If you do not understand anything, do not worry. You will slowly get the hang of it. Now, take a look at the formula of VBA Enum.
Enum GroupName Member1 = [Long] Member2 = [Long] Member3 = [Long] Member4 = [Long] Member5 = [Long] End Enum
As we said in the beginning, one can use Enum as a variable, the numeric variable data type of Long.
Examples of VBA Enum
Before we start the Enum examples, let us show you the “Constant” example in VBA. Constant is also a word used to declare the variable in VBA.
Look at the below codes.
Code:
Option ExplicitVBA option explicitly makes a user mandatory to declare all the variables before using them; any undefined variable will throw an error while coding execution. We can enable it for all codes from options to require variable declaration.read more Const Samsung = 15000 Const VIVO = 18000 Const Redmi = 8500 Const Oppo = 18500 Sub Enum_Example1() End Sub
We have declared the variables at the top of the module by using the Const word.
Const Samsung = 15000
Const VIVO = 18000
Const Redmi = 8500
Const Oppo = 18500
Now, we know all these variables are group members of mobile. So, if we want to use these variables, let us say “Vivo” in the module.
Code:
Sub Enum_Example1() V End Sub
As we start with the character “V,” we can see many other things of VBA mixed up with them, starting with the letter “V.”
It is where the picture of VBA “Enumerations” comes into the picture.
For better understanding, let us try to change the cell’s background color.
Code:
Sub Enum_Example1() AcriveCell.Interior.Color = RGB End Sub
As you can see in the above code, we can see all the RGB colors available in VBARGB can be also termed as red green and blue, this function is used to get the numerical value of the color value, this function has three components as a named range and they are red, blue and green the other colors are considered as the components of these three different colors in VBA.read more. These are all constants with wonderful names with them.
All these RGB colors are part of the family enumeration called “xlRGBColor.”
Code:
Sub Enum_Example1() AcriveCell.Interior.Color = xlrg End Sub
Using these VBA enumerations, we can access this enumeration’s group members.
Code:
Sub Enum_Example1() AcriveCell.Interior.Color = XlRgbColor. End Sub
As we can see in the above image, we see only color combinations, nothing else. It is a simple overview of the “VBA Enum.”
We will go back to our original example of mobile group members. Like how we have seen group members of RGB color similarly, we can declare the variables using the VBA Enum statement.
Code:
Enum Mobiles Samsung = 15000 VIVO = 18000 Redmi = 8500 Oppo = 18500 End Enum Sub Enum_Example1() End Sub
We have now declared all the mobile brands under the “Mobiles” group using “Enum” statements.
Using the group name “Mobiles,” we can now access all these brands in the module.
Code:
Enum Mobiles Samsung = 15000 VIVO = 18000 Redmi = 8500 Oppo = 18500 End Enum Sub Enum_Example1() Mob End Sub
Select the group and put a dot to see all the group members.
We can see only the group members’ “Mobiles” and nothing else. That is how we can use VBA enumerations to group a list of items under one roof.
Using VBA Enumeration Variables to Store the Data
Let us see a simple example of using declared Enum variables. First, declare the Enum group name as “Department” and add the department’s names as the group member.
Code:
Enum Mobiles Finance = 150000 HR = 218000 Sales = 458500 Marketing = 718500 End Enum Sub Enum_Example1() End Sub
We have declared each department’s salary numbers in front of them.
Now, we will store the values of these numbers in an Excel sheet. Before applying the code, create a table like the one below.
Now, go back to the basic visual editor and refer the cell B2 using the RANGE object.
Code:
Sub Enum_Example1() Range("B2").Value = End Sub
In the A2 cell, we have the “Finance” department, so in the B2 cell, we will store the department’s salary. So first, access the group name “Department.”
Code:
Sub Enum_Example1() Range("B2").Value = Dep End Sub
Now in this group, we can see only declared department names.
Code:
Sub Enum_Example1() Range("B2").Value = Department. End Sub
Select the department named “Finance.”
Code:
Sub Enum_Example1() Range("B2").Value = Department.Finance End Sub
Similarly, for all the other cells, select the respective department names.
Code:
Sub Enum_Example1() Range("B2").Value = Department.Finance Range("B3").Value = Department.HR Range("B4").Value = Department.Marketing Range("B5").Value = Department.Sales End Sub
Run this VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more to get the assigned salary amount for these departments.
It is how we can use VBA Enum.
You can download this VBA Enum Excel here. VBA Enum Excel Template
Recommended Articles
This article is a guide to what is VBA Enum (Enumerations). Here, we discuss how we can use VBA Enum along with examples and download an Excel template. Below are some useful Excel articles related to VBA: –
- Data Type in VBA
- VBA Union
- UCase in VBA
- Functions in VBA
- VBA Enum
VBA Enum
Enum сокращенно обозначается как перечисление. Это процесс, в котором мы упоминаем что-то один за другим. Точно так же у нас есть перечисления в каждом языке программирования, будь то JAVA, C или Excel VBA. В VBA у нас есть некоторые встроенные перечисления, которые начинаются с VB, например, VBnewLine используется для вставки новой строки. Это перечисление. В Excel VBA мы также можем создавать наши собственные нумерации.
В VBA Enum на самом деле является переменной, такой же как целое число или строка и другие. Мы можем составить список элементов в VBA и использовать переменные. Перечисления сделаны, чтобы сделать вещи проще в использовании или легко найти. Например, для такой мотоциклетной компании, как Bajaj, список будет производиться как велосипеды, такие как пульсар, мститель, доминар и т. Д. Единственное, что нам нужно помнить, это то, что enum похож на числовую переменную, которую можно использовать как представление одной интерпретации. Существует также другой способ использовать сообщения о состоянии, используя константу, но они могут быть утомительными, поскольку они не сгруппированы и идут вместе со всеми другими перечисляемыми переменными VBA. Но с помощью VBA ENUM мы можем сгруппировать наши перечисления в одну группу и использовать их, когда захотим.
Синтаксис Enum в Excel VBA
Синтаксис для использования ENUM в Excel VBA выглядит следующим образом:
Enum EnumName EnumValue (= LongValue) EnumValue (= LongValue) ((_EnumValue)) (= LongValue) End Enum
Важно помнить, что значения, указанные в ENUM, должны иметь конкретные значения, но если мы не предоставляем никаких значений, VBA автоматически присваивает первому значению enum значение 0, а следующему — 1 и т. Д.
Поэтому, как я уже говорил выше, для мотоциклетной компании, производящей велосипеды, перечень будет таким:
ENUM Bikes Pulsar Avenger = 4 Доминар Энд ENUM
Теперь в приведенном выше примере перечисления я назначил значения только для Avenger, поэтому по умолчанию pulsar равен нулю, а dominar равен 5, так как предыдущее значение списка было 4. Именно так значения присваиваются значениям ENUM.
Сначала давайте поймем, почему перечисления важны в VBA, а затем перейдем к примерам создания пользовательских перечислений в VBA.
Для демонстрации в коде VBA попытайтесь обратиться к ячейке A1, и как только мы используем оператор точки, мы увидим, что всплывают многие другие перечисления, которые могут или не могут потребоваться для нас. Посмотрите на скриншот ниже.
На приведенном выше снимке экрана видно, что существует множество перечислений, начиная с A. Это встроенные перечисления VBA.
Теперь давайте научимся создавать пользовательские перечисления в VBA на нескольких примерах.
Примечание. Чтобы использовать Excel VBA, убедитесь, что вкладка разработчика включена на вкладке «Файлы» и в разделе «Параметры».
Как сделать пользовательские перечисления в Excel VBA
Мы научимся создавать собственные перечисления (Enum) на нескольких примерах в Excel VBA.
Вы можете скачать этот шаблон VBA Enum Excel здесь — Шаблон VBA Enum Excel
Excel VBA Enum — Пример № 1
Давайте сначала сделаем очень простое перечисление. В этом примере мы определим приветствия дня как некоторые цифры и отобразим их как персонализированное сообщение.
Выполните следующие шаги, чтобы использовать VBA Enum:
Шаг 1: На вкладке разработчика нажмите Visual Basic, чтобы открыть VB Editor.
Шаг 2: Вставьте новый модуль с вкладки «Вставка» в VB Editor.
Шаг 3: Объявите функцию Enum с именем enum.
Код:
Enum Greetings End Enum
Шаг 4: Объявите значения перечисления следующим образом:
Код:
Enum Поздравления Утро = 1 День = 2 Вечер = 3 Ночь = 4 Конец Enum
Шаг 5: Теперь объявите подфункцию ниже функции enum для использования enum.
Код:
Enum Приветствия Утро = 1 День = 2 Вечер = 3 Ночь = 4 End En Sub Sub UseEnum () End Sub
Шаг 6: Показать персональное сообщение, используя функцию msgbox.
Код:
Enum Greetings Morning = 1 День = 2 Вечер = 3 Ночь = 4 End En Sub SubEnum () MsgBox "Greeting Number" End Sub
Шаг 7: Для отображения номера приветствия мы используем перечисление следующим образом:
Код:
Enum Greetings Утро = 1 День = 2 Вечер = 3 Ночь = 4 End Enum Sub UseEnum () MsgBox "Greeting Number" & Greetings. End Sub
Шаг 8: Выберите любое из значений приветствия следующим образом.
Код:
Enum Greetings Morning = 1 День = 2 Вечер = 3 Ночь = 4 End Sub Sub UseEnum () MsgBox "Greeting Number" & Greetings.Af днем End Sub
Шаг 9: Когда закончите, скомпилируйте и запустите полный код, нажав на кнопку воспроизведения, расположенную чуть ниже строки меню. Когда мы запускаем код, мы видим следующий результат.
Было очень легко создать перечисление и использовать их, это ясно из приведенного выше примера.
Excel VBA Enum — Пример № 2
Теперь в этом примере давайте воспользуемся перечислением для хранения данных в листе Excel. Мы будем использовать пример мотоциклов, использованных во вводном разделе.
У нас есть какой-то предварительный расчет на листе 1 следующим образом.
Мы заполним ячейки подсчета мотоциклов, используя перечисления, которые подсчитают общую стоимость этих мотоциклов.
Для этого выполните следующие действия, чтобы использовать VBA Enum:
Шаг 1: Перейдите на вкладку разработчика, чтобы щелкнуть Visual Basic, чтобы открыть VB Editor.
Шаг 2: Вставьте новый модуль с вкладки «Вставка» в VB Editor.
Шаг 3: Объявите функцию enum как мотоциклы.
Код:
Enum Motorbikes End Enum
Шаг 4: Объявите список перечислений следующим образом:
Код:
Enum Motorbikes Pulsar = 20 Мститель = 15 Доминар = 10 Платина = 25 End Enum
Шаг 5: Теперь объявите подфункцию для использования этих перечислений.
Код:
Enum Motorbikes Pulsar = 20 Мститель = 15 Доминар = 10 Платина = 25 End En Sub Sub TotalCalculation () End Sub
Шаг 6: Мы знаем, что для использования свойств листа 1 нам нужно сначала активировать лист с помощью следующего кода.
Код:
Enum Motorbikes Pulsar = 20 Мститель = 15 Доминар = 10 Платина = 25 End En Sub SubCalculation () Рабочие таблицы ("Sheet1"). Активировать End Sub
Шаг 7: Теперь присвойте значения ячейке, используя перечисление следующим образом:
Код:
Enum Motorbikes Pulsar = 20 Мститель = 15 Dominar = 10 Platina = 25 End Enum Sub TotalCalculation () Рабочие листы ("Sheet1"). Активировать диапазон ("B2"). Значение = Мотоциклы. Диапазон Pulsar ("B3"). Значение = Мотоциклы . Диапазон мстителя ("B4"). Значение = Мотоциклы. Номинальный диапазон ("B5"). Значение = Мотоциклы. Платина End Sub
Шаг 8: Запустите приведенный выше код с помощью кнопки запуска или нажмите F5 и просмотрите следующий результат на листе 1.
В приведенном выше примере мы видим, что мы добавили значения в ячейки, используя перечисление VBA.
Теперь из приведенных выше примеров нам очень ясно, что такое ENUM в VBA. ENUM — это числовая переменная в VBA, которая используется для создания данных и простого обращения к конкретным значениям. В Enum мы группируем сообщения, чтобы их можно было эффективно использовать.
То, что нужно запомнить
- ENUM — это числовая переменная, которая может быть создана пользователем, но также встроена в VBA.
- Если мы не присваиваем значения ENUM, VBA автоматически присваивает им значения.
- Чтобы использовать перечисления VBA в нашем коде, мы ссылаемся на них по имени enum.
Рекомендуемые статьи
Это был путеводитель по VBA Enum. Здесь мы обсудили, как сделать пользовательские перечисления в Excel VBA вместе с практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —
- VBA Range | Учебники по Excel
- Группировка столбцов в Excel
- VBA Active Cell
- VLOOKUP Учебник в Excel
Microsoft has recently introduced a structure into VBA to categorize the plethora of symbolic constants. This structure is called an enum , which is short for enumeration. A list of enums can be obtained using my Object Model Browser software. For instance, among Excel’s 152 enums, there is one for the fill type used by the AutoFill method, defined as follows:
Enum XlAutoFillType xlFillDefault = 0 xlFillCopy = 1 xlFillSeries = 2 xlFillFormats = 3 xlFillValues = 4 xlFillDays = 5 xlFillWeekdays = 6 xlFillMonths = 7 xlFillYears = 8 xlLinearTrend = 9 xlGrowthTrend = 10 End Enum
(The Excel documentation incorrectly refers to this enum as XlFillType.) Note that enum names begin with the letters Xl (with an uppercase X ).
Thus, the following line of code will autofill the first seven cells in the first row of the active sheet with the days of the week, assuming that the first cell contains the word Monday:
ActiveSheet.Range(«A1»).AutoFill ActiveSheet.Range(«A1:G1»), xlFillDays
This is far more readable than:
ActiveSheet.Range(«A1»).AutoFill ActiveSheet.Range(«A1:G1»), 5
Note that this enum is built in, so we do not need to add it to our programs in order to use these symbolic constants. (We can create our own enums, but this is generally not necessary in Excel VBA programming, since Excel has done such a good job of this for us.)
As another example, the built-in enum for the constant values that can be returned when the user dismisses a message box (by clicking on a button) is:
Enum VbMsgBoxResult vbOK = 1 vbCancel = 2 vbAbort = 3 vbRetry = 4 vblgnore = 5 vbYes = 6 vbNo = 7 End Enum
For instance, when the user hits the OK button on a dialog box (assuming it has one), VBA returns the value vbOK. Certainly, it is a lot easier to remember that VBA will return the symbolic constant vbOK than to remember that it will return the constant 1. (We will discuss how to get and use this return value later.)
VBA also defines some symbolic constants that are used to set the types of buttons that will appear on a message box. These are contained in the following enum (which includes some additional constants not shown):
Enum VbMsgBoxStyle vbOKOnly = 0 vbOKCancel = 1 vbAbortRetrylgnore = 2 vbYesNoCancel = 3 vbYesNo = 4 vbRetryCancel = 5 End Enum
To illustrate, consider the following code:
If MsgBox(«Proceed?», vbOKCancel) = vbOK Then
‘ place code to execute when user hits OK button Else
‘ place code to execute when user hits any other button End If
In the first line, the code MsgBox(«Proceed?», vbOKCancel) causes Excel to display a message box with an OK button and a Cancel button and the message «Proceed?», as shown in Figure 5-1.
Figure 5-1. Example message box
Figure 5-1. Example message box
If the user clicks the OK button, Excel will return the constant value vbOK; otherwise it will return the value vbCancel. Thus, the If statement in the first line will distinguish between the two responses. (We will discuss the If statement in detail in Chapter 8. Here, we are interested in the role of symbolic constants.)
In case you are not yet convinced of the value of symbolic constants, consider the following enum for color constants:
Enum ColorConstants vbBlack = 0 vbBlue = 16711680 vbMagenta = 16711935 vbCyan = 16776960 vbWhite = 16777215 vbRed = 2 55 vbGreen = 65280 vbYellow = 65535 End Enum
Consider which you’d rather type, this:
ATextBox.ForeColor = vbBlue or this:
ATextBox.ForeColor = 16711680 Need I say more?
Continue reading here: Variable Declaration
Was this article helpful?