Dynamically Looping An Enum (ADDED: Using strings as Enum names)
I just ran across this code in a vbAccelerator.com sample project.
If you are developing an project and using enums, but find that you are adding things to the Enum often, you can use this cool trick when declaring it:
VB Code:
Public Enum eMyConstants
[_First] = 1
EMCFirstValue = 1
EMCSecondValue = 2
EMCThirdValue = 3
EMCFourthValue = 4
[_Last] = 4
End Enum
Then you can use it like this:
VB Code:
For i = eMyConstants.[_First] To eMyConstants.[_Last]
' Do something here
End If
As you add values to your enum, you don't have to go back and change every loop. All you have to do is change the value of [_Last] and you will be site.
Note that [_First] and [_Last] don't show up in the Object Brower or any code-tip pop-ups in VB.
I didn't know this existed until today, so it might function in other areas as well. Who knows. If anyone could give me examples of other ways to use similar syntax, I would appriciate it.
NOTE: This won't work if your constants are not consecutive. If you all your constants were powers of 2 (a very commen situation), you could do something like this:
VB Code:
Public Enum eMyConstants
[_First] = 0
EMCFirstValue = 1
EMCSecondValue = 2
EMCThirdValue = 4
EMCFourthValue = 8
[_Last] = 3
End Enum
' In use:
For i = eMyConstants.[_First] To eMyConstants.[_Last]
lCurrent = 2 ^ i
' You should have the current value in the enum at your service
' [_Last] Has the value of 3 and 2 ^ 3 is 8 which is our last enum value.
Next i
Re: Dynamically Looping An Enum (Use when adding things to Enum often)
Today, while looking through more code written by other people I ran across this other cool Enum trick. It allows you to use strings for your Enum names instead of the normal variable naming setup. It works like this:
VB Code:
Public Enum eMyEnum
[My Value Number 1]
[Another value with a descriptive name here]
[mwhaha I can use spaces]
End Enum
' In use:
Private Sub Command1_Click()
Dim eTest As eMyEnum
' You get a cool code-sense pop up with all the values like usual,
' but this way, you can use spaces and other characters
a = [Another value with a descriptive name here]
If (a = [My Value Number 1]) Then
MsgBox "YAY!"
End If
End Sub
PS - Thanks to Merri for this one. I saw it in his Sudoku solver code.