You are on page 1of 24

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

Your First Program

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.

More About Visual Basic

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

The Basics: How Programming Works


Before you jump in and start learning the Visual Basic programming language, it may help you to
understand what a programming language is and how it works, including some programming
terminology. The best place to start is with the basics.

How Programming Works

On its own, a computer isn't very smart.

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.

What is A Programming Language?

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.

Inside the Visual Basic Language

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:

Ca r.Speed .Max imum = 55

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!

Representing Words, Numbers, and Values with Variables


Variables are an important concept in computer programming. A variable is a letter or name that can
store a value. When you create computer programs, you can use variables to store numbers, such as
the height of a building, or words, such as a person's name. Simply put, you can use variables to
represent any kind of information your program needs.

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.

Storing Information in Variables

There are three steps to using a variable:

1. Declare the variable. Tell the program the name and kind of variable you want to use.

2. Assign the variable. Give the variable a value to hold.

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.

Dim aNumber As I n teger

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.

Here are more examples of how to declare variables.

Dim aDouble As Doub le Dim aName As St r i ngDim YesOrNoAs Boo lean

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.

Declaring and Assigning Variables with a Default Value

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.

Dim aDouble As Doub le = 0 Dim aName As St r i ng = "default string"


Dim YesOrNo As
Boo lean = True

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.

To create the project

1. If it is not already open, open Visual Basic from the Windows Start menu.

2. On the File menu, click New Project.

4
3. In the New Project dialog box on the Templates pane, click Windows Application.

4. In the Name box, type Var i ab les


and then click OK.

Visual Basic will create the files for your program and open the Form Designer.

Next, you'll create the variables.

To create variables and display their values

1. Double-click the form.

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.

2. In the Fo rm1_Load procedure, type the following code.

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.

MsgBox(anInteger) MsgBox(aSingle) MsgBox(aString) MsgBox(aBoolean)


End
The first four lines of code tell the program to display each value that you assigned in the previous step
in a new window, using the MsgBox function. The final line tells the program to end after executing this
procedure—it uses the End statement.

4. Press F5 to run your program.

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.

Closer Look: Data Types


5
Data types in Visual Basic determine what kind of values or data can be stored in a variable, as well as
how that data is stored. Why are there different data types? Think of it this way: if you had three
variables, two of which held numbers while the third held a name, you could perform arithmetic using
the first two, but you can't perform arithmetic on the name. Assigning a data type to a variable makes it
easier to determine how the variable can—or can't—be used.

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.

Data Types for Numbers

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.

Data Types for Text

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.

Other Data Types

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.

Words and Text: Using String Variables to Organize Words


In this lesson, you will learn how to use the String data type to represent words and text.

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.

Dim aString As String = "This is a string"


When assigning actual text (also called a string literal) to a String variable, the text must be enclosed
in quotation marks (" "). You can also use the = character to assign one String variable to another
String variable, as shown in this example.

Dim aSt r i ng As String = "This is a string" Dim bSt r i ng As String = ""


The previous code sets the value of bSt r i ngto the same value as aSt r i ng(This is a string).

You can use the ampersand (&) character to sequentially combine two or more strings into a new
string, as shown below.

Dim aSt r i ng As String = "Across the Wide" Dim bSt r i ng As String =

"Missouri" Dim cS t r i ng As String = "" cS t r i ng = aSt r i ng & bSt r i ng


The previous example declares three String variables and respectively assigns "Across the Wide" and
"Missouri" to the first two, and then assigns the combined values of the first two to the third variable.
What do you think the value of cString is? You might be surprised to learn that the value is Across

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.

Dim aSt r i ng As String = "Across the Wide" Dim bSt r i ng As String =

"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

1. On the File menu, click New Project.

7
2. In the New Project dialog box:

1. In the Templates pane, click Windows Application.

2. In the Name box, type Concatenation.

3. Click OK.

A new Windows Forms project opens.

3. Double-click the form to open the Code Editor.

4. In the Form1.Load event procedure, declare four string variables and assign the string values, as

