An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic |...

34
An Introduction to Programming in Visual Basic | Page 1 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. This includes 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 small 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 difficult task—that's where programming languages come in. What Is a Programming Language? People express themselves using a language that has many words. Computers use a simple language that consists 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 by 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. 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 have to understand what the computer is doing or how it does it. You just have to understand how the Visual Basic programming language works. Inside the Visual Basic Language The language you write and speak has structure: for example, a book has chapters with paragraphs that contain sentences consisting of words. Programs written in Visual Basic also have a structure: modules are like chapters, procedures are like paragraphs, and lines of code are like sentences. When you speak or write, you use different categories of words, such as nouns or verbs. Each category is used according to a defined set of rules. In many ways, Visual Basic is much like the language that you use every day. Visual Basic also has rules that define how categories of words, known as programming elements, are used to write programs. Programming elements in Visual Basic include statements, declarations, methods, operators, and keywords. As you complete the following sections, 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: Car.Speed.Maximum = 55

Transcript of An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic |...

Page 1: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 1

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. This includes 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 small 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 difficult task—that's where programming languages come in.

What Is a Programming Language?

People express themselves using a language that has many words. Computers use a simple language that consists 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 by 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.

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 have to understand what the computer is doing or how it does it. You just have to understand how the Visual Basic programming language works.

Inside the Visual Basic Language

The language you write and speak has structure: for example, a book has chapters with paragraphs that contain sentences consisting of words. Programs written in Visual Basic also have a structure: modules are like chapters, procedures are like paragraphs, and lines of code are like sentences.

When you speak or write, you use different categories of words, such as nouns or verbs. Each category is used according to a defined set of rules. In many ways, Visual Basic is much like the language that you use every day. Visual Basic also has rules that define how categories of words, known as programming elements, are used to write programs.

Programming elements in Visual Basic include statements, declarations, methods, operators, and keywords. As you complete the following sections, 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:

Car.Speed.Maximum = 55

Page 2: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 2

Data Types

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. [dmc maybe allude to the ambiguity of the term ‘variable’ wrt MR vs programming languages]

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

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.[dmc I think that Long and Integer are in fact identical]

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.

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. [dmc is Char in VB.Net? I’ve never used it – certainly not in VBS]

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.

Page 3: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 3

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.

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.

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 pieces of candy you have in a jar on your desk. Because candy is meant to be eaten, the number of pieces of candy in the jar is likely to change over time. Rather than rewriting your program every time that you get a sugar craving, you can represent the number of pieces of candy 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. 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 name it and what data type to assign to it. You can name the variable anything that you want, as long as the name starts with a letter or an underscore. When you use a name that describes what the variable is holding, your code is easier to read. For example, a variable that tracks the number of pieces of candy in a jar could be named totalCandy.

You declare a variable using the Dim and As keywords, as shown here.

Dim aNumber As Integer

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 Double

Page 4: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 4

Dim aName As String

Dim YesOrNo As Boolean

Note

You can create a local variable without declaring the type of the variable by using local type inference. When

you use local type inference, the type of the variable is determined by the value that is assigned to it.

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 earlier, you can declare a variable on one line of code, and then later assign the value on another line. This can cause 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 Double = 0

Dim aName As String = "default string"

Dim YesOrNo As Boolean = 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.

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. 3. In the New Project dialog box on the Templates pane, click Windows Forms Application. 4. In the Name box, type Variables and then click OK.

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

Next, you'll create the variables.

Page 5: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 5

To create variables and display their values

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

The Code Editor opens to a section of code called Form1_Load. This section of code is an event handler, which is also referred to as a procedure. The code that you write in this procedure is the instructions that will be performed when the form is first loaded into memory.

2. In the Form1_Load procedure, type the following code.

Dim anInteger As Integer = 42

Dim aSingle As Single = 39.345677653

Dim aString As String = "I like candy"

Dim aBoolean As Boolean = True

This code declares four variables and assigns their default values. The four variables are an Integer, a Single, a String, and a Boolean.

Tip

As you typed the code, you may have noticed that after you typed As, a list of words appeared underneath

the cursor. This feature is called IntelliSense. It enables you to just type the first few letters of a word until

the word is selected in the list. Once the word is 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)

This code tells the program to display each value that you assigned in the previous step in a new window, using the MsgBox function.

4. Press F5 to run your program.

Click OK for each message box as it appears. Note that the value of each variable is displayed in turn. You can close the form by clicking the x in the upper-right corner of the form. After the program has finished, you can go back and change the values that are assigned in the code—you'll see that the new

