Visual Basic Flow Control

Revision as of 14:42, 5 May 2016 by Neil (Talk | contribs) (Text replacement - "<table border="0" cellspacing="0" width="100%">" to "<table border="0" cellspacing="0">")

Revision as of 14:42, 5 May 2016 by Neil (Talk | contribs) (Text replacement - "<table border="0" cellspacing="0" width="100%">" to "<table border="0" cellspacing="0">")

PreviousTable of ContentsNext
Visual Basic Comparison and LogicVisual Basic For Loops


Purchase and download the fully updated Visual Basic 2010 edition of this eBook in PDF and ePub for only $9.99


In Visual Basic Comparison and Logic we looked at how to use Visual Basic logical expressions to decide if something is True or False. Much of the art of programming involves writing code that makes decisions based on one or more criteria. Such decisions define which code gets executed and which code gets by-passed when the application is running. This is often referred to as flow control since it controls the flow of execution.

In previous chapters, the If statement has been widely used in examples. In this chapter of Visual Basic Essentials we are going to cover the various forms of If statements such as If .. Then .. Else, together with other decision making code structures such as Select Case and GoTo

Using If ... Then to Make Decisions

The If ... Then construct is probably the most common decision making tool used by Visual Basic programmers. The basic syntax of this decision structure is as follows:

If expression Then

.. Code to be executed is expression is True ..

Endif

Essentially if the expression evaluates to True (see Visual Basic Comparison and Logic for more details of this type of logic) then the code in the body of the statement is executed. If, on the other hand, the expression evaluates to False the code is skipped.

For example, if a decision needs to be made depending on whether one string matches another, the following code might be used:

        Dim myName As String = "John Doe"

        If myName = "John Doe" Then
            MessageBox.Show("Strings match")
        End If

Clearly, the strings match, so the above code will cause the MessageBox to appear.

Using If ... Then .. Else to Make Decisions

The next variation of If statement allows us to also specify some code to perform if the expression in the If statement evaluates to False. The syntax for this construct is as follows:

If expression Then

.. Code to be Executed is expression is True ..

Else

.. Code to be executed is expression is False

Endif

We can, therefore, extend our previous example to display a different message if the comparison expression evaluates to be False:

        Dim myName As String = "John Doe"

        If myName = "John Smith" Then
            MessageBox.Show("Strings match")
        Else
            MessageBox.Show("Strings do not match")
        End If

In this case, the strings to do not match, so the second MessageBox will display.


Using If ... Then .. ElseIf to Make Decisions

<google>ADSDAQBOX_FLOW</google> The final variation of the If .. Then structure is the If .. Then .. ElseIf construct. This allows multiple expressions to be evaluated in a single structure. The syntax of If .. Then .. ElseIf is as follows:

If expression Then

.. Code to be Executed is expression is True ..

ElseIf expression Then

.. Code to be executed is expression is True

ElseIf expression Then

.. Code to be executed is expression is True

Endif

For example, the following code construct uses the ElseIf approach to find a match to a string:

        Dim myName As String = "John"

        If myName = "Fred" Then
            MessageBox.Show("Hello Fred")
        ElseIf myName = "John" Then
            MessageBox.Show("Hello John")
        ElseIf myName = "Paul" Then
            MessageBox.Show("Hello Paul")
        End If

This approach works well for a moderate number of comparisons, but can become cumbersome for a larger volume of values or expression evaluations. For such situations, the Select Case construct provides a more flexible and efficient solution.

Evaluating Multiple Possibilities using Select Case

The Visual Basic Select Case construct is extremely useful if you need to evaluate a value or expression against multiple possible outcomes. For example you might want to compare a string against a variety of other strings in order to decide what action to take. The syntax for the Select Case construct is as follows:

Select Case expression
  Case value1, value2, ...
    ...
  Case value3, value3, ...
    ...
  Case value1, value2, ...
    ...
End Select

As with most programming concepts, this is best explained using examples. The following code excerpt shows a Select Case construct which takes specific action depended on the value of a String variable:

        Dim strCity As String = "London"
        Dim strCountry As String

        Select Case strCity
            Case "Paris"
                strCountry = "France"
            Case "London"
                strCountry = "England"
            Case "Berlin"
                strCountry = "Germany"
        End Select

        MessageBox.Show("Welcome to " & strCountry)

It is also possible to specify more than one option per Case statement:

       Dim strCity As String = "Munich"
        Dim strCountry As String

        Select Case strCity
            Case "Paris", "St. Tropez"
                strCountry = "France"
            Case "London", "Sheffield", "Dover"
                strCountry = "England"
            Case "Berlin", "Munich"
                strCountry = "Germany"
        End Select

        MessageBox.Show("Welcome to " & strCountry)

One of the most powerful aspects of the Visual Basic Select Case construct (and a feature that is missing from the Select Case implementations in other programming languages) is the ability to specify a range of matches for a case statement. For example, the following code excerpt specifies acceptable value ranges for an integer match:

       Dim intSize As Integer = 6
        Dim strSize As String

        Select Case intSize
            Case 0 To 4
                strSize = "Small"
            Case 5 To 8
                strSize = "Medium"
            Case 9 To 12
                strSize = "Large"
        End Select

        MessageBox.Show("Shirt size is " & strSize)

Using the Visual Basic GoTo Statement

The Visual Basic GoTo statement provides a way for program execution to jump to a labeled location in the code.

Before going into detail of how to use the GoTo statement it is important to be aware that the use of the GoTo statement is generally considered to be bad programming practice. A programmer under pressure will often reach for the GoTo statement when they have programmed themselves into a corner and need some way of getting to another section of code. Almost without exception, a GoTo jump should never be needed if the code had been carefully planned in the first place. If you find yourself tempted to use a GoTo jump, take some time to step back from the code and make sure there is not a more elegant solution. Avoiding excessive GoTo statements will make the code easier to maintain and debug.

With that disclaimer we will now look at how to use a GoTo statement. As mentioned previously, the GoTo statement simply allows us to jump to a labeled code location somewhere else in an application. One valid use, which we will use in this example, is to exit a subroutine or function when an error is found:

Private Sub ValidateValue(ByVal intValue As Integer)
       If intValue > 10 Then 
             GoTo EXIT_SUB
       else
             ProcessValue(intValue)
             MessageBox.Show("Valid Number Entered")
       Endif

EXIT_SUB:
       Exit Sub
End Sub


Purchase and download the fully updated Visual Basic 2010 edition of this eBook in PDF and ePub for only $9.99