Skip navigation.
Home

Iterate over Enum Members

When you are dealing with a variable that can have one of a defined set of values, it is preferable to use an Enum to define those values, rather than use a primitive datatype like Integer.

This tip isn't about why Enums are better, it is about how to iterate over the range of valid values for the Enum. For example, given the following Enum:

    Private Enum FileOperation
        Open = 1
        Close = 2
        Save = 3
        SaveAs = 4
        Copy = 5
        Move = 6
        Delete = 7
    End Enum

We can iterate over the values (1 to 7) using the following code:

For Each value As FileOperation In [Enum].GetValues(GetType(FileOperation))
            MsgBox(value)
Next

You can iterate over the Names of the Enum members as follows:

        For Each name As String In [Enum].GetNames(GetType(FileOperation))
            MsgBox(name)
        Next