shown below:

Dim aString As String = "Concatenating" Dim bString As String = "Without"

Dim cString As String = "With" Dim dString As String = "Spaces"


5. Add the following code to concatenate the strings and display the results:

' Displays "ConcatenatingWithoutSpaces". MsgBox(aString & bString &

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.

Arrays: Variables That Represent More Than One Value


In this lesson, you will learn how to use arrays to store groups of values.

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.

Dim players() As String


You declare an array variable by putting parentheses after the variable name. If you know how many
values you need to store, you can also specify the size of the array in the declaration as follows.

Dim players(9) As String


The size of the array is 9 because a baseball team has 9 players. An array is made up of a number of
values, or elements, starting with element 0 and ending with one less than the number specified in the
declaration. In this case, the array contains the elements 0 through 8, for a total of nine elements.
When you want to refer to one of the players on the team, you just subtract 1. For example, to
reference the first player, you reference element 0, to reference the ninth player, you reference element
8.

Assigning Values to Arrays

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.

players(0) = "John" players(3) = "Bart"


In the above code, the value J ohn is assigned to the first element of the array (element 0) and the
value Bre t tis assigned to the fourth element (element 3). The elements of the array don't have to be
assigned in order, and any unassigned element will have a default value—in this case, an empty string.

As with other types of values, you can declare and assign values to an array on a single line as follows.

Dim p laye rs ( ) As Integer = {1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9}


In this case, curly brackets indicate a list of values. The values are assigned to elements in the order
listed. Notice that size of the array isn't specified—it is determined by the number of items that you list.

Retrieving Values from Arrays

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.

Dim AtBat As String AtBat = p laye rs (3 )


The above code retrieves the fourth element of the array and assigns it to the string variable AtBat.

Try It!

To store values in an array

1. On the File menu, choose New Project.

2. In the New Project dialog box, in the Templates pane, click Windows Application.

3. In the Name box, type MyFi r s tA r ray


and then click OK.

A new Windows Forms project opens.

4. From the Toolbox, drag a Textbox control onto the form.

5. From the Toolbox, drag a Button control onto the form.

6. Double-click the Button to open the Code Editor.

7. In the Button1_Click event procedure, add the following code:

Dim p laye rs ( ) As String = {"Dan", "Fred", "Bart", "Carlos", _ "Ty",

"Juan" , , , "Pedro"} Dim i As Integer = C In t ( Tex tbox1 . Tex t )


Notice that "Jay"
the above"Sam"
code uses the CInt function to convert the String value (Tex tBox1 . Tex) tto an
Integer (i). You can learn more about conversions in Closer Look: Converting from One Variable Type
to Another.

8. Press F5 to run the program.

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.

Arithmetic: Creating Expressions With Variables And Operators


In this lesson, you will learn how to create expressions to perform arithmetic and then return values.

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.

Using Values Returned by Expressions

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.

Dim an In tege r As Integer = 5 + 4


This example declares a new Integer variable called anInteger and assigns the value returned by 5 +

4 to it.

Arithmetic Operators

A common use for expressions is to perform arithmetic on variables: addition, subtraction,


multiplication, or division. The following table describes the operators commonly used for arithmetic.

Operator Description Example


+ (addition) Returns the sum of two operands 5+4
- (subtraction) Returns the difference of two operands 5-4
* (multiplication) Returns the product of two operands 5*4
/ (division) Returns the quotient of two operands 5/4
The kind of variable that you use when performing arithmetic can affect the result. Dividing two
numbers often results in a return value that is not a whole number. For example, when you divide 3 by
2, the result is 1.5. If you assigned the return value of that expression to an Integer variable, it would
be rounded to the nearest whole number, 2. When performing division, you should use a Double
variable to store the return value.

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

1. On the File menu, choose New Project.

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.

A new Windows Forms project opens.

4. From the Toolbox, drag two Textbox controls onto the form.

5. From the Toolbox, drag a Button control onto the form.

6. Double-click the Button to open the Code Editor.