Page 6: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 6

values are displayed the next time that you run the program.[dmc should show the completed code amnd a screen shot of VBExpress form]

Words and Text: Using String Variables to Organize Words

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

The previous section showed how to use variables to store data in a program, and that each variable must be of the appropriate type for the data that it will store. In this section, 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 here.

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 aString As String = "This is a string"

Dim bString As String = ""

bString = aString

The previous code sets the value of bString to the same value as aString (This is a string). [dmc should quote this?] You can use the ampersand (&)character to sequentially combine two or more strings into a new string, as shown here. This is also known as concatenation. Dim aString As String = "using string"

Dim bString As String = "variables"

Dim cString As String = ""

cString = aString & bString

The previous example declares three String variables and respectively assigns "using string" and "variables" 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 [dmc indent so that the space is obvious] using stringvariables because there is no space at the end of aString or at the start of bString. The two strings are just 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 here.

Dim aString As String = "using string"

Dim bString As String = "variables"

Dim cString As String = ""

cString = aString & " " & bString

Page 7: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 7

The text that is contained in cString now reads as using string variables.

[dmc or could save a variable by “using string “ and “variables “

Try It!

Try It!

To join strings

1. On the File menu, click New Project. 2. In the New Project dialog box:

a. In the Templates pane, click Windows Application. b. In the Name box, type Concatenation. c. 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 here:

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 & " " & cString & " " & dString)

6. Press F5 to run your program.

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.

Page 8: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 8

Arrays: Variables That Represent More Than One Value

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

As explained in previous sections, 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 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 that is shown here.

Dim players() As String

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

Dim players(8) As String

The size of the array is 9 because a baseball team has 9 players. An array consists of a number of values, or elements, which are referenced by unique index values, starting with 0. The index value of the final element is always one less than the size of the array. 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

As with other types of values, you have to assign values to arrays. To do so, you refer to the element number as part of the assignment, as shown here.

players(0) = "John"

players(3) = "Bart"

In the previous code, the value John is assigned to the first element of the array (element 0) and the value Bart is 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 players() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9}

In this case, braces 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. [dmc better to continue with the string type for players array?]

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 the value that you want to retrieve.

Dim AtBat As String

AtBat = players(3) The above code retrieves the fourth element of the array and assigns it to the string variable AtBat.

Page 9: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 9

Try It!

To store values in an array 1. On the File menu, click New Project. 2. In the New Project dialog box, in the Templates pane, click Windows Forms Application. 3. In the Name box, type MyFirstArray 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 players() As String = {"Dan", "Fred", "Bart", "Carlos", _

"Ty", "Juan", "Jay", "Sam", "Mick"}

Dim i As Integer = CInt(Textbox1.Text)

MsgBox(players(i) & " is on first base.")

Notice that the previous code uses the CInt function to convert the String value (TextBox1.Text) to an Integer (i).

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.

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 section, 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 here: 5 + 4

The expression 5 + 4 returns the value 9 when evaluated and consists 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 here:

Dim anInteger As Integer = 5 + 4

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

This is an underscore, used to continue a line of code over

more than one line

Page 10: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 10

Arithmetic Operators

A common use for expressions is to perform arithmetic on variables: addition, subtraction, multiplication, or division. The following table describes the operators frequently 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 you perform 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.

Try It!

To add numbers

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 Arithmetic 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. In the Button1_Click event procedure, type the following code.

Dim A As Double = Textbox1.Text

Dim B As Double = Textbox2.Text

MsgBox(A + B)

MsgBox(A - B)

MsgBox(A * B)

MsgBox(A / B)

The first two lines declare the variables A and B. A and B 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.

Page 11: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 11

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 text box and click Button1.

Note

If you type any other character into the text boxes, an error will occur.

10. Expressions are created by 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.

Comparisons: Using Expressions to Compare Values

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

The last section showed 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. The following table summarizes the comparison operators:

Operator Description Examples

= (equals) Returns True if the number on the left-hand side is equal to the number on the

right-hand side.

5 = 4 (false)

4 = 5 (false)

4 = 4 (true)

<> (not equal to) Returns True if the number on the left is not equal to the number on the right. 5 <> 4

(true)

4 <> 5

(true)

4 <> 4

(false)

> (greater than) Returns True if the number on the left is greater than the number on the right. 5 > 4 (true)

4 > 5 (false)

4 > 4 (false)

Page 12: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 12

< (less than) Returns True if the number on the left is less than the number on the right. 5 < 4 (false)

4 < 5 (true)

4 < 4 (false)

