Platinum Edition Using Visual Basic 5

Previous chapterNext chapterContents


- 8 -
Programming Visual Basic

Learn how you can use variables to store and retrieve information while your programs are running.
Perform mathematical and string operations on the information your program uses.
Learn how you can use conditional statements to have your code make decisions that affect your program's processing flow.
You see how procedures and functions make it easier to create, test, and reuse parts of your code. Also, discover how to use loops to make the computer run a task multiple times.
Use Visual Basic's integrated debugging environment to easily track errors in your programs.

Although designing your program's user interface with forms and controls is important, most of its actual work is done with code. Visual Basic is a powerful programming language that is relatively easy to use. Visual Basic is a direct descendant of the BASIC programming language, which has been around for many years. BASIC was designed as a language for beginning programmers, hence the name, which is an abbreviation of Beginner's All-purpose Symbolic Instruction Code.

However, don't let the name fool you. Visual Basic is a much more powerful language than the BASIC you may remember from high school. With release 5.0, the language has been extended far beyond its primitive ancestry. Visual Basic has grown into a robust programming environment that can solve a wide variety of application needs.

This chapter looks at some of the basic concepts of programming in Visual Basic--starting with variables, working with information, and controlling your program with loops and conditional statements.

Working with Variables

Simply stated, you use variables to store information in the computer's memory while your programs are running. Three components define a variable:

Suppose you are given the assignment: "Go count all of the cars in the parking lot." As you count each car, you are storing information in a variable. Your location in memory is either a notepad or your brain. The type of information being stored is a number. And the actual information you are storing is the current number of cars.

As the name variable suggests, the information stored in a variable can change over time. Another way to think of a variable is that it's like a mailbox. You can perform two basic functions on a variable: get the information (remove a letter from the mailbox) and write new information (put a letter into the mailbox).

A variable has to have a name to be able to assign values to it. You might have noticed in earlier examples, statements like:

Dim X As Integer

This is a Dim statement, used for dimensioning (or declaring) variables. When your program declares a variable, it is, in essence, telling Visual Basic: "Set aside some memory for me and call it X." The last two words in the statement tell VB what type of information you will be storing, in this case integer numbers. This helps determine how much memory is to be set aside for the variable.

In naming a variable, you have a tremendous amount of flexibility. Variable names can be simple, or they can be descriptive of the information they contain. In the preceding example, X is a perfectly legal name, but not very descriptive to the reader. While you are allowed great latitude in naming variables, there are a few restrictions:


TIP: Make your variable names descriptive of the task to make your code easy to read, but also keep the names as short as possible to make the code easy to type. Many programmers also use prefixes in their variable names to indicate the type of data stored; usually these conventions are variations of the Hungarian Naming Convention. These prefixes usually consist of one or two lowercase characters at the beginning of the variable; the next letter is usually capitalized.

For example, a prefix of in, as in inAge, would indicate a variable that stores an integer value. The following table lists some of the common prefixes that I use when naming variables. This convention is used for many of the original code samples in this book. You might prefer a one-character prefix or some other convention altogether.


Variable Type Prefix Example
String st stFirstName
Integer in inAge
Long Integer lg lgPopulation
Single sg sgAverageGrade
Double db dbThrustRatio
Currency cr crPayRate
Boolean bl blTaxable

Types of Variables

Okay, you know what a variable does and how to name it. But what can you store in a variable? The simple answer is: almost anything. A variable can hold a number; a string of text; or an instance of an object, such as a form, control, or database. This chapter looks specifically at using variables to store numbers, strings, and logical values. Use of objects and database objects is covered later in Chapters 28, "Improving Data Access with the Data Access Objects," and 32, "Using Classes in Visual Basic," respectively.

Each type of variable has its own memory requirements and is designed to work efficiently with different types of information. Therefore, you couldn't store a string like "Hello" in a variable that you declared as an integer.

Table 8.1 shows some of the standard variable types that are available in Visual Basic. The table also shows the range of values that the variable can hold and the amount of memory required. Variables with smaller memory requirements should be used wherever possible to conserve system resources.

Table 8.1 Variables Store Many Types of Information

Type Stores Memory Requirement Range of Values
Integer Whole umbers Two bytes -32,768 to +32,767
Long Whole umbers Four bytes (approximately) +/- 2 billion
Single Decimal umbers Four bytes +/- 1E-45 to 3E38
Double Decimal umbers Eight bytes +/- 5E-324 to 1.8E308
Currency Numbers with up to 15 digits left of the decimal and four digits right of the decimal Eight bytes +/- 9E14
String Text information One byte per character Up to 65,400 characters for fixed-length string and up to two billion characters for dynamic strings
Byte Whole umbers One byte 0 to 255
Boolean Logical values Two bytes True or False
Date Date and Eight bytes time information 1/1/100 to 12/31/9999
Object Instances of classes; OLE objects Four bytes N/A
Variant Any of the preceding data types 16 bytes +1 byte per character N/A

In addition to the preceding variable types, there are specialized types to deal with databases (Database, Field, and Recordset). Visual Basic knows about these other data types when you add a reference to a type library. It is also possible to create user-defined types to meet your needs.

Variable Declarations

In the section "Working with Variables" earlier in this chapter, you saw an example of the Dim statement, which is used to tell Visual Basic the name and type of your variable. However, Visual Basic does not require you to specifically declare a variable before it is used. If a variable is not declared, Visual Basic creates the variable by using a default data type known as a variant. A variant can contain any type of information. Using a variant for general information has two major drawbacks--it can waste memory resources, and the variable type might be invalid for use with some data-manipulation functions that expect a specific variable type.

It is good programming practice to declare your variables before they are used, so take a look at the two ways to declare a variable in Visual Basic--explicit and implicit declaration.

Explicit Declaration Explicit declaration means that you use a statement to define the type of a variable. These statements do not assign a value to the variable but merely tell Visual Basic what the variable can contain. Each of the following statements can be used to explicitly declare a variable's type:

Dim varname [As vartype][, varname2 [As vartype2]]
Private varname [As vartype][, varname2 [As vartype2]]
Static varname [As vartype][, varname2 [As vartype2]]
Public varname [As vartype][, varname2 [As vartype2]]

Dim, Private, Static, and Public are Visual Basic keywords that define how and where the variable can be used. varname and varname2 represent the names of two variables that you want to declare. As indicated in the syntax, you can specify multiple variables in the same statement as long as you separate the variables with commas. Note that the syntax shows only two variables on one line, but you can specify several. In fact, over a thousand characters will fit on one line in the Code window. From a practical standpoint, however, you should refrain from writing lines of code that are wider than the displayed Code window. This will make your code much easier to read, as you don't have to scroll left and right when looking at it.

vartype and vartype2 represent the type definitions of the respective variables. The type definition is a keyword that tells Visual Basic what kind of information will be stored in the variable. As indicated, the variable type is an optional property. If you include the variable type, you must include the keyword As. If you do not include a variable type, the Variant type (which is the default) is used.

The following code shows the use of these declaration statements for actual variables:

Private inNumVal As Integer
Private inAvgVal As Integer, varInptVal As Variant
Static sgClcAverage As Single
Dim stInptMsg As String

Implicit Declaration It is best to declare your variables using the Dim or other statements shown in the section "Working with Variables" earlier in this chapter, but in many cases you also can assign a type to a variable using an implicit declaration. With this type of declaration, a special character is used at the end of the variable name when the variable is first assigned a value. The characters for each variable type are shown in Table 8.2.

Table 8.2 Special Characters at the End of a Variable Name that Can Identify the Type of Data Stored by the Variable

Variable Type Character
Integer %
Long &
Single !
Double #
Currency @
String $
Byte None
Boolean None
Date None
Object None
Variant None

The variables that were declared using the code in the preceding section could have been used as implicitly declared variables, without having to declare their types with Dim statements, as follows:

inNumVal% = 0
inAvgVal% = 1
varInptVal = 5
sgClcAverage! = 10.1
stInptMsg$ = "Mike"