7. In the Button1_Click event procedure, type the following code.

Dim A As Double = Tex tbox1 . Tex t Dim B As Double = Tex tbox2 . Tex t MsgBox(A

+ B) MsgBox(A - B) MsgBox(A * B) MsgBox(A / B)


The first two lines declare the variables A and B, which will hold the numeric values used in this
program, and assign the values of the two TextBox controls (their text) to the variables A and B.

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.

8. Press F5 to run the application.

9. Type a number in each of the text boxes and click Button1.

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.

Closer Look: Converting from One Variable Type to Another


As you have seen, variables come in different types. The type determines what kind of data a variable
can hold. An Integer variable can hold only numeric data without decimal points. A String variable can
hold only text.

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.

Converting Variables to Text

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!

To convert a variable to text

1. On the File menu, click New Project.

11
2. In the New Project dialog box, in the Templates pane, click Windows Application.

3. In the Name box, type Convers i onand then click OK.

A new Windows Forms project opens.

4. Double-click the form to open the Code Editor.

5. In the Form1_Load event handler, type the following code.

Dim an In tege r As Integer = 54 MsgBox(CSt r (an In tege r ) )


This code declares an Integer variable called an In teger
, assigns it a value of 54, and then converts
that value to text and displays it in a message box by calling the CStr function.

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.

Converting Between Numeric 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!

To convert numeric data types

1. In the Code Editor, delete the code that you entered in the previous procedure and type the
following:

Dim A As Integer = 1 Dim B As Integer = 2 MsgBox(CDb l (A / B) )


This code declares two Integer variables (A and B), assigns them values of 1 and 2, and then
converts the result of the division operation (A / B) using the CDbl function and displays it in a
message box.

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.

Comparisons: Using Expressions to Compare Values


In this lesson, you will learn how to use comparison operators to create expressions that compare
values.

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.

The following table summarizes the comparison operators:

Operator Description Examples


5 = 4 (false)
Returns True if the number on the left-hand side is
= (equals) 4 = 5 (false)
equal to the number on the right-hand side.
4 = 4 (true)
5 <> 4 (true)
Returns True if the number on the left is not equal to
<> (not equal to) 4 <> 5 (true)
the number on the right.
4 <> 4 (false)
5 > 4 (true)
Returns True if the number on the left is greater than
> (greater than) 4 > 5 (false)
the number on the right.
4 > 4 (false)
5 < 4 (false)
Returns True if the number on the left is less than the
< (less than) 4 < 5 (true)
number on the right.
4 < 4 (false)
5 >= 4 (true)
>= (greater than or Returns True if the number on the left is greater than or
4 >= 5 (false)
equal to) equal to the number on the right.
4 >= 4 (true)
5 <= 4 (false)
<= (less than or equal Returns True if the number on the left is less than or
4 <= 5 (true)
to) equal to the number on the right.
4 <= 4 (true)
Try It!

To compare expressions

1. On the File menu, click New Project.

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.

A new Windows Forms project opens.

4. From the Toolbox, drag two Textbox controls onto the form.

5. From the Toolbox, drag a Button control onto the form.

13
6. Double-click the Button to open the Code Editor.

7. In the Button1_Click event handler, type the following code:

Dim A As Double = CDbl(Textbox1.Text) Dim B As Double =

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.

8. Press F5 to run the application.

9. Type a number in each of the text boxes and click Button1.

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.

Making Your Computer Do Something: Writing Your First Procedure


In this lesson, you will learn how to create a procedure, a self-contained block of code that can be run
from other blocks of code, and then how to create parameters for your procedures.

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

Functions and Subs

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.

Dim Today As Integer

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.

Sub MyFi r s tSub( ) End Sub


The Sub keyword tells the program that this procedure is a sub and will not return a value. The name of
the sub (MyFi r s tSub
) comes next, and the empty parentheses indicate that there are no parameters
for this procedure. Finally, the End Sub keyword indicates the end of the subroutine. All code that is to
be executed by this sub goes between these two lines.

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.