>= (greater than or equal

to)

Returns True if the number on the left is greater than or equal to the number on

the right.

5 >= 4

(true)

4 >= 5

(false)

4 >= 4

(true)

<= (less than or equal to) Returns True if the number on the left is less than or equal to the number on the

right.

5 <= 4

(false)

4 <= 5

(true)

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 Comparison 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. In the Button1_Click event handler, type the following code:

Dim A As Double = CDbl(Textbox1.Text)

Dim B As Double = CDbl(Textbox2.Text)

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

Page 13: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 13

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 a Computer Do Something: Writing Your First Procedure

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

A procedure is just a block 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 sections. 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 that has a picture. You have to write your own procedure to accomplish that 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 that is required to accomplish one task. For example, you might have a procedure called PlaySound, which contains the code that is required to play a wave file. While you could write the same code to play a sound every time your program had 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 just add a line of code that has the name of your procedure, as shown here.

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 that is contained there. The program will then jump back to the next line that follows the call to PlaySound. [dmc note ambiguity with use of trailing () as sub or array]

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

PlaySounds()

DisplayResults()

Page 14: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 14

Functions and Subs

There are two kinds of procedures: functions and subroutines (sometimes referred to as subs). A function returns a value to the procedure that called it, whereas a sub just 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 here.

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. It states whether the procedure is a function or a sub, it names the procedure, and it details any parameters the procedure might have. (Parameters will be discussed in detail later in this section.) The following is an example of a simple procedure declaration.

Sub MyFirstSub()

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 (MyFirstSub) 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 MyFirstFunction() As Integer

End Function

The As Integer keywords 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!

Page 15: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 15

Try It!

To create procedures

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 MyFirstProcedure 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 Class. This is the end of the code section that

makes up the form. Immediately before this line, add the following procedure:

Function GetTime() As String

Return CStr(Now)

End Function

This function uses the built-in Now procedure to receive the current time, and 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 DisplayTime()

MsgBox(GetTime)

End Sub

This sub calls the function GetTime 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 here.

DisplayTime()

8. Press F5 to run the program.

When the program starts, the Form1_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 have 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 about which sound to play by using parameters.

Parameters are much 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 as follows:

Page 16: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 16

• 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 section to explain.

An example of a sub with parameters is shown here.

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

My.Computer.Audio.Play(SoundFile, Volume)

End Sub

You would then call the sub with the values for the parameters as shown here.

PlaySound("Startup.wav", 1)

You can also declare parameters for functions in the same way you would for subs.

Try It!

To create a function that has parameters

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 parameters 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 Button1_Click event 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 Button1_Click procedure, add the following code:

Dim aNumber As Integer = CInt(Textbox1.Text)

Dim bNumber As Integer = CInt(Textbox2.Text)

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.

Page 17: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 17

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 a Program Repeat Actions: Looping with the For...Next Loop

In this section, 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.

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 NumberOfRepetitions As Integer = CInt(Textbox1.Text) For i = 1 To NumberOfRepetitions MsgBox("This line has been repeated " & i & " times") Next

7. Press F5 to run the program.

Page 18: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 18

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.

Using Do...While and Do...Until to Repeat Until a Condition Is Met

In this section, you will learn how to use the Do...While and Do...Until statements to repeat code based on certain conditions.

In the previous section, 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 has to be repeated is different for certain conditions? The Do...While and Do...Until statements enable 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 this code, the Do While line evaluates the variable sum to see whether it is less than 100: If it is, the next line of code is run; if not, 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.

Try It!

To use a Do...While statement

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 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 counter As Integer = 0

Do While sum < 100

sum = sum + CInt(Textbox1.Text)

counter = counter + 1

Loop

MsgBox("The loop has run " & CStr(counter) & " times!")

Page 19: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 19

7. Press F5 to run the program. 8. In the text box, type a number and click the button.

A message box appears that displays how many times the number was added to itself before reaching 100.

9. On the Debug menu, click 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 resembles the code for the Do...While statement, except that this time the code is evaluating the sum variable to see whether it is equal to or greater than 100.

Try It!

This procedure starts where "To use a Do...While statement" ended. If you have not completed "To use a Do...While statement," you must do so before continuing.

To use a Do...Until statement

1. Add the following code underneath the MsgBox line.

Dim sum2 As Integer = 0

Dim counter2 As Integer = 0

Do Until sum2 >= 100

sum2 = sum2 + CInt(Textbox1.Text)

counter2 = counter2 + 1

Loop

MsgBox("The loop has run " & CStr(counter2) & " times!")

2. Press F5 to run the program. 3. In the text box, type a number and click the button.

A second message box appears that displays how many times the number was added to itself before equalling 100 or greater.

Making a Program Choose Between Two Possibilities: The If...Then Statement

Page 20: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 20

In this section, 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.Computer.Clock.LocalTime.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."

Try It!

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 IfThen and 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.Computer.Clock.LocalTime.DayOfWeek = DayOfWeek.Saturday OrElse

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

MsgBox("Happy Weekend!")

End If

6. Press F5 to run your program.

If today is Saturday or Sunday, a message box appears telling you Happy Weekend! Otherwise, no message box appears.

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.

Page 21: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 21

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

MsgBox("Today is Friday!")

Else

MsgBox("It isn't Friday yet!")

End If

In this example, the expression is evaluated; if it is true, then the next line of code is run, and the first 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!

This procedure begins where "To use the If...Then statement" ended. If you have not completed "To use the If...Then statement," you must do so before continuing.

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 OrElse

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

MsgBox("Happy Weekend!")

Else

MsgBox("Happy Weekday! Don't work too hard!")

End If

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

Page 22: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 22

What To Do When Something Goes Wrong: Handling Errors

In this section, you will learn how to create basic error-handling code for your programs.

Even the best designed programs sometimes encounter errors. Some errors are defects in your code that can be found and corrected. Other errors are a natural consequence of the program; for example, your program might attempt to open a file that is already in use. In cases like this, errors can be predicted but not prevented. As a programmer, it is your job to predict these errors and help your program deal with them.

Run-Time Errors

An error that occurs while a program is running is called a run-time error. A run-time error occurs when a program tries to do something it wasn't designed to do. For example, if your program attempts to perform an invalid operation, such as converting a non-numeric string to a numeric value, a run-time error occurs.

When a run-time error occurs, the program issues an exception, which deals with errors by looking for code within the program to handle the error. If no such code is found, the program stops and has to be restarted. Because this can lead to the loss of data, it is wise to create error-handling code wherever you anticipate errors occurring.

The Try...Catch...Finally Block

You can use the Try...Catch...Finally block to handle run-time errors in your code. You can Try a segment of code—if an exception is issued by that code, it jumps to the Catch block, and then the code in the Catch block is executed. After that code has finished, any code in the Finally block is executed. The entire Try...Catch...Finally block is closed by an End Try statement. The following example illustrates how each block is used.

Try

' Code here attempts to do something.

Catch

' If an error occurs, code here will run.

Finally

' Code in this block will always run.

End Try

First, the code in the Try block is executed. If it runs without error, the program skips the Catch block and runs the code in the Finally block. If an error does occur in the Try block, execution immediately jumps to the Catch block, and the code there is run; then the code in the Finally block is run.

Try It!

To use the Try...Catch block

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 TryCatch and then click OK.

Page 23: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 23

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:

Try

Dim aNumber As Double = CDbl(Textbox1.Text)

MsgBox("You entered the number " & aNumber)

Catch

MsgBox("Please enter a number.")

Finally

MsgBox("Why not try it again?")

End Try

7. Press F5 to run the program. 8. In the text box, type a numeric value and click the button. A message box that displays the number

you entered, followed by an invitation to try again, is displayed. 9. Next, type a non-numeric value in the text box, such as a word, and click the button. This time,

when the program attempts to convert the text in the text box to a number, it cannot, and an error occurs. Instead of finishing the code in the Try block, the Catch block is executed and you receive a message box asking you to enter a number. The Finally block then executes, inviting you to try again.

Know Your Bugs: Three Kinds of Programming Errors

In this section, you will learn about the different types of errors that can occur when writing a program.

Even the most experienced programmers make mistakes, and knowing how to debug an application and find those mistakes is an important part of programming. Before you learn about the debugging process, however, it helps to know the types of bugs that you will need to find and fix.

Programming errors fall into three categories: compilation errors, run-time errors, and logic errors. The techniques for debugging each of these are covered in the next three sections.

Compilation Errors

Compilation errors, also known as compiler errors, are errors that prevent your program from running. When you press F5 to run a program, Visual Basic compiles your code into a binary language that the computer understands. If the Visual Basic compiler comes across code that it does not understand, it issues a compiler error.

Most compiler errors are caused by mistakes that you make when typing code. For example, you might misspell a keyword, leave out some necessary punctuation, or try to use an End If statement without first using an If statement.

Fortunately the Visual Basic Code Editor was designed to identify these mistakes before you try to run the program.

Page 24: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 24

Run Time Errors

Run-time errors are errors that occur while your program runs. These typically occur when your program attempts an operation that is impossible to carry out.

An example of this is division by zero. Suppose you had the following statement:

Speed = Miles / Hours

If the variable Hours has a value of 0, the division operation fails and causes a run-time error. The program must run in order for this error to be detected, and if Hours contains a valid value, it will not occur at all.

When a run-time error does occur, you can use the debugging tools in Visual Basic to determine the cause..

Logic Errors

Logic errors are errors that prevent your program from doing what you intended it to do. Your code may compile and run without error, but the result of an operation may produce a result that you did not expect.

For example, you might have a variable named FirstName that is initially set to a blank string. Later in your program, you might concatenate FirstName with another variable named LastName to display a full name. If you forgot to assign a value to FirstName, only the last name would be displayed, not the full name as you intended.

Logic errors are the hardest to find and fix, but Visual Basic has debugging tools that make this job easier.

Procedures in Visual Basic

A procedure is a block of Visual Basic statements enclosed by a declaration statement (Function, Sub, Operator, Get, Set) and a matching End declaration. All executable statements in Visual Basic must be within some procedure.

Calling a Procedure

You invoke a procedure from some other place in the code. This is known as a procedure call. When the procedure is finished running, it returns control to the code that invoked it, which is known as the calling code. The calling code is a statement, or an expression within a statement, that specifies the procedure by name and transfers control to it.

Returning from a Procedure

A procedure returns control to the calling code when it has finished running. To do this, it can use a Return Statement, the appropriate Exit Statement for the procedure, or the procedure's End Statement. Control then passes to the calling code following the point of the procedure call.

• With a Return statement, control returns immediately to the calling code. Statements following the Return statement do not run. You can have more than one Return statement in the same procedure.

• With an Exit Sub or Exit Function statement, control returns immediately to the calling code. Statements following the Exit statement do not run. You can have more than one Exit statement in the same procedure, and you can mix Return and Exit statements in the same procedure.

• If a procedure has no Return or Exit statements, it concludes with an End Sub or End Function, End Get, or End Set statement following the last statement of the procedure body. The End statement returns control immediately to the calling code. You can have only one End statement in a procedure.

Page 25: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 25

Parameters and Arguments

In most cases, a procedure needs to operate on different data each time you call it. You can pass this information to the procedure as part of the procedure call. The procedure defines zero or more parameters, each of which represents a value it expects you to pass to it. Corresponding to each parameter in the procedure definition is an argument in the procedure call. An argument represents the value you pass to the corresponding parameter in a given procedure call.

Types of Procedures

Visual Basic uses several types of procedures:

• Sub Procedures perform actions but do not return a value to the calling code. • Event-handling Procedures are Sub procedures that execute in response to an event raised by user

action or by an occurrence in a program. • Function Procedures return a value to the calling code. They can perform other actions before

returning. • Property Procedures return and assign values of properties on objects or modules. • Operator Procedures define the behaviour of a standard operator when one or both of the

operands is a newly-defined class or structure. • Generic Procedures define one or more type parameters in addition to their normal parameters,

so the calling code can pass specific data types each time it makes a call.

Procedures and Structured Code

Every line of executable code in your application must be inside some procedure, such as Main, calculate, or Button1_Click. If you subdivide large procedures into smaller ones, your application is more readable.

Procedures are useful for performing repeated or shared tasks, such as frequently used calculations, text and control manipulation, and database operations. You can call a procedure from many different places in your code, so you can use procedures as building blocks for your application.

Structuring your code with procedures gives you the following benefits:

• Procedures allow you to break your programs into discrete logical units. You can debug separate units more easily than you can debug an entire program without procedures.

• After you develop procedures for use in one program, you can use them in other programs, often with little or no modification. This helps you avoid code duplication.

Sub Procedures A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub statements. The Sub procedure performs a task and then returns control to the calling code, but it does not return a value to the calling code.

Each time the procedure is called, its statements are executed, starting with the first executable statement after the Sub statement and ending with the first End Sub, Exit Sub, or Return statement encountered.

You can define a Sub procedure in modules, classes, and structures. By default, it is Public, which means you can call it from anywhere in your application that has access to the module, class, or structure in which you defined it.

The term, method, describes a Sub or Function procedure that is accessed from outside its defining module, class, or structure.

A Sub procedure can take arguments, such as constants, variables, or expressions, which are passed to it by the calling code.

Page 26: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 26

Declaration Syntax

The syntax for declaring a Sub procedure is as follows:

