Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleUse a macro to build a Select Case statement for an enumerated value in Visual Basic 2005
DescriptionThis example shows how to use a macro to build a Select Case statement for an enumerated value in Visual Basic 2005.
Keywordsmacro, enum, select case, VB.NET, VB 2005
CategoriesSoftware Engineering
 
This example should work in other versions of Visual Basic .NET.

This example shows how to build a macro that generates code. This example makes a Select Case statement to handle each of the allowed values for an enumerated type. This example uses the following enumerated type:

 
Public Enum Sizes
    Small
    Medium
    Large
    ExtraLarge
End Enum
 
It generates this code:
 
Select Case selected_size
    Case Sizes.Small

    Case Sizes.Medium

    Case Sizes.Large

    Case Sizes.ExtraLarge

    Case Else

End Select
 
Start by selecting Tools\Macros\Macro Explorer. Then open a macro module or create a new one and enter this macro:
 
Sub MakeEnumSelectCase()
    Dim var_name As String = InputBox("Variable Name:")
    If var_name.Length = 0 Then Exit Sub
    Dim enum_name As String = InputBox("Enum Name:")
    If enum_name.Length = 0 Then Exit Sub

    Dim fcm As FileCodeModel = _
        DTE.ActiveDocument.ProjectItem.FileCodeModel
    Dim enum_element As CodeElement = _
        FindElement(fcm.CodeElements, enum_name)
    If enum_element Is Nothing Then
        MsgBox("Cannot find enum " & enum_name, _
            MsgBoxStyle.Critical, "Enum Not Found")
        Exit Sub
    End If

    ' Start the Select Case.
    DTE.ActiveDocument.Selection.NewLine()
    DTE.ActiveDocument.Selection.Text = "Select Case " & _
        var_name
    DTE.ActiveDocument.Selection.NewLine()

    ' Write the Case statements.
    For Each value_element As CodeElement In _
        enum_element.Children
        DTE.ActiveDocument.Selection.Text = "Case " & _
            enum_element.Name & "." & value_element.Name
        DTE.ActiveDocument.Selection.NewLine()
        DTE.ActiveDocument.Selection.NewLine()
        DTE.ActiveDocument.Selection.DeleteLeft()
    Next value_element

    ' Write the Case Else statement.
    DTE.ActiveDocument.Selection.Text = "Case Else"
    DTE.ActiveDocument.Selection.NewLine()
    DTE.ActiveDocument.Selection.DeleteLeft()
End Sub
 
To run the macro, position the cursor on a blank line where you want the Select Case statemet and run the macro. When prompted, enter the name of the variable (selected_sizes) and the name of the Enum (Sizes).
 
 
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated