34,333
edits
Changes
no edit summary
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 ==
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:
<pre>
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 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:
<pre>