Function MyFi r s t Func t i on ( ) As Integer End Function


The As I n tegerkeywords indicate that this function will return an Integer value. To return a value
from a function, use the Return keyword, as shown in the following example.

Function GetTheNumberOne( ) As Integer Return 1 End Function


This procedure will return the number 1.

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.

3. In the Name box, type MyFi r s tP rocedure


and then click OK.

A new Windows Forms project opens.

4. Double-click the form to open the Code Editor.

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:

Function GetT ime( ) As String Return CSt r (Now) End Function


This function uses the built-in Now procedure to get the current time, then uses the CStr function to
convert the value returned by Now into a human-readable String. Finally, that String value is
returned as the result of the function.

6. Above the function you added in the previous step, add the following Sub.

Sub Disp layT ime( ) MsgBox(GetT ime) End Sub


This sub calls the function GetT ime and displays the result returned by it in a message box.

7. Finally, add a line to the Form1_Load event handler that calls the DisplayTime sub, as shown

below.

Disp layT ime( )


8. Press F5 to run the program.

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.

Parameters in Functions and Subs

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.

Sub PlaySound(ByVal SoundFile As String, ByVal Volume As Integer)

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!

To create a function with parameters

1. On the File menu, choose New Project.

2. In the New Project dialog box, in the Templates pane, click Windows Application.

3. In the Name box, type paramete rs and then click OK.

A new Windows Forms project opens.

4. From the Toolbox, drag two Textbox controls onto the form.

5. From the Toolbox, drag a Button control onto the form.

6. Double-click the Button to open the Code Editor.

7. Immediately after the End Sub line of the But ton1_C l i ckevent handler, add the following

procedure:

Function AddTwoNumbers ( ByVal N1 As Integer, ByVal N2 As Integer) _ As

Integer Return N1 + N2 End Function


8. In the But ton1_C l i ck
procedure, add the following code:

Dim aNumber As Integer = C In t ( Tex tbox1 . Tex t ) Dim bNumber As Integer =

C In t ( Tex tbox2 . Tex t ) MsgBox(AddTwoNumbers (aNumber , bNumber ) )


This code declares two integers and converts the text in the two text boxes to integer values. It then
passes those values to the AddTwoNumbers function and displays the value returned in a message
box.

9. Press F5 to run the program.

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.

Dim i As Integer = 0 For i = 1 To 10 DisplayNumber(i) Next


The For...Next loop begins with a counter variable, i. This is a variable that the loop uses to count the
number of times it has executed. The next line ( For i = 1 to ) 10
tells the program how many times to
repeat the loop and the values i is going to have.

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!

To use the For...Next statement

1. On the File menu, choose New Project.

2. In the New Project dialog box, in the Templates pane, click Windows Application.

3. In the Name box, type ForNext and then click OK.

A new Windows Forms project opens.

4. From the Toolbox, drag one TextBox control and one Button control onto the form.

5. Double-click the Button to open the Code Editor

6. In the Button1_Click event handler, type the following code:

Dim i As Integer = 0 Dim NumberOfRepet i t i ons As Integer =

C In t ( Tex tbox1 . Tex t ) For i = 1 To NumberOfRepet i t i ons

7. Press F5 to run the program.


MsgBox( "This line has been repeated " & i & " times") Next
8. In the text box, type a number and click the button.

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.

To use a Do...While statement

1. On the File menu, choose New Project.

2. In the New Project dialog box, in the Templates pane, click Windows Application.

3. In the Name box, type DoWhile and then click OK.

A new Windows Forms project opens.

4. From the Toolbox, drag one TextBox control and one Button control onto the form.

5. Double-click the Button to open the Code Editor.

6. In the Button1_Click event handler, type the following code:

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

7. Press F5 to run the program.


has run " & CSt r ( counte r ) & " times!")
8. In the text box, type a number and click the button.

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

are about to add to it.

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

1. Add the following code beneath the MsgBox line.