You might have noticed that the variable varInptVal didn't have a declaration character. This means that InptVal will be of the Variant type.

Fixed-Length Strings Most strings that you use in your programs will be of the type known as variable-length strings. These strings can contain any amount of text, up to approximately two billion characters. As information is stored in the variable, the size of the variable adjusts to accommodate the length of the string. Both the implicit and explicit declarations shown earlier created variable-length strings. There is, however, a second type of string in Visual Basic--the fixed-length string.

As the name implies, a fixed-length string remains the same size, regardless of the information assigned to it. If a fixed-length string variable is assigned an expression shorter than the defined length of the variable, the remaining length of the variable is filled with the space character. If the expression is longer than the variable, only the characters that fit in the variable are stored; the rest are truncated.

A fixed-length string variable can only be declared by using an explicit declaration of the form, like the following:

Dim varname As String*strlength

Notice that this declaration is slightly different from the previous declaration of a string variable. The declaration of a fixed-length string variable contains an asterisk (*) to tell Visual Basic that the string will be of a fixed length. The final parameter, strlength, tells the program the maximum number of characters that the variable can contain.

Variable Arrays

All the variables you've worked with so far have been single-instance variables. Often, however, you'll find it very useful to work with variable arrays. An array is a group of variables of the same type, sharing the same name. This makes it easy to process groups of related areas. For example, you might want to have a group of variables that tracks the sales in each of your company's four regions. You could declare a currency variable for each region, plus one for the total sales across all regions, like this:

Dim crRegSales1 As Currency, crRegSales2 As Currency
Dim crRegSales3 As Currency, crRegSales4 As Currency
Dim crTotalSales As Currency

Then, if you wanted to calculate the total sales for all regions, you might use this code:

crTotalSales = crRegSales1 + crRegSales2 + crRegSales3 + crRegSales4

This isn't all that cumbersome. However, what if you had 20 regions? Or several hundred? You can see how working with large numbers of related variables could get messy very quickly.

You can greatly enhance this example by using a variable array. We'll create an array of variables named crRegSales; the array will contain as many elements (instances of variables) as we have regions. We could rewrite our previous example for 20 regions like this:

Dim crRegSales(1 To 20) As Currency
Dim crTotalSales As Currency
Dim inCounter As Integer
Dim stTemp As String
    crTotalSales = 0
    For inCounter = 1 To 20
        crTotalSales = crTotalSales + crRegSales(inCounter)
   ext inCounter
    stTemp = "Total sales for all regions = "
    stTemp = stTemp & Format(crTotalSales, "currency")
        MsgBox stTemp, vbInformation, "Sales Analysis"

Note this example's use of a repetition loop. The block of code beginning with the For instruction and ending with the Next instruction defines a group of program statements that will be repeated a certain number of times (in this case, 20). Using loops makes short work of processing variable arrays. We cover loops in the section "Working with Loops" a little later in this chapter.

As you progress through this book, you'll see several cases where variable arrays can make your coding much simpler.

Determining Where a Variable Can Be Used

In addition to telling Visual Basic what you want to be able to store in a variable, a declaration statement tells Visual Basic where the variable can be used. This area of usage is called the scope of the variable. This is analogous to the coverage area of a paging system. When you purchase a pager, you make a decision whether you want local service, regional service, or nationwide service. This is then programmed into your pager when you buy it. If you go outside the service area, your pager does not work. In a similar manner, you can declare variables to work in only one procedure, work in any procedure of a form, or work throughout your program.

By default, a variable that is implicitly declared is local to the procedure in which it is created. If you don't specify any kind of declaration, explicit or implicit, you create a local variable of the variant type. Therefore, to create variables that have a scope other than local, you must use a declaration statement.


NOTE: The scope of a variable is determined not only by the type of declaration, but by the location of the declaration as well. For instance, the Dim and Private keywords assume different meanings in different parts of a form's code.

Creating Variables that Are Available Everywhere In most programs, unless you have only one form and no code modules, you will find that you need some variables that can be accessed from anywhere in the code. These are called Public variables. (Other languages, as well as earlier versions of Visual Basic, might refer to these as Global variables. In fact, Visual Basic still recognizes the Global keyword.) These variables are typically used to hold information such as the name of the program's user, or to reference a database that is used throughout the program. They might also be used as flags to indicate various conditions in the program.

To create a Public variable, you simply place a declaration statement with the Public keyword in the declarations section of a module of your program. The following line shows the Public declaration of a variable used for referencing a database:

Public dbMemDB As Database

See "Determining the Scope of Procedures and Functions," Chapter 17

In a form or a class module, the Public keyword has a special meaning. Variables defined as Public act like a property of the form or class that is available anywhere in the program. These properties are referenced like the built-in properties of a form or control instead of like a variable. The Public properties are used to pass information between forms and other parts of your program.

Keeping a Variable Local If you do not eed to access a variable from everywhere in your program, you do not want to use the Public keyword in a declaration. Instead, you should use the Dim or Private keywords. These keywords tell Visual Basic to define the variable within the scope of the current procedure or form. With these declarations, the location of the statement determines the actual scope of the variable. If the variable is defined in the General Declarations section of a form or module, the variable is available to every procedure in that form or module. This is known as a form-level or module-level variable. If the variable is declared inside a procedure, it can be used only within that procedure. This is typically known as a local variable.

Using Static Variables Most variables that are created inside a procedure are discarded by Visual Basic when the procedure is finished. There are times, however, when you might want to preserve the value of a variable even after the procedure has run. This is often the case when you call the procedure multiple times, and the value of a variable for one call to the procedure is dependent on the value left over from previous calls.

To create a variable that retains its value, you use the Static keyword in the variable declaration. This tells Visual Basic that the variable can be referenced only within the procedure, but to remember the value because it might be needed again. Here's an example of a variable declared using the Static keyword:

Static inPageNumber As Integer


NOTE: If you use the Static keyword to declare a procedure, all variables in the procedure are treated as static.

Using the Option Explicit Statement

You learned in the earlier section, "Variable Declarations," that it's good programming practice to declare your program's variables before they are used. You can ensure that you do this by setting one of the environment options of Visual Basic. To do this, access Visual Basic's Options dialog box by choosing Tools, Options. In this dialog box's Editor tab, you find the Require Variable Declaration option (see Figure 8.1). Selecting this box forces you to declare each variable before you use it.

FIG. 8.1
The Require Variable Declaration option helps prevent you from mistyping variable names.

Setting the Require Variable Declaration option causes the Option Explicit statement to be placed in the General Declarations section of each new module or form that is added to your project, as shown in Figure 8.2.

FIG. 8.2
The Option Explicit statement is added to your program.

If you have invoked Option Explicit and you fail to declare a variable, you will receive the error message Variable not defined when you try to run your code. The integrated debugger highlights the offending variable and pauses the execution of your program. The benefit of this is that it helps you avoid errors in your code that might be caused by typographical errors. For example, you might declare a variable using the following statement:

Dim stMyName As String

If in a later statement, you mistyped the variable name, Visual Basic would catch the error for you, rather than continue with unpredictable results. For example, the following statement would cause an error:

stMyNme = "Tina Marie"


CAUTION: If you set the Require Variable Declaration option after starting to create a program, the option has no effect on any forms or modules that have already been created. In this case, you can add the Option Explicit statement as the first line of code in the General Declarations section of any existing forms or modules.


TIP: If you use some capital letters in your variable declarations, then enter your code in all lowercase letters. Visual Basic automatically sets the capitalization of your variable to match the declaration. This gives you an immediate visual indication that you typed the name correctly.

What's Different About Constants

Variables are just one way of storing information in the memory of a computer. Another way is to use constants. Constants in a program are treated a special way. After you define them (or they are defined for you by Visual Basic), you cannot change them later in the program by using an assignment statement. If you try, Visual Basic generates an error when you run your program.

Constants are most often used to replace a value that is hard to remember, such as the color value for the Windows title bar. It is easier to remember the constant vbActiveTitleBar than the value 2147483646. You can also use a constant to avoid typing long strings if they are used in a number of places. For example, you could set a constant such as FileFoundError containing the string "The requested file was not found."

