
VBA
Assigning Values: By default, the first item in an Enum has a value of 0, and each subsequent item increments by 1. However, you can manually assign values to the items.
Enum Season
Spring
Summer
Autumn
Winter
End Enum
VBA
Using Enum in Code: You can now use the Enum in your procedures and functions as a data type. This makes your code more readable, as it’s clear what the set of allowable values are.
Enum Season
Spring = 1
Summer = 2
Autumn = 3
Winter = 4
End Enum
VBA
Calling a Procedure with Enum: When calling a procedure that uses an Enum, you can pass in the Enum values directly.
Sub ShowSeason(season As Season)
Select Case season
Case Season.Spring
MsgBox "It's Spring!"
Case Season.Summer
MsgBox "It's Summer!"
Case Season.Autumn
MsgBox "It's Autumn!"
Case Season.Winter
MsgBox "It's Winter!"
End Select
End Sub
VBA
IntelliSense Support: When you use an Enum in your code, VBA’s IntelliSense will provide you with a dropdown list of the Enum’s values, which can help prevent errors and speed up coding.
Scope of Enum: By default, Enum definitions are public within the module they’re declared in. If you want to restrict their scope to the module, use the Private keyword.
Sub Test()
ShowSeason Season.Summer
End Sub
VBA
Strong Typing: Enums provide strong typing, which means that you can set procedure arguments to be of a specific Enum type, reducing errors and making your code more robust.
Using Enum effectively makes your VBA code more structured, easier to understand, and reduces the likelihood of invalid values being used.
Private Enum Season
Spring
Summer
Autumn
Winter
End Enum