[modifiers] Sub subname[(parameterlist)]

' Statements of the Sub procedure.

End Sub

The modifiers can specify access level and information about overloading, overriding, sharing, and shadowing.

Parameter Declaration

You declare each procedure parameter similarly to how you declare a variable, specifying the parameter name and data type. You can also specify the passing mechanism, and whether the parameter is optional or a parameter array.

The syntax for each parameter in the parameter list is as follows:

[Optional] [ByVal | ByRef] [ParamArray] parametername As datatype

If the parameter is optional, you must also supply a default value as part of its declaration. The syntax for specifying a default value is as follows:

Optional [ByVal | ByRef] parametername As datatype = defaultvalue

Parameters as Local Variables

When control passes to the procedure, each parameter is treated as a local variable. This means that its lifetime is the same as that of the procedure, and its scope is the whole procedure.

Calling Syntax

You invoke a Sub procedure explicitly with a stand-alone calling statement. You cannot call it by using its name in an expression. You must provide values for all arguments that are not optional, and you must enclose the argument list in parentheses. If no arguments are supplied, you can optionally omit the parentheses. The use of the Call keyword is optional but not recommended.

The syntax for a call to a Sub procedure is as follows:

[Call] subname[(argumentlist)]

You can call a Sub method from outside the class that defines it. First, you have to use the New keyword to create an instance of the class, or call a method that returns an instance of the class. Then, you can use the following syntax to call the Sub method on the instance object:

Object.methodname[(argumentlist)]

Page 27: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 27

Illustration of Declaration and Call

The following Sub procedure tells the computer operator which task the application is about to perform, and also displays a time stamp. Instead of duplicating this code at the start of every task, the application just calls tellOperator from various locations. Each call passes a string in the task argument that identifies the task being started.

Sub tellOperator(ByVal task As String) Dim stamp As Date stamp = TimeOfDay() MsgBox("Starting " & task & " at " & CStr(stamp)) End Sub

The following example shows a typical call to tellOperator.

tellOperator("file update")

Page 28: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 28

Keyboard Shortcuts: Navigating the IDE by Using the Keyboard

Visual Basic has many keyboard shortcuts that you can use to help you perform tasks in the Integrated Development Environment (IDE) quickly. The following tables describe some of these keyboard shortcuts, and give the command name equivalents in parenthesis.

Editing

Title Shortcut Description

Toggle All Outlining CTRL +M, CTRL + L Toggles all existing regions between collapsed and expanded states.

(Edit.ToggleAllOutlining)

Toggle Outlining for

Current Region

CTRL + M, CTRL +

M

Toggles the current region between collapsed and expanded states.

(Edit.ToggleOutliningExpansion)

Comment and

Uncomment

CTRL + K, CTRL + C

CTRL + K, CTRL + U