Constants are also used a lot for conversion factors, such as 12 inches per foot or 3.3 feet per meter. The following code example shows how constants and variables are used:

Const MetersToFeet = 3.3
inDistMeters = InputBox("Enter a distance in meters")
inDistFeet = inDistMeters * MetersToFeet
MsgBox "The distance in feet is: " & Str(inDistFeet)

Another common use for constants is to minimize changes to your code for reasons such as changing your program's name, version number, and so forth. You can define constants at the beginning of your program and use the predefined constants throughout the program. Then, when a version number changes, all you need to do is change the declaration of the constant. The following example illustrates this technique:

Public Const ProgTitle = "My Application Name"
Public Const ProgVersion = "3.1"

Note the use of the Public keyword, which makes these constants available throughout the application (assuming that their declaration is in a module).

Constants that Visual Basic Supplies Visual Basic supplies a umber of built-in constants for various activities. These are known as intrinsic constants. There are color-definition constants, data-access constants, keycode constants, and shape constants, among many others. Especially useful are constants correlating to a command's parameter information, such as the vbExclamation constant that we've used for a MessageBox statement in previous chapters.

The constants that you need for most functions are defined in the help topic for the function. If you want to know the value of a particular constant, you can use the Object Browser (see Figure 8.3). Access the Object Browser by clicking its icon in the Visual Basic toolbar, by selecting View, Object Browser from the menu system, or simply by pressing F7. You can use the list to find the constant that you want. When you select it, its value and function are displayed in the text area at the bottom of the dialog box.

Creating Your Own Constants While Visual Basic defines a large number of constants for many activities, there will be times when you need to define your own constants. Constants are defined using the Const statement to give the constant a name and a value, as illustrated in the following syntax:

Const constantname [As constanttype] = value

