Introduction To The Visual Basic Programming Language
Introduction To The Visual Basic Programming Language
Microsoft Visual Basic 2005 Express Edition is a fast and easy way to create programs for Microsoft
Windows. Even if you are new to Windows programming, with Visual Basic you have a complete set of
tools to simplify development.
So what is Visual Basic? "Visual" refers to the method used to create what the user sees—the graphical
user interface, or GUI. "Basic" refers to the BASIC (Beginners All-Purpose Symbolic Instruction Code)
programming language, a language used by more programmers than any other language in the history
of computing. You can create useful programs by learning just a few of its features. The following links
will get you started with Visual Basic programming; each link includes examples, as well as access to
additional information.
Programming Concepts
What exactly is a programming language? The following links will give you some background on what a
language is and how it stores different types of information.
Term Definition
How a programming language works, along with
The Basics: How Programming Works
basic terminology.
Representing Words, Numbers, and Values How variables store values and represent
with Variables information, along with how to use variables.
Words and Text: Using String Variables to How to use a String variable to represent words and
Organize Words text.
Arrays: Variables That Represent More How to use an Array variable to represent several
Than One Value values of the same type.
Arithmetic: Creating Expressions With
How to write code that performs arithmetic.
Variables And Operators
Comparisons: Using Expressions to
How to write code that compares numeric values.
Compare Values
Ready for a bit of real-world programming? The following links will walk you through the creation of a
simple program and will show you how to check your program for errors.
Term Definition
Making Your Computer Do Something: How to write code that tells your program to perform
Writing Your First Procedure a particular action.
How to write code that repeats actions in your
Making Your Program Repeat Actions:
program and counts how many times these actions
Looping With the For...Next Loop
have been performed.
Making Your Program Choose Between How to write code that does different things in
Two Possibilities: The If...Then Statement response to different conditions.
What To Do When Something Goes How to write code that handles errors in your
1
programs. You will also learn about the different
Wrong: Handling Errors
types of errors.
The following links will help you build on your knowledge of programming and of the Visual Basic 2005.
Term Definition
Closer Look: Understanding Properties,
How properties, methods, and events work.
Methods, and Events
How data is stored using the different types of
Closer Look: Data Types
variables.
Closer Look: Converting from One Variable How to convert data from one type to another,
Type to Another along with some common pitfalls of this process.
How to use the Do...While and Do...Until
Closer Look: Using Do...While and
statements to repeat code based on certain
Do...Until to Repeat Until a Condition is Met
conditions.
Closer Look: Using Select Case to Decide How to run code based on multiple conditions,
Between Multiple Choices where there are many choices.
More of what you can do with the Visual Basic
Visual Basic Guided Tour
2005 programming language
A computer is essentially just a big bunch of tiny electronic switches that are either on or off. By setting
different combinations of these switches, you can make the computer do something, for example,
display something on the screen or make a sound. That's what programming is at its most basic—telling
a computer what to do.
Of course, understanding which combination of switches will make the computer do what you want
would be a daunting task—that's where programming languages come in.
People express themselves using a language with many words. Computers use a simple language
consisting of only 1s and 0s, with a 1 meaning "on" and a 0 meaning "off." Trying to talk to a computer
in its own language would be like trying to talk to your friends using Morse code—it can be done, but
why would you?
A programming language acts as a translator between you and the computer. Rather than learning the
computer's native language (known as machine language), you can use a programming language to
instruct the computer in a way that is easier to learn and understand.
2
A specialized program known as a compiler takes the instructions written in the programming language
and converts them to machine language. This means that as a Visual Basic programmer, you don't need
to understand what the computer is doing or how it does it, you just need to understand how the Visual
Basic programming language works.
In many ways, Visual Basic is a lot like the language that you use every day. When you speak or write,
you use different types of words, such as nouns or verbs, which define how they are used. Visual Basic
also has different types of words known as programming elements that define how they are used to
write programs.
Programming elements in Visual Basic include statements, declarations, methods, operators, and
keywords. As you complete the following lessons, you will learn more about these elements and how to
use them.
Written and spoken language also has rules, or syntax, that defines the order of words in a sentence.
Visual Basic also has syntax—at first it may look strange, but it is actually very simple. For example, to
state "The maximum speed of my car is 55", you would write:
You will learn more about syntax later, and tools in Visual Basic such as IntelliSense provide you with
guidance in using the correct syntax when writing programs.
The language you write and speak also has structure: for example, a book has chapters with paragraphs
that contain sentences. Programs written in Visual Basic also have a structure: modules are like
chapters, procedures are like paragraphs, and lines of code are like sentences.
Next Steps
In this lesson, you learned what a programming language is and how it works. In the next lesson, you
will start learning how to use the Visual Basic programming language. Don't worry—you'll be speaking
Visual Basic in no time at all!
You might ask, "Why use a variable when I could just use the information instead?" As the name
implies, variables can change the value that they represent as the program is running. For example, you
might write a program to track the number of jelly beans you have in a jar on your desk. Because candy
is meant to be eaten, the number of jelly beans in the jar is likely to change over time. Rather than
rewriting your program every time you get a sugar craving, you can represent the number of jelly beans
with a variable that can change over time.
1. Declare the variable. Tell the program the name and kind of variable you want to use.
3
3. Use the variable. Retrieve the value held in the variable and use it in your program.
Declaring Variables
When you declare a variable, you have to decide what to call it and what data type to assign to it.
You declare a variable using the Dim and As keywords, as shown below.
This line of code tells the program that you want to use a variable named aNumber , and that you want
it to be a variable that stores whole numbers (the Integer data type).
Because aNumber is an Integer, it can store only whole numbers. If you had wanted to store 42.5,
for example, you would have used the Double data type. And if you wanted to store a word, you'd use
a data type called a String. One other data type worth mentioning at this point is Boolean, which can
store a True or False value.
For more information about other variable types, see Closer Look: Data Types.
Assigning Variables
You assign a value to your variable with the = sign, which is sometimes called the assignment operator,
as shown in the following example.
aNumber = 42
This line of code takes the value 42 and stores it in the previously declared variable named aNumber.
As shown above, you can declare a variable on one line of code, and then later assign the value on
another line. This can result in an error if you try to use the variable before assigning it a value.
For that reason, it is a better idea to declare and assign variables on a single line. Even if you don't yet
know what value the variable will hold, you can assign a default value. The code for declaring and
assigning the same variables shown earlier would look like the following.
By declaring variables and assigning default values on a single line, you can prevent possible errors. You
can still use assignment to give the variable a different value later on.
Try It!
In this exercise, you will write a short program that creates four variables, assigns them values, and
then displays each value in a window called a message box. Let's begin by creating the project where
the code will be stored.
1. If it is not already open, open Visual Basic from the Windows Start menu.
4
3. In the New Project dialog box on the Templates pane, click Windows Application.
Visual Basic will create the files for your program and open the Form Designer.
The Code Editor opens to a section of code called Fo rm1_Load . This section of code, which is called a
procedure, contains instructions that will be carried out when the form is first loaded into memory.
Dim an In tegerAs I n tege r = 42 Dim aS ing leAs S ing le = 39 .345677653 Dim aSt r i ngAs
St r i ng= "I like candy"
Dim aBoo leanAs Boo lean = True
This code declares four variables—an Integer, a Single, a String, and a Boolean—and assigns their
default values.
Tip
As you typed the code, you may have noticed that after you typed As, a list of words
appeared below the cursor. This feature is called Intellisense. It allows you to just type the
first few letters of a word until the word is selected in the list. Once selected, you can press
the TAB key to finish the word.
Note
Whenever you represent actual text in a program, you must enclose it in quotation marks
(""). This tells the program to interpret the text as actual text instead of as a variable name.
When you assign a Boolean variable a value of True or False, you do not enclose the word
in quotation marks, because True and False are Visual Basic keywords with special
meanings of their own.
3. Beneath the code you wrote in the previous step, type the following.
Click OK for each window as it appears. Note that the value of each variable is displayed in turn, and
then the program ends. After the program has finished, you can go back and change the values that are
assigned in the code and run the application again—you'll see that the new values are displayed.
Note
Data types are also used in other programming elements such as constants, properties, and
functions. You will learn more about the other uses of data types in a following lesson.
Most computer programs deal with numbers in some form or another. Since there are several different
ways to express numbers, Visual Basic has several numeric data types to deal with numbers more
efficiently.
The numeric data type that you will use the most is the Integer, which is used to represent a whole
number (a number without a fractional part). When choosing a data type to represent whole numbers,
you will want to use the Long data type if your variable will be storing numbers larger than
approximately two billion; otherwise an Integer is more efficient.
Not all numbers are whole numbers; for example, when you divide two whole numbers, the result is
often a whole number plus a fraction (9 divided by 2 equals 4.5). The Double data type is used to
represent numbers that have a fractional part.
Note
There are additional numeric data types such as Decimal, Short, SByte, and UInteger; these
are typically used in very large programs where memory usage or speed is an issue. For now,
the basic numeric data types are all you will need.
Most programs also deal with text, whether displaying information to the user or capturing text entered
by the user. Text is usually stored in the String data type, which can contain a series of letters,
numbers, spaces, and other characters. A String can be of any length, from a sentence or a paragraph
to a single character to nothing at all (a null string).
For a variable that will always represent just one character, there is also a Char data type. If you only
need to hold one character in a single variable, you can use the Char data type instead of a String.
In addition to text and numbers, programs sometimes need to store other types of information, such as
a true or false value, a date, or data that has a special meaning to the program.
For values that can be represented as true/false, yes/no, or on/off, Visual Basic has the Boolean data
type. A Boolean variable can hold one of two possible values: True or False.
Although you can represent dates or times as numbers, the Date data type makes it easy to calculate
dates or times, such as the number of days until your birthday or the number of minutes until lunch.
When you need to store more than one type of data in a single variable, you can use a composite data
type. Composite data types include arrays, structures, and classes. You will learn more about these in
later lessons.
6
Finally, there are some cases in which the type of data that you need to store may be different at
different times. The Object data type allows you to declare a variable and then define its data type
later. You will also learn more about the Object data type in a later lesson.
In the previous lesson, you learned how to use variables to store data in your program, and that each
variable must be of the appropriate type for the data that it will store. In this lesson, you will learn
more about the String data type, which is used to store text.
What Is a String?
A string is any series of text characters, such as letters, numbers, special characters, and spaces.
Strings can be human-readable phrases or sentences, such as "The quick brown fox jumps over the
lazy dog," or an apparently unintelligible combination, such as "@#fTWRE^3 35Gert".
String variables are created just as other variables: by first declaring the variable and assigning it a
value, as shown below.
You can use the ampersand (&) character to sequentially combine two or more strings into a new
string, as shown below.
the WideMissouri because there is no space at the end of aString or at the beginning of bString.
The two strings are simply joined together. If you want to add spaces or anything else between two
strings, you must do so with a string literal, such as " ", as shown below.
"Missouri" Dim cS t r i ng As String = "" cS t r i ng = aSt r i ng & " " & bSt r i ng
The text contained in cString now reads as Across the Wide Missouri.
Try It!
To join strings
7
2. In the New Project dialog box:
3. Click OK.
4. In the Form1.Load event procedure, declare four string variables and assign the string values, as
shown below:
dString) ' Displays "Concatenating With Spaces". MsgBox(aString & " " &
The text displayed in the message box is the result of joining the string variables that were assigned in
a previous step. In the first box, the strings are joined together without spaces. In the second, spaces
are explicitly inserted between each string.
As you learned in the previous lessons, variables are used to store different types of data for use by
your program. There is another type of variable called an array that provides a convenient way to store
several values of the same type.
For example, suppose you were writing a program for a baseball team and you wanted to store the
names of all of the players on the field. You could create nine separate string variables, one for each
player, or you could declare an array variable that looks something like the code below.
8
As with other types of values, you need to assign values to arrays. To do so, you refer to the element
number as part of the assignment, as shown below.
As with other types of values, you can declare and assign values to an array on a single line as follows.
Just as you use numbers to specify an item's position in an array, you use the element number to
specify which value you want to retrieve.
Try It!
2. In the New Project dialog box, in the Templates pane, click Windows Application.
9. Type a number between 0 and 8 in the text box and click the button. The name corresponding to
that element is displayed in a message box.
9
Tip
You should write additional code to check that the data entered is valid. For example, you can
check that the value entered is a numeric value between 0 and 8.
An expression is a segment of code that performs arithmetic and then returns a value. For example, a
simple addition expression is shown below.
5+4
The expression 5 + 4 returns the value 9 when evaluated and is made up of two parts: the operands
(5 and 4), which are the values that the operation is performed on, and the operator (+), which
specifies the operation to be performed.
For an expression to be useful, you must do something with the value that is returned. The most
common thing to do is to assign it to a variable, as shown below.
4 to it.
Arithmetic Operators
Note
You can also convert a variable from one data type to another by using the conversion
functions of Visual Basic. For more information,
To add numbers
2. In the New Project dialog box, in the Templates pane, click Windows Application.
10
3. In the Name box, type Ar i thmet i cand then click OK.
4. From the Toolbox, drag two Textbox controls onto the form.
Dim A As Double = Tex tbox1 . Tex t Dim B As Double = Tex tbox2 . Tex t MsgBox(A
The final four lines create expressions with the two variables and each of the basic arithmetic
operators, and display the results of those expressions in a message box.
Note
If you type any other character into the text boxes, an error will occur.
10. Expressions are created using the two numbers that you enter and each of the four basic
arithmetic operators (addition, subtraction, multiplication, and division). The result of each
expression is displayed in a message box.
What happens when you want to display an Integer in a TextBox control that requires a String? The
answer is that the data must be converted from one type to another. In this topic, you will explore how
to convert data from one type to another, and you will learn some techniques used for data conversion,
as well as some of its common pitfalls.
Every variable in Visual Basic can be converted to text by using a special function called CStr (which is
shorthand for Convert to String). This function, as the name implies, returns the data represented by
the variable as a String. The following procedure demonstrates a simple example of converting an
Integer to text.
Try It!
11
2. In the New Project dialog box, in the Templates pane, click Windows Application.
6. Press F5 to build and run your application. A message box that reads 54 is displayed.
Let's try something just for fun. In the Code Editor, change the line that reads
MsgBox(CSt r (an In tege r )to) read MsgBox(an In teger,) and press F5 to run. What happens? The
program behaves exactly as it did before. Visual Basic is smart enough to know that what you really
want is to convert the Integer to text to display in the message box. However, you cannot rely on this
behavior for all cases—there are many variable types that cannot be automatically converted.
Therefore, it is good practice to always use the CStr function, even if a variable would automatically be
converted to text.
In addition to converting Integer variables to text, the CStr function can be used on any numeric data
type, such as Double or Long. It can also be used to convert the Date and Boolean data types to
text. For more information on data types, see Closer Look: Data Types.
As you learned in the arithmetic lesson, sometimes the result of an arithmetic operation can't be
expressed as an Integer. Just as Visual Basic has a function for converting numbers to text, it also has
functions for converting variables from one numeric data type to another. For example, you can use the
CDbl (Convert to Double) function in an arithmetic operation to return a fractional number when
working with Integer variables. The following procedure shows how to use the CDbl function when
dividing two integers.
Try It!
1. In the Code Editor, delete the code that you entered in the previous procedure and type the
following:
2. Press F5 to build and run your application. A message box that reads 0.5 is displayed.
Visual Basic has functions for other types of numeric variables as well. For example, if you add two
variables of the type Double and want to round the result to the nearest whole number, use the CInt
12
function. Other numeric conversion functions include CByte, CDec, CLng, and CShort. For a list of all
the Visual Basic conversion functions, see Type Conversion Functions.
In the last lesson, you learned how to use arithmetic operators to create numeric expressions and return
numeric values. Another kind of operator, the comparison operators, can be used to compare numeric
values and return Boolean (True or False) values.
Comparison operators are most frequently used to compare values and make decisions based on that
comparison. Making decisions in your program will be covered in-depth in Making Your Program Choose
Between Two Possibilities: The If...Then Statement.
To compare expressions
2. In the New Project dialog box, in the Templates pane, click Windows Application.
3. In the Name box, type Compar i son and then click OK.
4. From the Toolbox, drag two Textbox controls onto the form.
13
6. Double-click the Button to open the Code Editor.
CDbl(Textbox2.Text)
The first two lines declare MsgBox(A > A
the variables B)and
MsgBox(A
B, which <willB)hold
MsgBox(A = B)
the numeric values used in this
program; they use the CDbl statement to convert the text from Textbox1 and Textbox2 into
numeric values. Finally, the last three lines create expressions to compare the two variables using three
basic comparison operators, and display the results of those expressions in three message boxes.
The first message box will display True if A (the number that you entered in the first text box) is
greater than B (the number that you entered in the second text box); otherwise it will display False.
The second message box will display True if A is less than B, and the third message box will display
True if both numbers are the same.
Try typing different numbers into the text boxes to see how the results change.
A procedure is simply a piece of code that tells the program to perform an action. Although you may not
have realized it, you have already used procedures in the previous lessons. For example, the MsgBox
function is a built-in procedure that performs the action of displaying a dialog box.
While Visual Basic has many built-in procedures for performing common actions, there will always be
cases when you want your program to perform an action that a built-in procedure can't handle. For
example, the MsgBox function cannot display a dialog box with a picture. You need to write your own
procedure to accomplish this task.
What is a Procedure?
A procedure is a self-contained block of code that can be run from other blocks of code. Generally
speaking, procedures each contain the code necessary to accomplish one task. For example, you might
have a procedure called PlaySound, which contains the code required to play a wave file. While you
could write the code to play a sound every time your program needed to make a noise, it makes more
sense to create a single procedure that you can call from anywhere in your program.
A procedure is run, or executed, by calling it in code. For example, to run the PlaySound procedure,
you simply add a line of code to your program with the name of your procedure, as shown below.
PlaySound
That's all there is to it! When the program reaches that line, it will jump to the PlaySound procedure
and execute the code contained there. The program will then jump back to the next line that follows the
call to PlaySound.
14
You can call as many procedures as you like. Procedures are run in the order that they are called. For
example, you might also have a procedure called DisplayResults; to execute it after executing the
PlaySounds procedure, call the procedures as shown below.
P laySounds
Disp layResu l t s
There are two kinds of procedures: functions and subroutines (sometimes called subs). A function
returns a value to the procedure that called it, whereas a sub simply executes code. Subs are called
when a line of code that contains the name of the sub is added to the program, as in the following
example.
DisplayResults
Functions are different, because functions not only execute code, they also return a value. For example,
imagine a function called GetDayOfWeek that returns an Integer indicating the day of the week. You
call this function by first declaring a variable in which to store the return value, and then assigning the
returned value to the variable for later use, as shown below.
Today = GetDayOfWeek
In this example, the value returned by the function is copied to the variable named Today and stored
for later use.
Writing Procedures
You write procedures by first writing a procedure declaration. A procedure declaration does several
things: states whether the procedure is a function or a sub, names the procedure, and details any
parameters the procedure might have (parameters will be discussed in detail later in this lesson). The
following is an example of a simple procedure declaration.
Declaring functions is similar, but with the added step that the return type (such as Integer, String,
etc.) must be specified. For example, a function that returned an Integer might look like this.
Try It!
To create procedures
15
1. On the File menu, choose New Project.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
5. In the Code Editor, locate the line that reads End C lass
. This is the end of the code section that
makes up your form. Immediately before this line, add the following procedure:
6. Above the function you added in the previous step, add the following Sub.
7. Finally, add a line to the Form1_Load event handler that calls the DisplayTime sub, as shown
below.
When the program starts, the Fo rm1_Load event procedure is executed. This procedure calls the
DisplayTime sub, so program execution jumps to the DisplayTime sub procedure. That sub in turn
calls the GetTime function, so program execution then jumps to the GetTime function. This function
returns a String representing the time to the DisplayTime sub procedure, which then displays that
string in a message box. After the sub is finished executing, the program continues normally and
displays the form.
At times you will need to provide additional information to your procedures. For example, in the
PlaySound procedure, you may want to play one of several different sounds. You can provide the
information on which sound to play by using parameters.
Parameters are a lot like variables. They have a type and a name, and they store information just like
variables. They can be used just like variables in a procedure. The two main differences between
parameters and variables are:
• Parameters are declared in the procedure declaration, not in individual lines of code.
• Parameters are usable only in the procedure they are declared in.
Parameters are declared in the procedure declaration in the parentheses that follow the procedure
name. The As keyword is used to declare the type, and each parameter is generally preceded by the
ByVal keyword. This keyword will be added automatically by Visual Basic if you do not add it, and it
has a fairly advanced function that is beyond the scope of this lesson to explain.
16
An example of a sub with parameters is shown below.
My.Computer.Audio.Play(SoundFile,
You Volume)
would then call the sub with the values for the End as
parameters Sub
shown below.
PlaySound("Startup.wav", 1)
You can also declare parameters for functions in exactly the same way you would for subs.
Try It!
2. In the New Project dialog box, in the Templates pane, click Windows Application.
4. From the Toolbox, drag two Textbox controls onto the form.
7. Immediately after the End Sub line of the But ton1_C l i ckevent handler, add the following
procedure:
10. Type a number value in each text box and click the button. The two numbers are added, and the
result is displayed in a message box.
Making Your Program Repeat Actions: Looping With the For...Next Loop
In this lesson, you will learn how to use the For...Next statement to repeat actions in your program,
and to count how many times these actions have been performed.
17
When you write a program, you frequently need to repeat actions. For example, suppose you are writing
a method that displays a series of numbers on screen. You will want to repeat the line of code that
displays the numbers as many times as necessary.
The For...Next loop allows you to specify a number, and then repeat code contained within that loop for
the specified number of times. The following example shows how a For...Next loop appears in code.
When the code enters the For...Next loop, it starts with i containing the first value (in this case 1). The
program then executes the lines of code between the For line and the Next line, in this case calling
the DisplayNumber method with a parameter of i (in this case also 1).
When the line Next is reached, 1 is added to i and program execution jumps back to the For line
again. This repeats until the value of i is larger than the second number in the For line, in this case 10.
When this occurs, the program continues with any code after the Next line.
Try It!
2. In the New Project dialog box, in the Templates pane, click Windows Application.
4. From the Toolbox, drag one TextBox control and one Button control onto the form.
A message box appears as many times as you indicated in the text box.
Closer Look: Using Do...While and Do...Until to Repeat Until a Condition is Met
In this lesson, you will learn how to use the Do...While and Do...Until statements to repeat code based
on certain conditions.
18
In the previous lesson, you learned how to use the For...Next statement to loop through a block of
code a specified number of times—but what if the number of times that the code needs to be repeated
is different for certain conditions? The Do...While and Do...Until statements allow you to repeat a
block of code while a certain condition is True, or until a certain condition is True.
For example, suppose you had a program to add a series of numbers, but you never wanted the sum of
the numbers to be more than 100. You could use the Do...While statement to perform the addition as
follows:
Dim sum As Integer = 0 Do While sum < 100 sum = sum + 10 Loop
In the above code, the Do Whi le line evaluates the variable sum to see if it is less than 100: If it is,
the next line of code is run; if not, then it moves to the next line of code following Loop. The Loop
keyword tells the code to go back to the DoWhile line and evaluate the new value of sum.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
4. From the Toolbox, drag one TextBox control and one Button control onto the form.
Dim sum As Integer = 0 Dim counte r As Integer = 0 Do While sum < 100 sum
= sum + C In t ( Tex tbox1 . Tex t ) counte r = counte r + 1 Loop MsgBox( "The loop
A message box appears displaying how many times the number was added to itself before reaching
100.
9. On the Debug menu, choose Stop Debugging to end the program. Keep this project open. We
Do...Until Statement
The Do...While statement repeats a loop while a condition remains True, but sometimes you might
want your code to repeat itself until a condition becomes True. You can use the Do...Until statement
as follows:
Dim sum As Integer = 0 Do Until sum >= 100 sum = sum + 10 Loop
This code is similar to the code for the Do...While statement, except that this time the code is
evaluating the sum variable to see if it is equal to or greater than 100.
19
To use a Do...Until statement
2. counte
Press F5 r2 + 1theLoop
to run MsgBox( "The loop has run " & CSt r ( counte r2 ) &
program.
A second message box appears displaying how many times the number was added to itself
before equaling 100 or greater.
Making Your Program Choose Between Two Possibilities: The If...Then Statement
In this lesson, you will learn to use the If...Then statement to run code based on conditions.
Programs need to do different things in response to different conditions. For example, you might want
your program to check what day of the week it is, and then do something different depending on the
day. The If...Then statement allows you to evaluate a condition and to then run different sections of
code based on the results of that condition.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
20
7. On the Debug menu, choose Stop Debugging to end the program. Keep this project open. You
will add to it in the next procedure, "To use the Else clause".
You may have noticed in the above example that the If...Then statement used the Or operator to
evaluate multiple conditions ("if it is Saturday Or if it is Sunday"). You can use the Or and And
operators to evaluate as many conditions as you want in a single If...Then statement.
You have seen how to use the If...Then statement to run code if a condition is true—but what if you
want to run one set of code if a condition is true, and another if it is false? In this case, you can use the
Else clause. The Else clause allows you to specify a block of code that will be run if the condition is
false. The following example demonstrates how the Else clause works.
MsgBox("Today
In this is Friday!")
example, the expression Elseif itMsgBox("It
is evaluated; isn't
is true, then the next Friday yet!")
line of code is run, End If first
and the
message box is displayed. If it is false, then the code skips to the Else clause, and the line following
Else is run, displaying the second message box.
Try It!
If My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Saturday Or
Note
You can change the day of the week by double-clicking the time on the Windows taskbar, if
you want to test the execution of both code blocks. (The taskbar is the bar that contains the
Windows Start button; by default, it is at the bottom of the desktop, and the time appears in
the right corner.)
Closer Look: Using Select Case to Decide Between Multiple Choices
In this lesson, you will learn to use the Select Case statement to run code based on multiple
conditions.
In the previous lesson, you learned how to use If...Then statements to run different blocks of code for
different conditions. While it's possible to evaluate more than two conditions in an If...Then statement
by using the ElseIf keyword, the Select Case statement provides a much better way to evaluate
multiple conditions.
The Select Case statement allows you to use as many conditions (or cases) as you need, making it
convenient to write code for situations in which there are many choices. For example, suppose your
program used a String variable to store a color choice and you needed to get the color value. The code
for the Select Case statement might look like the following:
21
Select Case Color Case "red" MsgBox("You selected red") Case "blue"
MsgBox("You
When selected
this code is run, blue")
the Select Case
Case line "green"
determines theMsgBox("You selected
value (Co lo r) of green")
the expression. Assume
that Co lo r is a String variable and that this variable is a parameter for a method that contains the
Select Case statement. The value of Color is then compared to the value for first Case statement. If
the value matches, the next line of code is run, and then the code skips to the End Select line; if the
value doesn't match, then the next Case line is evaluated.
The Case statement can take many different forms—in the example above, it is a String. However, it
can be any data type or expression.
Case 1 To 10
In this example, any number between 1 and 10 would result in a match.
You can also evaluate multiple values in a single Case statement by separating them with commas, as
follows:
You can also use comparison operators and the Is keyword to evaluate values, as follows.
Case Is > 9
In this example, any number greater than 9 would result in a match.
Case Else
The above example works when you know all possible conditions, but what happens if there is a
condition you didn't account for? For example, if the value of Color was yellow, the code would simply
evaluate the three cases without finding a match, and no message box would display.
The Case Else statement can be used to run code when no match is found, as in the following
example.
Select Case Co lo r Case "red" MsgBox( "You selected red") Case "blue"
MsgBox( "You selected blue") Case "green" MsgBox( "You selected green")
In the above code, if the value of Color is yellow, the code compares it with the first three Case lines
Case Else MsgBox( "Please choose red, blue, or green") End Select
without finding a match. When the Case Else line is reached, the next line of code is run before
moving to End Select.
2. In the New Project dialog box, in the Templates pane, click Windows Application.
22
4. From the Toolbox, drag one TextBox control and one Button control onto the form.
A message box appears displaying the message for the Case statement matching the number that you
entered.
In the previous lesson, you learned how to use If...Then statements to run different blocks of code for
different conditions. While it's possible to evaluate more than two conditions in an If...Then statement
by using the ElseIf keyword, the Select Case statement provides a much better way to evaluate
multiple conditions.
The Select Case statement allows you to use as many conditions (or cases) as you need, making it
convenient to write code for situations in which there are many choices. For example, suppose your
program used a String variable to store a color choice and you needed to get the color value. The code
for the Select Case statement might look like the following:
Select Case Color Case "red" MsgBox("You selected red") Case "blue"
MsgBox("You
When selected
this code is blue")
run, the Select Case
Case "green" MsgBox("You
line determines the value (Co loselected green")Assume
r) of the expression. End
that Co lo r is a String variable and that this variable is a parameter for a method that contains the
Select Case statement. The value of Color is then compared to the value for first Case statement. If
the value matches, the next line of code is run, and then the code skips to the End Select line; if the
value doesn't match, then the next Case line is evaluated.
The Case statement can take many different forms—in the example above, it is a String. However, it
can be any data type or expression.
Case 1 To 10
In this example, any number between 1 and 10 would result in a match.
You can also evaluate multiple values in a single Case statement by separating them with commas, as
follows:
23
You can also use comparison operators and the Is keyword to evaluate values, as follows.
Case Is > 9
In this example, any number greater than 9 would result in a match.
Case Else
The above example works when you know all possible conditions, but what happens if there is a
condition you didn't account for? For example, if the value of Co lo r was ye l l ow
, the code would simply
evaluate the three cases without finding a match, and no message box would display.
The Case Else statement can be used to run code when no match is found, as in the following
example.
Select Case Co lo r Case "red" MsgBox( "You selected red") Case "blue"
MsgBox( "You selected blue") Case "green" MsgBox( "You selected green")
2. In the New Project dialog box, in the Templates pane, click Windows Application.
4. From the Toolbox, drag one TextBox control and one Button control onto the form.
A message box appears displaying the message for the Case statement matching the
number that you entered.
24