Inserts and removes, respectively, the apostrophe (') at the start of the current line

or every selected line. (Edit.CommentSelection and Edit.UncommentSelection)

Undo CTRL + Z Undoes the last action. (Edit.Undo)

Redo CTRL + SHIFT + Z Redoes the last action. (Edit.Redo)

Cut Line CTRL + Y Cuts the current line of code. (Edit.LineCut)

Insert Blank Line CTRL + ENTER

CTRL + SHIFT +

ENTER

Inserts a blank line above or below the cursor position, respectively.

(Edit.LineOpenAbove and Edit.LineOpenBelow)

Select Word CTRL + SHIFT + W Selects the word that contains, or is to the right of, the cursor.

(Edit.SelectCurrentWord)

Delete Word CTRL +

BACKSPACE

CTRL + DELETE

Deletes to the start and end of the word, respectively.

(Edit.WordDeleteToStart and Edit. WordDeleteToEnd)

Change Casing CTRL + U

CTRL + SHIFT + U

Changes the selected text to lowercase or uppercase characters, respectively.

(Edit.MakeLowercase and Edit.MakeUppercase)

Replace CTRL + H Displays the Quick Replace tab or the Replace In Files tab, respectively, of the

Page 29: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 29

CTRL + SHIFT H Find and Replace dialog box. (Edit.Replace and Edit.ReplaceInFiles)

Extend Selection SHIFT + ALT + UP

ARROW

SHIFT + ALT +

DOWN ARROW

Moves the cursor one line up or down respectively, extending the line selection.

(Edit.LineUpExtendColumn and Edit.LineDownExtendColumn)

Format Code CTRL + K, CTRL + D

CTRL + K, CTRL + F

Formats the current document or selection, respectively. (Edit. FormatDocument

and Edit.FormatSelection)

Display Smart Tag CTRL + DOT (.)

SHIFT + ALT + F10

Displays the available options on the Smart Tag menu. (View. ShowSmartTag)

Help F1 Displays a topic from Help that corresponds to the current user interface element

or to the code item or error messages selected. (Help.F1Help)

Build and Debugging

Title Shortcut Description

Build Solution CTRL + SHFT + B Builds all the projects in the solution. (Build.BuildSolution)

Start Debugging F5 Starts the application in the debugger. When in Break mode, invoking this

command runs the application until the next breakpoint. (Debug.Start)

Start Without

Debugging

CTRL + F5 Starts the application without invoking the debugger. Use this exclusively instead

of F5 for Web site debugging. (Debug.StartWithoutDebugging)

Step Into F8 or F11 Executes code one statement at a time, following execution into method calls.

(Debug.StepInto)

Step Out CTRL + SHIFT + F8

SHIFT + F11

Executes the remaining lines of the method in which the current execution point is

located. (Debug.StepOut)

Step Over SHIFT + F8

F10

Executes the next line of code, but does not follow execution into any method

calls. (Debug.StepOver)

Stop Debugging CTRL + ALT + BREAK Stops running the current application in the debugger. (Debug.StopDebugging)

Toggle Breakpoint F9 Sets or removes a breakpoint at the current line. (Debug.ToggleBreakpoint)

Page 30: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 30

Set Next Statement CTRL + F9 Sets the execution point to the line of code you choose.

(Debug.SetNextStatement)

Break at a Function CTRL + B Displays the New Breakpoint window. (Debug.BreakatFunction)

Attach to Process CTRL + ALT + P Displays the Attach to Process dialog box. (Tools.AttachToProcess)

Make Data Tip

Transparent

CTRL Hides the current data tip so that you can see the code underneath it. Must be

invoked while a data tip is active.

Immediate Window CTRL + G Displays the Immediate window. (Debug.Immediate)

Call Stack Window CTRL + L Displays the Call Stack window. (Debug.CallStack)

QuickWatch

Window

SHIFT + F9 Displays the QuickWatch dialog box. (Debug.QuickWatch)

Windows

Title Shortcut Description

Navigation Bar CTRL + F2 Moves the cursor to the drop-down list located at the top of the Code Editor.

(Window.MoveToNavigationBar)

Object Browser F2 Displays the Object Browser. (View.ObjectBrowser)

Properties Window F4 Displays the Properties window for the currently selected item.

(View.PropertiesWindow)

Solution Explorer CTRL + R Displays Solution Explorer. (View.SolutionExplorer)

Show Data Sources SHIFT + ALT

+ D

Displays the Data Sources window. (Data.ShowDataSources)

Toolbox CTRL + ALT +

X

Displays the Toolbox. (View.Toolbox)

Error List CTRL + \, E Displays the Error List. (View.ErrorList)

Close Tool Window SHIFT + ESC Closes the current tool window. (Window.CloseToolWindow)

Page 31: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 31

Close Document

Window

CTRL + F4 Closes the current tab. (Window.CloseDocumentWindow)

Navigation

Title Shortcut Description

Go to Definition F12

SHIFT + F12

Moves to the declaration for the selected symbol. (Edit.GoToDefinition)

Highlight References CTRL + SHIFT

+ UP/DOWN

ARROW

Moves to the next or previous reference for the selected symbol, or clause of an

If...Then...Else or Select...Case statement. CTRL + SHIFT + DOWN + ARROW moves to

the next reference for the selected symbol; CTRL + SHIFT + UP ARROW moves to the

previous reference. (Edit.MoveToNextReference, Edit.MoveToPreviousReference)

IDE Navigator CTRL + TAB Displays the IDE Navigator, with the first document window selected. The IDE Navigator

functions similarly to the Windows Navigator (ALT + SHIFT + TAB), only it is for files and

tool windows within Visual Studio. (Window.NextDocumentWindowNav)

View All Open

Documents

CTRL + ALT +

DOWN

ARROW

Displays a pop-up listing of all open documents. (Window.ShowEzMDIFileList)

View Code F7 Displays the selected item in Code view. (View.ViewCode)

View Designer SHIFT + F7 Displays the selected item in Design view. (View.ViewDesigner)

Add or Remove

Bookmark

CTRL + K,

CTRL + K

Sets or removes a bookmark at the current line. (Edit.ToggleBookmark)

Navigate Bookmarks CTRL + K,

CTRL + N

CTRL + K,

CTRL + P

Moves to the next or previous bookmark, respectively. (Edit.NextBookmark and Edit.

PreviousBookmark)

Delete All

Bookmarks

CTRL + K,

CTRL + L

Deletes all bookmarks. (Edit.ClearBookmarks)

Search

Title Shortcut Description

Find Symbol ALT + F12 Displays the Find Symbol dialog box. (Edit.FindSymbol)

Page 32: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 32

Find All References ALT + SHIFT + F12 Displays a list of all references for the symbol selected. (Edit.FindAllReferences)

Find Text CTRL + F

CTRL + SHIFT + F

Displays the Find and Replace dialog box for a single-file and multiple-file

search, respectively. (Edit.Find and Edit.FindInFiles)

Next and Previous

Result

F3

SHIFT + F3

Finds the next and previous occurrence, respectively, of the text from the most

recent search. (Edit.FindNext and Edit.FindPrevious)

Next and Previous

Selected

CTRL + F3

CTRL + SHIFT F3

Finds the next and previous occurrence, respectively, of the currently selected

text or the word at the cursor position. (Edit.FindNextSelected and Edit.

FindPreviousSelected)

Incremental Search ALT + I

ALT + SHIFT + I

Activates incremental search (forward and reverse). If no input is typed, the

previous search query is used. (Edit.IncrementalSearch and

Edit.ReverseIncrementalSearch)

Stop Search ALT + F3, S Halts the current Find In Files operation. (Edit.StopSearch)

File

Title Shortcut Description

New Project CTRL + N

CTRL + SHIFT + N

Displays the New Project dialog box. (File.NewProject)

Open Project CTRL + O

CTRL + SHIFT + O

Displays the Open Project dialog box. (File.OpenProject)

Add New Item CTRL + SHIFT + A Displays the Add New Item dialog box. (Project.AddNewItem)

Add Existing Item CTRL + D Displays the Add Existing Item dialog box. (Project.AddExistingItem)

Snippets

Title Shortcut Description

Insert Snippet Type ? and press TAB Displays the Code Snippet Picker in the Code Editor. The selected code snippet

is then inserted at the cursor position. (Edit.InsertSnippet)

Insert Snippet from

Shortcut

Type the snippet

shortcut and press TAB

Inserts the expanded code snippet. (Edit.InvokeSnippetFromShortcut)

Page 33: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 33

Insert Property

Snippet

Type property and

press TAB

Inserts a Property snippet. (Example of Edit.InvokeSnippetFromShortcut)

Insert For Snippet Type for and press TAB Inserts a For…Next snippet. (Example of Edit.InvokeSnippetFromShortcut)

List Snippet

Shortcuts

Type a snippet shortcut

prefix, type ?, and press

TAB

Displays the Code Snippet Shortcut Picker. The shortcut in the list, which most

closely matches the prefix, is selected.

List Snippet

Replacements

CTRL + SPACE Invokes an IntelliSense completion list for the currently selected snippet

replacement.

Escape

Replacement

Selection

ESC Deselects the current text. A second ESC deselects the replacement. Can be

useful when you want to type at the end of a replacement without extending

its bounds.

IntelliSense

Title Shortcut Description

Display a Filtered

List

CTRL + J Displays the IntelliSense completion list for the current cursor position.

(Edit.ListMembers)

Display the Global

List or Complete a

Word

CTRL + SPACE If invoked when no list is active, displays the IntelliSense completion list for

the current cursor position. If a substring has already been typed and there is

a match in the list, completes the word without invoking the list. If invoked

when a filtered list is active, switches to the global list. (Edit.CompleteWord)

Common Tab ALT + COMMA (,) Decreases the filter level of the active IntelliSense list to the Common tab.

All Tab ALT + PERIOD (.) Increases the filter level of the active IntelliSense list to the All tab.

Navigate Up CTRL + PAGE UP Navigates to the first item in the IntelliSense completion list.

Navigate Down CTRL + PAGE DOWN Navigates to the last item in the IntelliSense completion list.

Commit an Item TAB

SPACE

ENTER

Inserts the currently selected item in the list. The following characters can also

be used to commit: { } ( ) . , : ; + - * / ^ ! = < > \

Page 34: An Introduction to Programming in Visual Basic · An Introduction to Programming in Visual Basic | Page 3 For values that can be represented as true/false, yes/no, or on/off, Visual

An Introduction to Programming in Visual Basic

| P a g e 34

Escape the List ESC Closes the IntelliSense completion list. This can be useful if you want to

prevent the currently selected item from being inserted.