If you think this statement looks similar to the declaration of a variable, you are right. As with declaring a variable, you provide a name for the constant and, optionally, specify the type of data it will hold. The Const keyword at the beginning of the statement tells Visual Basic that this statement defines a constant. This distinguishes the statement from one that just assigns a value to a variable. In declaring the type of a constant, you use the same types as you did for defining variables. (These types are defined in Table 8.1.) Finally, to define a constant, you must include the equal sign (=) and the value to be assigned. If you are defining a string constant or date constant, remember to enclose the value in either quotes ("") or the pound sign (#), respectively.

FIG. 8.3
The Object Browser shows you the value and function of most of Visual Basic's internal constants.

A constant's scope is also important. The same rules for the scope of variables, which were discussed in the earlier section, "Determining Where a Variable Can Be Used," apply to constants as well.

Writing Simple Statements

Now you know a little about variables and constants. You know what data they can store and how to initially set them up. But that is just the beginning of working with information in a program. You also need to be able to assign information to the variable and manipulate that information. Stay tuned--it's covered in the next section.

Using the Assignment Statement

After setting up a variable, the first thing you need to do to use the variable is to store information in the variable. This is the job of the assignment statement. The assignment statement is quite simple; you specify a variable whose value you want to set, place an equal sign after the variable name, and then follow this with the expression that represents the value you want stored. The expression can be a literal value, an expression or equation using some combination of other variables and constants, or even a function that returns a value. There is no limit on the complexity of the expression you can use. The only restriction is that the expression must yield a value of the same type as the variable to which it is assigned. The following statements illustrate different assignment statements:

inNumStudents = 25
inSumScores = 2276
sgAvgScore = SumScores / NumStudents
stTopStudent = "Janet Simon"
inISpace = InStr(TopStudent," ")
stFirstName = Left(TopStudent,ISpace)

You might have noticed that these statements look very similar to the ones used to set the properties of forms and controls in the section "Setting and Retrieving Property Values" in Chapter 4, "Working with Forms and Controls." Actually, they are the same. Most properties of forms and controls act like variables. They can be set at design time, but can also be changed at runtime using an assignment statement. You can also use a property on the right side of a statement to assign its value to a variable for further processing. For example, you use this assignment statement to read the top student name from a text box:

stTopStudent = txtTop.Text

Using Math Operators

Processing numerical data is one of the key activities of many computer programs. Mathematical operations are used to determine customer bills, interest due on savings or credit card balances, average scores for a class test, and many other bits of information. Visual Basic supports a number of different math operators that can be used in program statements. These operations and the Visual Basic symbol for each operation are summarized in Table 8.3. The operations are then described in detail.

Table 8.3 Math Operations and the Corresponding Visual Basic Symbol

Operation Operator
Addition +
Subtraction -
Multiplication *
Division /
Integer division \
Modulus mod
Exponentiation ^

Addition and Subtraction The two simplest math operations are addition and subtraction. You use these operations in such everyday chores as balancing your checkbook or determining how much change you should get back from a sales clerk. If you have ever used a calculator to do addition and subtraction, you already have a good idea how these operations are performed in a line of computer code.

A computer program, however, gives you greater flexibility than a calculator in the operations you can perform. Your programs are not limited to working with literal numbers (for example, 1, 15, 37.63, -105.2). Your program can add or subtract two or more literal numbers, numeric variables, or any functions that return a numeric value. Also, as with a calculator, you can perform addition and subtraction operations in any combination. Now let's take a look at exactly how you perform these operations in your program.

As indicated in Table 8.3, the operator for addition in Visual Basic is the plus sign (+). The general use of this operator is shown in the following syntax line:

result = number1 + number2 [+ number3]

result is a variable (or control property) that will contain the sum of the numbers. The equal sign indicates the assignment of a value to the variable. number1, number2, and number3 are the literal numbers, numeric variables, or functions that are to be added together. You can add as many numbers together as you like, but each number pair must be separated by a plus sign.

The operator for subtraction is the minus sign (-). The syntax is basically the same as for addition:

result = number1 - number2 [- number3]

While the order does not matter in addition, in subtraction, the number to the right of the minus sign is subtracted from the number to the left of the sign. If you have multiple numbers, the second number is subtracted from the first, then the third number is subtracted from that result, and so on, moving from left to right. For example, consider the following equation:

result = 15 - 6 - 3

The computer first subtracts 6 from 15 to yield 9. It then subtracts 3 from 9 to yield 6, which is the final answer stored in the variable result.

You can create assignment statements that consist solely of addition operators or solely of subtraction operators. You can also use the operators in combination with one another or other math operators. The following code lines show a few valid math operations:

val1 = 1.25 + 3.17
val2 = 3.21 - 1
val3 = val2 + val1
val4 = val3 + 3.75 - 2.1 + 12 - 3
val4 = val4 + 1

If you are not familiar with computer programming, the last line might look a little funny to you. In fact, that line is not allowed in some programming languages. However, in Visual Basic, you can enter a line of code that tells the program to take the current value of a variable, add another number to it, and then store the resulting value back in the same variable.

Multiplication and Division Two other major mathematical operations with which you should be familiar are multiplication and division. Like addition and subtraction, these operations are used frequently in everyday life.

Multiplication in Visual Basic is very straightforward, just like addition and subtraction. You simply use the multiplication operator--the asterisk (*) operator--to multiply two or more numbers. The syntax of a multiplication statement is almost identical to the ones for addition and subtraction, as follows:

result = number1 * number2 [* number3]

As before, result is the name of a variable used to contain the product of the numbers being multiplied, and number1, number2, and number3 are the literal numbers, numeric variables, or functions.

As a demonstration of how multiplication and division might be used in a program, consider the example of a program to determine the amount of paint needed to paint a room. Such a program could contain a form that lets the painter enter the length and width of the room, the height of the ceiling, and the coverage and cost of a single can of paint. Your program could then calculate the number of gallons of paint required and the cost of the paint. An example of the form for such a program is shown in Figure 8.4. The actual code to perform the calculations is shown in Listing 8.1.

FIG. 8.4
Multiplication and division are used to determine the amount of paint needed for a room.

Listing 8.1 COSTEST.FRM--Cost Estimation Using Multiplication and Division Operators

sgRmLength = Val(txtLength.Text)
slRmWidth = Val(txtWidth.Text)
sgRmHeight = Val(txtHeight.Text)
sgCanCoverage = Val(txtCoverage.Text)
crCanCost = val(txtCost.Text)
sgRmPerimeter = 2 * sgRmLength + 2 * sgRmWidth
sgWallArea = sgRmPerimeter * sgRmHeight
sgNumGallons = sgWallArea / sgCanCoverage
crProjCost = sgNumGallons * crCanCost
txtGallons.Text = sgNumGallons
txtTotalCost.Text = crProjCost

Division in Visual Basic is a little more complicated than multiplication. In Listing 8.1, you saw one type of division used. This division is what you are most familiar with and what you will find on your calculator. This type of division returns a number with its decimal portion, if one is present.

However, Visual Basic supports three different ways to divide numbers. These are known as floating-point division (the normal type of division, with which you are familiar); integer division; and modulus, or remainder, division.

Floating-point division is the typical division that you learned in school. You divide one number by another, and the result is a decimal number. The floating-point division operator is the forward slash (/):

result = number1 / number2 [/ number3]
`The following line returns 1.333333
Print 4 / 3

Integer division divides one number into another and then returns only the integer portion of the result. The operator for integer division is the backward slash (\):

result = number1 \ number2 [\ number3]
`The following line returns 1
Print 4 \ 3

Modulus, or remainder, division divides one number into another and returns what is left over after you have obtained the largest integer quotient possible. The modulus operator is the word mod:

result = number1 mod number2 [mod number3]
`The following line returns 2, the remainder when dividing 20 by 3
Print 20 mod 3

As with the case of addition, subtraction, and multiplication, if you divide more than two numbers, each number pair must be separated by a division operator. Also, like the other operations, multiple operators are handled by reading the equation from left to right.

Figure 8.5 shows a simple form that is used to illustrate the differences between the various division operators. The code for the command button of the form is shown as follows:

inpt1 = Text1.Text
inpt2 = Text2.Text
Text3.Text = inpt1 / inpt2
Text4.Text = inpt1 \ inpt2
Text5.Text = inpt1 Mod inpt2

The project CALULAT.VBP on the CD-ROM contains a calculator program that demonstrates the various math th operations.

FIG. 8.5
This program demonstrates the difference between Visual Basic's three types of division operators.

After setting up the form, run the program, enter 5 in the first text box and 3 in the second text box, and then click the command button. Notice that different numbers appear in each of the text boxes used to display the results. You can try this with other number combinations as well.

Exponents Exponents are also known as powers of a number. For example, 2 raised to the third power (23) is equivalent to 2x2x2, or 8. Exponents are used quite a lot in computer operations, where many things are represented as powers of two. Exponents are also used extensively in scientific and engineering work, where many things are represented as powers of ten or as natural logarithms. Simpler exponents are used in statistics, where many calculations depend on the squares and the square roots of numbers.

To raise a number to a power, you use the exponential operator, which is a caret (^). Exponents greater than one indicate a number raised to a power. Fractional exponents indicate a root, and negative exponents indicate a fraction. The following is the syntax for using the exponential operator:

answer = number1 ^ exponent

The equations in the following table show several common uses of exponents. The operation performed by each equation is also indicated:

Sample Exponent Function Performed
3 ^ 2 = 9 This is the square of the number.
9 ^ 0.5 = 3 This is the square root of the number.
2 ^ -2 = 0.25 A fraction is obtained by using a negative exponent.

Operator Precedence Many expressions contain some combination of the operators we've just discussed. In such cases, it's important to know in what order Visual Basic processes the various types of operators. For example, what's the value of the expression 4 * 3 + 6 / 2 ? You might think that the calculations would be performed from left to right. In this case, 4 * 3 is 12; 12 + 6 is 18; 18 / 2 is 9. However, Visual Basic doesn't necessarily process expressions straight through from left to right. It follows a distinct order of processing known as operator precedence.

Simply put, Visual Basic performs subsets of a complex expression according to the operators involved, in this order:

Within a subset of an expression, the components are processed from left to right. When all subset groups have been calculated, the remainder of the expression is calculated from left to right.

In the previous example (4 * 3 + 6 / 2), the multiplication and division portions (4 * 3, which is 12, and 6 / 2, which is 3) would be calculated first, leaving a simpler expression of 12 + 3, for a total of 15.

An important note is that normal operator precedence can be overridden by using parentheses to group sub-expressions that you want to be evaluated first. Multiple nested levels of parentheses can be used. Visual Basic calculates sub-expressions within parentheses first, innermost set to outermost set, and then applies the normal operator precedence.


CAUTION: Understanding operator precedence is crucial to making sure your programs evaluate expressions the way that you expect. For example, if you wanted to calculate the average of two test scores, you might write this line of code:

sgAvgScore = inTest1 + inTest2 / 2

This line of code might look right, but Visual Basic's calculation won't be correct. Because the division operator has a higher precedence than the addition operator, the sub-expression inTest2 / 2 will be calculated first and then added to inTest1. This is obviously incorrect. You can avoid this problem by using parentheses to control the flow of evaluation:

sgAvgScore = (inTest1 + inTest2) / 2

This expression will be calculated properly by evaluating the sum of inTest1 + inTest2 first and then dividing the sum by 2. If inTest1's value was 97 and inTest2's value was 88, the expression would be evaluated as (97 + 88) / 2, or 185 / 2, which would store the correct result of 92.5 in sgAvgScore. Leaving out the parentheses would have resulted in an undesired answer (following the rules of operator precedence) of 97 + 88 / 2, or 97 + 44, or 141!


Visual Basic's Operator Precedence help screen has a very good discussion of the topic, including how the precedence extends to comparison operators and logical operators.

Working with Strings

Visual Basic supports only one string operator, the concatenation operator. This operator is used to combine two or more strings of text, similar to the way the addition operator is used to combine two or more numbers. The concatenation operator is the ampersand symbol (&). When you combine two strings with the concatenation operator, the second string is added directly to the end of the first string. The result is a longer string containing the full contents of both source strings.

The concatenation operator is used in an assignment statement as follows:

newstring = stringexpr1 & stringexpr2 [& stringexpr3]

In this syntax, newstring represents the variable that will contain the result of the concatenation operation. stringexpr1, stringexpr2, and stringexpr3 all represent string expressions. These can be any valid strings, including string variables, literal expressions (enclosed in quotes), or functions that return a string. The ampersand between a pair of string expressions tells Visual Basic to concatenate the two expressions. The ampersand must be preceded and followed by a space. The syntax shows an optional second ampersand and a third string expression. You can combine any number of strings with a single statement. Just remember to separate each pair of expressions with an ampersand.


NOTE: If you are working on converting programs from an older version of Visual Basic, you might find strings combined using the plus sign operator. This was prevalent in versions of Visual Basic prior to version 4, as well as in older BASIC languages. While Visual Basic still supports the plus sign operator, in case this operator is present in older code that you are modifying, I recommend that you use the ampersand for any work that you do to avoid confusion with the mathematical addition operation.

Listing 8.2 shows how the concatenation of strings would be used in a simple program to generate mailing labels. The fields from the different text boxes are combined to create the different lines of the mailing label. The form for this program is shown in Figure 8.6.

Listing 8.2 Mailing.Frm--String Concatenation Used in Mailing Labels

stFirst$ = txtFirst.Text
stLast$ = txtLast.Text
stAddr$ = txtAddress.Text
stCity$ = txtCity.Text
stState$ = txtState.Text
stZip$ = txtZip.Text
If optTitle1.Value Then stTitle$ = "Mr. "
If optTitle2.Value Then stTitle$ = "Mrs. "
If optTitle3.Value Then stTitle$ = "Miss "
If optTitle4.Value Then stTitle$ = "Ms. "
stLine1$ = stTitle$ & stFirst$ & " " & stLast$
stLine3$ = stCity$ & ", " & stState$ & "  " & stZip$
picOutput.Print stLine1$
picOutput.Print stAddr$
picOutput.Print stLine3$

FIG. 8.6
The mailing label application shows how strings are combined for display or printing.

Making Decisions in Your Program

Many of the statements in your programs will be assignment statements, but there are other statements that are important for handling more complex tasks. These statements are known collectively as control statements. Without control statements, your program would start at the first line of code and proceed line by line until the last line was reached. At that point, the program would stop.

One type of control statement is the decision statement. These statements are used to control the execution of parts of your program, based on conditions that exist at the time the statement is encountered. There are two basic types of decision statements: If statements and Select Case statements. Each is covered in this section.

Using the If Statement

For many decisions, you will want to execute a statement (or group of statements) only if a condition is True. There are two forms of the If statement for handling True conditions--the single line If statement and the multiple line If statement. Each uses the If statement to check a condition. If the condition is True, the program runs the commands associated with the If statement. If the condition is False, the commands are skipped, and any Else portion of the If statement block is executed.

The Single Line If Statement The single line If statement is used to perform a single task when the condition in the statement is True. The task can be a single command, or you can perform multiple commands by calling a procedure. The following is the syntax of the single line If statement:

If condition Then command

The argument condition represents any type of logical condition, which can be any of the following:

The argument command represents the task to be performed if the condition is True. This can be any valid Visual Basic statement, including a procedure call. The following code shows how an If statement would be used to print a person's name if his or her fortieth birthday occurred during a particular year. This code is retrieving information from a database to perform the comparison and get the names (Figure 8.7 shows the output list that might be generated):

inCompYear = Val(txtYear.Text) - 40
inBirthYear = Year(Members("BirthDate"))
If inBirthYear = inCompYear Then Picture1.Print Members("FullName")

FIG. 8.7
You can use comparisons to print the names of 40-year-olds.

Multiple Commands for the Condition If you need to execute more than one command in response to a condition, you can use the multiple line form of the If statement. This is also known as a block If statement. This form bounds a range of statements between the If statement and an End If statement. If the condition in the If statement is True, all the commands between the If and End If statements are run. If the condition is False, the program skips to the first line after the End If statement. Listing 8.3 shows how a block If statement is used to credit an invoice in a membership program. The program asks the user if a credit should be issued and executes the block of code if the user answers yes.

Listing 8.3 CREDIT.TXT--Making Decisions in Code

If Retval = vbYes Then
   OrgCanc.Close
   Set OrgCanc = MemDb.OpenRecordset("Dues", dbOpenTable)
   OrgCanc.Index = "InvoiceID"
   OrgCanc.Seek "=", InvcID
   TotDues = OrgCanc("AmountDue") - TotDues
   If TotDues < 0 Then
      TotDues = 0
      OrgCanc.Edit
      OrgCanc("AmountDue") = TotDues
      OrgCanc("LastUpdate") = Date
      OrgCanc("UpdateBy") = UserID
      OrgCanc.Update
   End If
End If


TIP: If you have a lot of commands between the If and End If statements, you might want to repeat the condition as a comment in the End If statement, as in this example:

If crTotalSales > crProjectedSales Then
        `
        ` A bunch of lines of code
        `
    Else
        `
        ` Another bunch of lines of code
        `
    End If `crTotalSales > crProjectedSales

This makes your code easier to read.


Working with the False Condition

Of course, if a condition can be True, it can also be False; and there may be times when you want code to execute only on a False condition. There may be other times when you want to take one action if a condition is True and another action if the condition is False. This section looks at handling the False side of a condition.

Using the Not Operator One way to execute a statement, or group of statements, for a False condition is to use the Not operator. The Not operator inverts the actual condition that follows it. If the condition is True, the Not operator makes the overall expression False, and vice versa. Listing 8.4 uses the operator to invert the value of the NoMatch property of a recordset. NoMatch is True if a record is not found in a search operation, and it is False if the search succeeds. Because the program can operate on a record only if it is found, the Not operator and NoMatch property are used as the condition of the If statement.

Listing 8.4 FALSEIF.TXT--Handling a False Condition

If Not OrgCanc.NoMatch Then
    OrgCanc.Edit
    OrgCanc("Renewed") = False
    OrgCanc("LastUpdate") = Date
    OrgCanc("UpdateBy") = UserID
    OrgCanc.Update
End If

Handling True and False Conditions The other way of handling False conditions allows you to process different sets of instructions for the True or False condition. You can handle this "fork in the road" in Visual Basic with the Else part of the If statement block. To handle both the True and False conditions, you start with the block If statement and add the Else statement, as follows:

If condition Then
   statements to process if condition is True
Else
   statements to process if condition is False
End If

The If and End If statements of this block are the same as before. The condition is still any logical expression or variable that yields a True or False value. The key element of this set of statements is the Else statement. This statement is placed after the last statement to be executed if the condition is True, and before the first statement to be executed if the condition is False. For a True condition, the program processes the statements up to the Else statement and then skips to the first statement after the End If. If the condition is False, the program skips the statements prior to the Else statement and starts processing with the first statement after the Else.


NOTE: If you want to execute code for only the False portion of the statement, you can just place code statements between the Else and End If statements. You are not required to place any statements between the If and Else statements.

Listing 8.5 shows how both parts of an If statement are used to handle different handicap calculations for men and women in a golf handicap program.

Listing 8.5 HANDICAP.TXT--Handicap Calculation Using Conditional Statements

If slope = 1 Then
   avgdif! = totdif! / bstscr
   hcidx! = Int(avgdif! * 0.96 * 10) / 10
   hcp% = Int(hcidx! + 0.5)
Else
   hcidx! = 0!
   avgdif! = Int(totdif! / bstscr * 100) / 10
   hcp% = 0
   Call Hcpchrt(avgdif!, hcp%)
End If
` Get member record
Get #1, pnt, mmbr
` Set maximum handicap for gender
If mmbr.gendr = "M" Then
   If hcp% > 36 Then hcp% = 36
Else
   If hcp% > 40 Then hcp% = 40
End If

Working with Multiple If Statements

In the previous sections, you saw the simple block If statements, which evaluate one condition and can execute commands for either a True or a False condition. You can also evaluate multiple conditions with an additional statement in the block If. The ElseIf statement lets you specify another condition to evaluate whether or not the first condition is False. Using the ElseIf statement, you can evaluate any number of conditions with one If statement block. Listing 8.6 shows how a series of ElseIf conditions could be used to determine the grade distribution in a class.

Listing 8.6 GRADESIF.TXT--Grade Distribution with Multiple If Statements

For I = 0 To numstd
    If inpGrades(I) >= 90 Then
        GradeDist(4) = GradeDist(4) + 1
    ElseIf inpGrades(I) >= 80 Then
        GradeDist(3) = GradeDist(3) + 1
    ElseIf inpGrades(I) >= 70 Then
        GradeDist(2) = GradeDist(2) + 1
    ElseIf inpGrades(I) >= 60 Then
        GradeDist(1) = GradeDist(1) + 1
    Else
        GradeDist(0) = GradeDist(0) + 1
    End If
Next I

The preceding code works by first evaluating the condition in the If statement. If the condition is True, the statement (or statements) immediately following the If statement is executed; and then the program skips to the first statement after the End If statement.

If the first condition is False, the program skips to the first ElseIf statement and evaluates its condition. If this condition is True, the statements following the ElseIf are executed, and control again passes to the statement after the End If. This process continues for as many ElseIf statements as are in the block.

If all the conditions are False, the program skips to the Else statement and processes the commands between the Else and the End If statements. The Else statement is not required.

Using Select Case

Another way to handle decisions in a program is to use the Select Case statement. This allows you to conditionally execute any of a series of statement groups based on the value of a test expression, which can be a single variable or a complex expression. The Select Case statement identifies the test expression to be evaluated. Then a series of Case statements specifies the possible values. If the value of the test expression matches the value (or values) indicated in the Case statement, the commands after the Case statement are executed. If the value does not match, the program proceeds to the next Case statement. The Select Case structure is similar to a series of If/Then/ElseIf statements. The following lines of code show the syntax of the Select Case block:

Select Case testvalue
   Case value1
      statement group 1
   Case value2
      statement group 2
End Select

The first statement of the Select Case block is the Select Case statement itself. This statement identifies the value to be tested against possible results. This value, represented by the testvalue argument, can be any valid numeric or string expression, including literals, variables, or functions.

Each conditional group of commands (those that are run if the condition is met) is started by a Case statement. The Case statement identifies the expression to which the testvalue is compared. If the testvalue is equal to the expression, the commands after the Case statement are run. The program runs the commands between the current Case statement and the next Case statement or the End Select statement. If the testvalue is not equal to the value expression, the program proceeds to the next Case statement.

The End Select statement identifies the end of the Select Case block.


NOTE: Only one case in the Select Case block is executed for a given value of testvalue, even if more than one of the Case statements match the value of the test expression.


CAUTION: The testvalue and value expressions must represent the same data type. For example, if the testvalue is a number, the values in the Case statements also must be numbers.

The simplest form of the Select Case block uses only a single value for the comparison expression. You might use this type of statement to handle a payroll calculation where you have a single pay rate for each job grade. Figure 8.8 shows a form that could be used to calculate pay for hourly employees with various job classifications. The code to perform the calculation is shown in Listing 8.7.

Listing 8.7 PAYROLL.FRM--Payroll Calculation with the Select Case Statement

totpay = 0.0
paygrd = Val(txtGrade.Text)
payhrs = Val(txtHours.Text)
Select Case paygrd
    Case 1
        totpay = payhrs * 4.35
    Case 2
        totpay = payhrs * 4.85
    Case 3
        totpay = payhrs * 5.35
    Case 4
        totpay = payhrs * 5.85
End Select
txtPay.Text = totpay

FIG. 8.8
A payroll calculator can use a Select Case structure to handle different wages for different classes of employees.

Case statements within a Select Case structure can also handle lists, ranges, and comparisons of values in addition to discrete values. Note the use of Case Is < 0, Case 1 to 9, and Case Is > 50 in this example:

    inQtyOrdered = Val(txtQuantity)
    Select Case inQtyOrdered
        Case Is < 0 `note use of comparison
            MsgBox "Order quantity cannot be negative!", vbExclamation
            Exit Sub
        Case 1, 2, 3 `note use of list
            sgDiscount = 0
        Case 4 To 9 `note use of range
            sgDiscount = 0.03
        Case 10 To 49
            sgDiscount = 0.08
        Case Is > 50
            sgDiscount = 0.1     End  Select

The preceding examples work fine if your test variable matches one of the conditions in a Case statement. But how do you handle other values that are outside the ones for which you tested? You can have your code do something for all other possible values of the test expression by adding a Case Else statement to your program. The Case Else statement follows the last command of the last Case statement in the block. You then place the commands that you want executed between the Case Else and the End Select statements.

You can use the Case Else statement to perform calculations for values not specifically called out in the Case statements. Or you can use the Case Else statement to let users know that they entered an invalid value. Listing 8.8 shows how to add a message to let the user know that an invalid code was entered in the payroll program shown earlier.

Listing 8.8 PAYROLL.FRM--Handling Invalid Input with the Case Else Statement

totpay = 0#
paygrd = Val(txtGrade.Text)
payhrs = Val(txtHours.Text)
Select Case paygrd
    Case 1
        totpay = payhrs * 4.35
    Case 2
        totpay = payhrs * 4.85
    Case 3
        totpay = payhrs * 5.35
    Case 4
        totpay = payhrs * 5.85
    Case Else
        MsgBox Str(paygrd) & " is an invalid pay code."
End Select
txtPay.Text = totpay

Working with Loops

The other major type of control statement is the loop. Loops are used to perform repetitive tasks in your program. There are two main types of loops that are supported by Visual Basic--counter loops and conditional loops. Counter loops are used to perform a task a set number of times. Conditional loops are used to perform a task while a specified condition exists or until a specified condition exists. Each of these types of loops is discussed in this section.

For Loops

A counter loop is also known as a For loop, or a For/Next loop. This is because the ends of the loop are defined by the For statement and the Next statement. At the beginning of a For loop, you define a counter variable, as well as the beginning and end points of the variable's value, and optionally the Step value, or the amount it is to be increased or decreased after each pass through the loop. The first time the loop is run, the counter variable is set to the value of the beginning point. Then after each time the program runs through the loop, the value of the counter is incremented by the Step value and checked against the value of the end point. If the counter is larger than the end point, the program skips to the first statement following the loop's Next statement.


CAUTION: If the beginning value of the loop is greater than the ending value, the loop does not execute at all. The exception to this is if you set up the loop to count backward, by setting the Step value to a negative number. In that case, the loop will execute until the counter variable is less than the end point.


TIP: For ease of reading your program, it is good practice to include the variable name in the Next statement. This is especially important in nested loops.


CAUTION: Although you can use any numeric variable for the counter, you need to be aware of the limits of variable types. For example, trying to run a loop 40,000 times using an integer variable will cause an error during execution because an integer has a maximum value of 32,767.

Listing 8.9 illustrates the use of several For loops to set the initial values of control arrays for a membership data-entry screen. The effect of the code is to create blank data-entry areas for a new member to be added. The form, after the code is run, is shown in Figure 8.9.

Listing 8.9 FORLOOP.TXT--Using For Loops to Initialize Variables

Dim I As Integer
`Clear the text from all text boxes
For I = 0 To 22
    txtMember(I).Text = ""
Next I
`Set each combo box to have no item selected
For I = 0 To 1
    cboMember(I).ListIndex = -1
Next I
`Clear the text from the Phone masked edit controls
For I = 0 To 3
    mskPhone(I).Text = ""
Next I
`Clear the text from the Date masked edit controls
For I = 0 To 1
    mskDate(I).Text = "  /  /  "
Next I


CAUTION: Never reset the value of the counter variable inside a For loop. Doing so can cause an infinite loop.

FIG. 8.9
A series of For loops is used to initialize control arrays.

Typically, you will want your For loop to run through all the values of the counter variable. However, there might be times when you want the loop to terminate early. To do this, simply place an Exit For statement at the point in your loop where you want the loop to stop. The Exit For statement is typically associated with an If statement (see Listing 8.10).

Listing 8.10 EXITFOR.TXT--Exiting a Loop Early

Private Sub cmdSearch_Click()
txtResults.Text = "No match was found."
For Icnt = 1 To 30
    iloc = InStr(1, NameArray(Icnt), findstr, 1)
    If iloc > 0 Then
        txtResults.Text = NameArray(Icnt)
        Exit For
    End If
Next Icnt
End Sub

This code is used to search an array for a particular name. When the name is found, it is not necessary to continue searching the rest of the elements of the array. Therefore, the Exit For is used to terminate the loop.


NOTE: As you have seen in this example and in others in the book, arrays and For loops are often used together. A For loop provides an easy way of looking at or processing each element of an array because the counter variable can be used as the array index.

Do Loops

The key feature of a conditional loop is, of course, the condition. The condition is any expression that can return either a True or a False value. This can be a function, such as EOF; the value of a property, such as the Value property of an Option button; or an expression, such as numval < 15. There are two basic types of conditional loops--a Do While loop, which repeats while the condition is True, and a Do Until loop, which repeats until the condition is True.

Using Do While Statements The keyword While in the Do While statement tells the program that the loop will be repeated while the condition expression is True. When the condition in a Do While loop becomes false, the program moves on to the next statement after the Loop statement.

There are two forms of the Do While loop. The difference between the two is the placement of the condition. The condition can be placed either at the beginning of the loop or at the end.

The first form of the Do While loop places the condition at the beginning of the loop, as shown in Listing 8.11. This code repeats the steps while there are available records in the recordset.

Listing 8.11 DOLOOP.TXT--Processing Database Records with a Do Loop

Do While Not OrgRenew.EOF
    OrgRenew.Edit
    If OrgRenew("Renew") Then
        OrgRenew("NumYears") = 0
        OrgRenew("Renew") = False
    Else
        OrgRenew("NumYears") = 1
        OrgRenew("Renew") = True
    End If
    OrgRenew.Update
    OrgRenew.MoveNext
Loop

By placing the While condition clause in the Do statement, you tell the program that you want to evaluate the condition before you run any statements inside the loop. If the condition is True, the repetitive statements between the Do statement and the Loop statement are run. Then the program returns to the Do statement to evaluate the condition again. As soon as the condition is False, the program moves to the statement following the Loop statement.

Both the Do and the Loop statements must be present.

With this form of the loop, the statements inside the loop might never be run. If the condition is False before the loop is run the first time, the program just proceeds to the statements after the loop.

To run the Do While loop at least once, the second form of the Do While loop must be used. This form of the loop places the condition in the Loop statement. This tells the program that you want the loop to run at least once and then evaluate the condition to determine whether to repeat the loop.


CAUTION: Do not put the While condition clause in both the Do and the Loop statements because this will cause an error when you try to run your program.


NOTE: If you are working on code that was developed by someone else, you might find a loop that starts with a While statement and ends with a Wend statement. This type of loop works the same as a Do While loop with the While clause in the Do statement. Visual Basic still supports a While...Wend loop, but I recommend that you use the Do While type of loop because it is more flexible.

Using a Do Until Statement The Do Until loop is basically the same as the Do While loop except that the statements inside a Do Until loop are run only as long as the condition is False. When the condition becomes True, the loop terminates. As with the Do While loop, there are two forms of the Do Until loop--one with the condition in the Do statement and one with the condition in the Loop statement. If you place the condition in the Do statement, it is evaluated before the statements in the loop are executed. If you place the condition in the Loop statement, the loop is run at least once before the condition is evaluated.

A frequent use of the Do Until statement is in reading and processing data files. A loop starts with the first record of the file and processes each record until the end of file is reached. Listing 8.12 uses a loop to load all the authors from the BIBLIO.MDB sample database into a list box. Figure 8.10 shows the results of the program.

Listing 8.12 AUTHORS.FRM--Using Do Until to Process a Database

Private Sub cmdListAuthors_Click()
    Dim OldDb As Database, OldWs As Workspace, OldTbl As Recordset
    Set OldWs = Workspaces(0)
    Set OldDb = OldWs.OpenDatabase("C:\VB\BIBLIO.MDB")
    Set OldTbl = OldDb.OpenRecordset("Authors", dbOpenTable)
    OldTbl.MoveFirst
    Do Until OldTbl.EOF
        LstAuthors.AddItem OldTbl("Author")
        OldTbl.MoveNext
    Loop
    OldTbl.Close
    OldDb.Close
End Sub


TIP: Indenting your code inside a loop or other structure (such as an If/Then/Else block or Select Case/End Select block) makes the code easier to read. To indent a line of code, press Tab at the beginning of the line. When you press Enter at the end of the line, the indention remains at the same point. Try to match up beginning and ending points of code blocks, as has been done in many of this book's code examples.

FIG. 8.10
The list was set up by using a Do Until loop to read through database records until the end of the data was reached.

Making Your Program Bug-Free

No matter how long you have been developing programs or how good you are at what you do, you'll still have errors crop up in your program. It's easy to make mistakes. All it takes is a simple typo to make your program refuse to run. This is called a syntax error. There are also logic errors, where your program runs but it just doesn't do what you want it to do.

Because you will make errors, one of the keys to successful program development is the ability to track down these errors, or bugs as they are often known, and fix them. Visual Basic provides you with a number of tools to help you find and eliminate bugs. These tools provide you with the following capabilities:

How to Avoid Syntax Errors

One of the best ways to eliminate bugs is to prevent them in the first place. Visual Basic provides you with a syntax checker that checks each line of code as you enter it. If you have an error in the code, the checker alerts you to the problem as soon as you move to another line. The syntax checker looks for misspelled keywords and missing items in a statement, such as a parenthesis or a keyword. When you have a syntax error, Visual Basic shows the erroneous line in red and displays a message telling you the cause of the problem. Figure 8.11 shows how the syntax checker can alert you to a missing part of an If statement.

FIG. 8.11
The syntax checker is reporting an incomplete statement.

The syntax checker is turned on when you first install Visual Basic. However, if for some reason it has been turned off, you can activate it by checking the Auto Syntax Check box in the Editor Options dialog box (see Figure 8.12). Access this dialog box by choosing Tools, Options.

FIG. 8.12
Automatic Syntax Checking is one of many options that can be selected for Visual Basic's editor.

Another great feature of Visual Basic is the new Auto List Members code-completion assistant. This assistant helps you by popping up the syntax of Visual Basic functions and by providing you with property lists for any object used in the code. While this feature is designed to help speed your coding, it also helps cut down on errors. Figure 8.13 shows how a property list for a form is displayed after you enter a dot after the form's name in the code line.

Another thing that Visual Basic does for you in the Code window is properly capitalizes keywords and displays them using blue text. This gives you another visual indication that you have correctly entered a command.

FIG. 8.13
The code-completion assistant helps eliminate programming errors.


TIP: If you enter all your control names and properties in lowercase and spell them correctly, Visual Basic capitalizes them. This indicates that you didn't make any typos.


TIP: If you don't like the default colors that are used in the Code Editor, you can change them by using the Editor Format tab on the Options dialog box.

What Happens When an Error Occurs

While you are running your code from the Visual Basic development environment, you might encounter errors in your program. These errors can be the runtime errors listed in the Help files or the program manuals. When you encounter an error, you are shown an error message like the one in Figure 8.14. The error message gives you the error number and a text description of the problem.

FIG. 8.14
A missing file leads to a runtime error. Notice that the message box has several command buttons on it.

One of these buttons, the Debug button, provides you with the first line of assistance in tracking down errors in your code. If you choose the Debug button, you are shown the code-editing window with the offending line highlighted by a yellow highlight bar and arrow (see Figure 8.15).

FIG. 8.15
By choosing Debug from the error message box, you can attempt to pinpoint the cause of the error.

Sometimes the error is obvious, such as mistyping a variable name or declaring a variable as the wrong type. Ot h er times, though, you need to dig deeper to find the source of the error.

How the Debugging Environment Works

Visual Basic's debugging environment provides you with the tools you need to locate and eliminate errors in your program. These tools are easily accessible from the Debug toolbar. This toolbar, shown in Figure 8.16, provides you with quick access to all the information windows of the debug environment and all of the functions for stepping through your code. Table 8.4 describes each of the Debug toolbar buttons. The Debug toolbar is accessible by choosing View, Toolbars, Debug; or by right-clicking any visible toolbar and selecting Debug from the toolbar list.

FIG. 8.16
The Debug toolbar organizes the debug functions in a convenient location.

Table 8.4 Debug Toolbar Buttons

Button

Name Function

Start Begins program execution, or continues if program has been paused.

Break Pauses program execution by placing the program in "break mode."

End Stops a running program.

Toggle Breakpoint Toggles the current code line as a "breakpoint;" the program will pause and enter break mode before the line is executed.

Step Into When in break mode, causes the next line of code to be executed, even if it means stepping into another procedure or function.

Step Over When in break mode, causes the next line of code to be executed; if the next line is a procedure or function call, the entire procedure or function will be executed before the program is paused again.

Step Out When in break mode, causes the remainder of the current procedure or function to be executed before the program is paused again.

Locals Window Displays the Locals window, which lists all variables that have been defined in the active procedure, along with their current values.

Immediate Window Displays the Immediate window, which allow you to manually execute lines of code while in break mode.

Watch Window Displays the Watch window, where can add "watches" to allow you to keep an eye on how the values of your program's variables change as the program runs.

Quick Watch Displays the Quick Watch dialog box, which shows you the current value of the selected variable or expression. You can add the expression to the Watch window from here.

Call Stack Displays the Calls dialog box, which contains a list of all procedures and functions that are currently running but have not yet finished executing.

Let's take a closer look at the tools at your disposal.

How to Determine the Value of a Variable

Often when you encounter an error, it is because a variable contains a value that you did not expect. It might be that a variable had a zero value and was then used in a division operation. Or a variable that was supposed to contain the name of a file somehow had a number stored in it. You can also see how a variable changes as the program runs. Watching the change in a variable's value, or the lack of a change, is one of the major factors in finding many program errors, including infinite loops.

To debug your program, you have to be able to determine the values of the variables that are used in the program at different points in the execution. Visual Basic provides you with several basic methods of checking the values of variables, including the Watch window, the Locals window, Quick Watches, and Auto Data Tips.

Using the Watch Window One way to view the value of variables is with the Watch window. This window shows you the expression you are watching, the value of the expression, the type of watch, and the procedure where the expression is being evaluated (see Figure 8.17). By using the Watch window, you can look at only the variables or expressions that interest you. You can access the Watch window from the Debug toolbar or by choosing View, Watch Window.

FIG. 8.17
The Watch window shows the value of variables and expressions you define.

To set up a variable or expression for viewing, you have to add it to the Watch window. To do this, choose Debug, Add Watch. This brings up the Add Watch dialog box (see Figure 8.18). This dialog box allows you to enter the name of the variable to observe in the Expression field.

FIG. 8.18
The Add Watch dialog box lets you set up variables to observe during program execution.

The Add Watch dialog box also allows you to specify where you want to observe the variable. These context settings let you observe the value of the variable during the entire program or just during a specific procedure.

The Watch Type options let you decide whether to just look at the value of the variable or to break (pause the execution of the code) when a specific condition exists. You can choose to have the program pause every time a variable changes or when the watch expression is True. This way, you can determine when a variable reaches or exceeds a specific value. To use this type of watch, the expression must be a Boolean variable or a logical expression.

If at a later time you want to edit the watch expression, you can right-click the mouse in the Watch window and select the Edit Watch item from the pop-up window. This brings up the Edit Watch dialog box, which is basically the same as the Add Watch dialog box, but adds a command button that allows you to delete the watch.

Using the Locals Window Sometimes it is easier to just check the values of all the variables in a procedure than it is to try to guess which variable has the problem. This is easily done with the Locals window, which is viewed by clicking the Locals Window button on the Debug toolbar, or by choosing View, Locals Window. This window, shown in Figure 8.19, lists all the variables declared in the current procedure along with their current values. Variables that are declared outside the current procedure are not shown.

FIG. 8.19
The Locals window lets you look at all the declared variables in a procedure.

Using Quick Watches and Auto Data Tips If you only need to find out the current value of a variable, but do not need to track its value as the program progresses, you can use a quick watch. A quick watch displays a dialog box that shows the name of the variable, its current value, and the procedure in which it is currently being used (see Figure 8.20).

FIG. 8.20
A quick watch provides a snapshot look at a variable.

To use a quick watch, highlight a variable in the Code window while the program is paused. Then you can click the Quick Watch button on the Debug toolbar or choose Debug, Quick Watch to show the dialog box. You can also run a quick watch by pressing Shift+F9. Note that the Quick Watch dialog box has an option to add the watch to the Watch window that we described previously.

Another way to quickly view the value of a variable or an object property is to rest the mouse pointer on the variable in the Code window. After the mouse is still for a second or two, the value pops up in a little box similar to a ToolTip (see Figure 8.21). This handy tool is known as Auto Data Tips. You can also select an entire expression and rest the mouse pointer on it to see the evaluated value of the expression.

FIG. 8.21
Resting the mouse pointer on App.Path in break mode causes Auto Data Tips to display its value in a ToolTip.

Running Commands

Another part of the Debug environment is the Immediate window. This window allows you to enter program commands, which will be executed as soon as you press Enter. From this window, you can print or even change the value of a variable using an assignment statement. You can also use commands to change the environment of your program, such as the fonts on a form or the color of text in a text box.

The Immediate window allows you to enter any single-line command. Loops and block statements (If blocks and Select Case blocks) are not allowed. If you issue the print command from the Immediate window, the results are printed on the line following the command. This provides another way to view the contents of a variable. Figure 8.22 shows how the Immediate window can be used to find the value of a variable or set a variable. If the Immediate window is not open, you can access it by clicking the Immediate Window button on the Debug toolbar, or by choosing View, Immediate Window.

FIG. 8.22
You can execute many types of statements in the Immediate window.

Another Debugging Tool

One final item you might need in debugging is the Call Stack window (see Figure 8.23), which can be viewed by clicking the Call Stack button on the Debug toolbar, by choosing View, Call Stack, or by pressing Ctrl+L. This window tells you which procedure is currently executing. It also shows the entire string of procedure calls from the initial procedure to the current one. These calls are listed from the most recent procedure (at the top of the list) to the initial calling procedure (at the bottom of the list). This list helps you determine how you got to the current point. This way, you will know if a procedure is being accessed from an area that you don't want.

FIG. 8.23
The Call Stack shows you the procedures that led up to the current procedure.

Pausing the Program's Execution

Whenever Visual Basic encounters an error, it automatically pauses the execution of the program by placing it in break mode. There also might be times that you want to pause a program when there is no error. You would do this to check the value of variables at a specific point.

There are several ways to pause a program without an error having occurred:

Setting a watch point to pause the program was discussed previously in the "Using the Watch Window" section; clicking the Break button and pressing Ctrl+Break are self-explanatory. Therefore, let's concentrate on setting a breakpoint in the code.

A breakpoint in code is set while you are in design mode. To set the breakpoint, you must have the Code window open and be in the procedure containing the statement where you want the break to occur. At this point, you can set the breakpoint in one of these ways:

When a breakpoint is set, the code statement is highlighted as shown in Figure 8.24.

Each of the methods for setting the breakpoint actually toggles the breakpoint status of the line. This means that if the statement is not a breakpoint, it becomes one. Conversely, if it is already a breakpoint, the breakpoint is removed.

FIG. 8.24
A breakpoint enables you to pause the code at a specific statement.

Tracing Through Your Code

In the previous sections, you learned how to pause the code; but for debugging to be effective, you have to be able to execute program statements and watch their effects.

After the execution of the program has stopped, you have several options for continuing the execution. You can do any of the following:

To execute a single statement or group of statements, you need to be in the code-editing window. To execute the program one statement at a time, you can press the F8 key, or click the Step Into button on the Debug toolbar. This executes the statement currently highlighted by the highlight bar and moves the box to the next statement. By repeatedly pressing the key, you move through the code a step at a time.

This method is extremely useful for determining which part of a conditional statement is being accessed. When the program encounters an If or Select Case statement, it evaluates the condition and moves immediately to the proper part of the block for the condition. For example, if the condition in an If statement is False, execution of the program immediately moves to the Else portion of the If block.

If the current statement contains a procedure call, pressing F8 or clicking the Step Into button causes you to go to the first step of the procedure. If you want to run the entire procedure and return to the next line in the current program, press Shift+F8 or click the Debug toolbar's Step Over button. Also, if you have stepped into the procedure and want to run the rest of the procedure, you can click the Debug toolbar's Step Out button or press Ctrl+Shift+F8. This runs the remaining lines of code in the procedure and pauses again at the statement after the procedure call.

If you're fairly certain that a block of statements is error-free, you might want to execute the entire block at once instead of executing each statement individually. You can accomplish this by placing the cursor on the statement where you next want to pause the program execution and pressing Ctrl+F8. This method is useful for executing an entire loop after you have determined that the loop is not part of the problem.

Finally, when you think you have resolved the problem and want to finish executing the program, you can press the F5 key to allow the program to continue running normally. You can also do this by pressing the Continue button (which is the break-mode version of the Run button) on the Standard or Debug toolbar.

From Here...

This chapter has provided you with an overview of programming in Visual Basic. You have learned how to handle mathematical operations, string manipulations, decisions, and loops in your code. You have also seen how to use the debugging environment to eliminate errors in your code. For some more material on programming, refer to the following chapters:


Previous chapterNext chapterContents


Macmillan Computer Publishing USA

© Copyright, Macmillan Computer Publishing. All rights reserved.