Dim sum2 As Integer = 0 Dim counte r2 As Integer = 0 Do Until

sum2 >= 100 sum2 = sum2 + C In t ( Tex tbox1 . Tex t ) counte r2 =

2. counte
Press F5 r2 + 1theLoop
to run MsgBox( "The loop has run " & CSt r ( counte r2 ) &
program.

3. In the text box, type a number and click the button.

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.

The following example demonstrates how the If...Then statement works.

If My.Compute r .C lock . Loca lT ime .DayOfWeek = DayOfWeek .Monday Then

MsgBox( "Today is Monday!") End If


When this code is run, the condition (the part between If and Then) is evaluated. If the condition is
true, the next line of code is run and a message box is displayed; if it is false, the code skips to the
End If line. In other words, the code states "If today is Monday, then display the message."

To use the If...Then statement

1. On the File menu, choose New Project.

2. In the New Project dialog box, in the Templates pane, click Windows Application.

3. In the Name box, type I f Thenand then click OK.

A new Windows Forms project opens.

4. Double-click the form to open the Code Editor.

5. In the Form1_Load event handler, type the following code.

If My.Compute r .C lock . Loca lT ime .DayOfWeek = DayOfWeek .Sa tu rday Or

_ My.Compute r .C lock . Loca lT ime .DayOfWeek = DayOfWeek .Sunday Then

6. Press F5 to run your program.


MsgBox( "Happy Weekend!") End If
If today is Saturday or Sunday, a message box appears telling you Happy Weekend! Otherwise, no
message box appears.

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.

The Else Clause

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.

If My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Friday Then

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!

To use the Else clause

1. Change the code in the If...Then statement to the following.

If My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Saturday Or

_ My.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Sunday Then

MsgBox("Happy Weekend!") Else MsgBox("Happy Weekday! Don't work


2. Press F5 to run your program. Your program will now display a message box stating whether it is a
weekend or a weekday, with appropriate content.

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.

You can evaluate a range of numbers by using the To keyword, as follows:

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:

Case "red", "white", "blue"


In this example, any of the three values would result in a match.

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.

To use the Select Case statement

1. On the File menu, choose New Project.

2. In the New Project dialog box, in the Templates pane, click Windows Application.

3. In the Name box, type SelectCase and then click OK.

A new Windows Forms project opens.

22
4. From the Toolbox, drag one TextBox control and one Button control onto the form.

5. Double-click the button to open the Code Editor.

6. In the Button1_Click event handler, type the following code.

Dim Number As Integer = CInt(Textbox1.Text) Select Case Number Case 1

MsgBox("Less than 2") Case 2 To 5 MsgBox("Between 2 and 5") Case 6, 7, 8

MsgBox("Between 6 and 8") Case 9 To 10 MsgBox("Greater than 8") Case Else


7. Press F5 to run the program.

8. In the text box, type a number and click the button.

A message box appears displaying the message for the Case statement matching the number that you
entered.

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:

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.

You can evaluate a range of numbers by using the To keyword, as follows:

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:

Case "red", "white", "blue"


In this example, any of the three values would result in a match.

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")

In the above code, if the value of Co lo r is ye l l ow


, 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.

To use the Select Case statement

1. On the File menu, choose New Project.

2. In the New Project dialog box, in the Templates pane, click Windows Application.

3. In the Name box, type Se lec tCaseand then click OK.

A new Windows Forms project opens.

4. From the Toolbox, drag one TextBox control and one Button control onto the form.

5. Double-click the button to open the Code Editor.

6. In the Button1_Click event handler, type the following code.

Dim Number As Integer = C In t ( Tex tbox1 . Tex t ) Select Case Number

Case 1 MsgBox( "Less than 2") Case 2 To 5 MsgBox( "Between 2 and

5") Case 6 , 7 , 8 MsgBox( "Between 6 and 8") Case 9 To 10


7. Press F5 to run the program.

8. In the text box, type a number and click the button.

A message box appears displaying the message for the Case statement matching the
number that you entered.

24

You might also like