VB Notes
VB Notes
AddNum is a simple addition program that shows you how to use variables.
While the data is being processed in your program, it's stored temporarily in variables.
Think of a variable as a cup that can hold various amounts of jelly beans; you never know
how many jelly beans are in the cup at any given time unless you look in the cup. The
same is true for a variable. A variable can hold a different value at different times. You
programmatically look into it to find out its value.
You use variables when you know that you'll have to deal with a quantity at some point
but don't know its present value--such as the balance of your checking account. You
know the account's balance today, but you have no idea what the balance will be in a
week.
Declaring Variables
You create (that is, declare) a variable by using the following form:
Understanding keywords
In this syntax,
Dim is the keyword that tells Visual Basic that you want to declare a variable.
VarName is the name of the variable.
As is the keyword that tells Visual Basic that you're defining the data type for the
variable.
DataType is the data type of the variable.
Thus, the following example creates a variable, i, that's of data type Integer:
Dim i as Integer
Listing 7.1 shows the event procedure for the Click() event of the cmdAdd button. Three
variables--x, y, and z (on lines 3, 6, and 9)--are declared. These variables are of type
Integer. (Data types are discussed later in the chapter. For now, realize that you are
making variables that will accommodate numbers. Also, if you type a letter such as a in a
text box, the code won't work because it's expecting a number. Preventing this sort of
error is addressed at the end of this chapter.) For more information about avoiding and
finding errors in your code see Chapter 21, "Debugging Your Applications."
Commenting code
Notice that some lines of code begin with an apostrophe (`), which tells
Visual Basic that everything on that line or following the apostrophe isn't
code and should be ignored by the compiler. Such a line of text offers
some remarks or information about what your programming intention is.
This is called commenting your code. Well-written code is heavily
commented. Commenting your code helps you remember your thinking
when you come back to your code at a later time. It also helps those who
must maintain your code after you've written it.
Naming Variables
When you declare a variable, you must give it a name. Returning to the cup analogy, if
you have two cups on a table that hold different amounts of jelly beans, you must be able
to distinguish between the cups to work with them. Naming makes each variable distinct
and easy to identify.
In naming a variable, you have tremendous flexibility. Variable names can be simple, or
they can be descriptive of the information they contain. For example, you could name a
counter variable i%, or you might want to use a more descriptive name, such as
NumberOfRedJellyBeansForBob or NumberOfJellyBeansForDorothy. Although you're
allowed great latitude in naming, you need to know about the following restrictions:
The name must start with a letter, not a number or other character.
The name can't contain a period.
The name must be unique within the current procedure or module (this restriction
depends on the scope of the name, which you'll learn about a little later).
The name can be no longer than 255 characters.
MyNum&
i%
iNumOne
strInputValue
Number2#
To make your code easy to read, your variable names should describe their task but, to
make your code easy to type, they should also be short. Many programmers use prefixes
on their variables to indicate the type of data stored and the scope of the variable. For
example, a prefix of g_int indicates a global or program-level variable that stores an
integer. Table 7.1 describes suggested prefixes you can use with your variables.
You can store almost anything in a variable. A variable can hold a number, a string of
text, or an instance of an object, including forms, controls, and database objects. This
chapter looks specifically at variables that store numbers, strings, and logical values.
You can use a variable to hold any type of information, but different types of variables
are designed to work efficiently with different types of information.
Returning to the earlier cup example, you might want to have a type of cup that can hold
only jelly beans, only cherries, or only nails. What the cup is supposed to hold greatly
influences how the cup is constructed. A cup that holds cherries might have little holes in
the bottom for water to pass through. A cup to hold nails might be made of tough material
so that the nails don't puncture or scratch it. The same is true of variables--the type of
variable must match the data it's going to hold. When you declare a variable to be of a
certain type, you're giving instructions to Visual Basic about how to build the variable to
accommodate the type of data that the variable will have to hold.
Table 7.2 presents the types of variables available in Visual Basic. The table also shows
the range of values that each variable can hold and the amount of memory required to
store the information in the variable (sort of like the cup size). Understanding memory
requirements is important if you want to optimize your code. To conserve system
resources, you should use variables with smaller memory requirements whenever
possible, but don't worry about optimizing code until you're comfortable with the concept
of creating and using variables.
Sizing variables
At some point you may wonder whether you're using a variable of the
right size, particularly with regard to numbers. A good rule of thumb is to
go with the larger variable size if you don't have a very good idea of what
the limit of your variable will be. For example, if you think that your
program at some point might be required to use numbers with decimals or
fractions, you might want to use Double and Single variable types instead
of Integers and Longs.
TABLE 7.2 Variables Store Many Types of Information
You know how to name a variable and what a variable can store, but how do you tell the
program what you want to store? In reality, you don't have to tell Visual Basic what a
variable will contain. Unlike other languages, Visual Basic doesn't require you to
specifically declare a variable before it's used. If a variable isn't declared, Visual Basic
uses a default data type known as a variant, which can contain any type of information.
Read more on variants in the following section.
It's a good idea to declare your variables before they're used. Declaring variables saves
you time in the long run and makes your code much more reliable.
Making Explicit Declarations
Explicit declaration means that you must use a statement to define a variable. Each of the
following statements can be used to explicitly declare a variable's type:
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 the 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 by commas. (The syntax shows only
two variables, but you can specify any number.)
VarType and VarType2 represent the type name of the respective variables. The type name
is a keyword that tells Visual Basic what kind of information will be stored in the
variable. The type can be one of those specified in Table 7.2 or a user-defined type.
What's a variant?
A variant is a data type that knows how to be any data type. If you declare
a variable to be of type variant, it can be an Integer, Double,
String...whatever. Variables have a definite use in advanced programming.
If you are a beginning programmer, however, you shouldn't use variants to
avoid the labor of learning to use the proper data type for the proper
situation.
As mentioned earlier, declaring a variable type is optional. If you include the variable
type, you must include the keyword As. If you don't include a variable type, the Variant
type (the default) is used. Using a variant for general information has two major
drawbacks, however: it can waste memory resources, and the variable type can produce
unpredictable default value behaviors, particularly with arrays.
The following code lines show the use of these declaration statements for explicitly
declared variables:
You can protect yourself. You can make the Visual Basic IDE force you to explicitly
declare a variable. All you need to do is enter the keywords Option Explicit in the first
line of the General section of your form or module. You can also configure the IDE to
automatically do this for you whenever you add a form or module.
3. Click OK.
Itís always preferable to configure the VB IDE to require you to declare your variables.
After you set Option Explicit, if you fail to declare a variable, you'll receive the message
Variable not defined when you try to compile your code. Visual Basic's integrated
debugger highlights the offending variable and halts the compilation of your program.
The benefit of this is that it helps you avoid code errors possibly caused by typographical
mistakes. For example, you might declare a variable with the following statement:
If, in a later statement, you mistype the variable name, Visual Basic will catch the error
for you. For example, the following statement would cause an error:
The code back in the section "Using Explicit Declarations" could be rewritten with type
suffixes as follows:
Private NumVal%
Private AvgVal%, Inputval#
Static CalcAverage!
Dim InputMsg$
Using suffixes to assign a type to your variables is a quick, handy way to declare a
variable. Also, using a suffix adds a new element of readability to your variable name.
For example, now when you run across the variable NumVal% in your code, you know
that the variable is of type Integer (from reading the suffix) and that its function is to be a
value for a number (from reading the variable name).
Using Strings
A string is a collection of characters. The following are examples of different string
values:
"Cheese"
"You have made an error!"
"a"
"July 4, 1776"
"75"
Notice that each collection of characters is enclosed by quotation marks (""). The
quotation marks are very important; they tell Visual Basic that the enclosed characters are
a string value. Characters not enclosed in quotation marks are considered to be a variable
or a part of the language.
You might find the string value "75" a bit baffling. You might think that it's a value for an
integer, but it's not. The following example illustrates the string-ness of "75":
Another use of strings that use numeric characters are ZIP codes and phone numbers.
Notice that declaring the following ZIP code and phone number as strings allows you to
use the - character:
strMyZipCode = "50311-0921"
strPhone = "1-515-555-1212"
Also, because they aren't number data types, you wouldn't and can't perform
mathematical operations on them, such as addition and multiplication.
Some beginning programmers have trouble with this concept; it takes a bit of getting used
to. If you look at the code in Listing 7.1, you'll see that the user's input into the text boxes
is treated as numeric string characters that must be converted to integers (lines 13 and
17). Chapter 12, "Working with Strings and Typecasting," provides a more detailed look
at this.
Most strings that you will use in your programs are of the type known as variable-length
strings, which can contain any amount of text up to 64,000 characters. As information is
stored in the variable, the size of the variable adjusts to accommodate the length of the
string. 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 discarded.
A fixed-length string variable can be declared only by using an explicit declaration of the
form, such as the following:
Therefore, to make a string, strMyString, that's always 128 characters long, you would
declare it as follows:
Notice that this declaration varies slightly 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 a fixed length. The final parameter, strlength, tells the
program the number of characters that the variable can contain.
In the beginning, you probably won't have much need for fixed-length strings. As you
advance, you will use them, particularly when it's time to program directly to Windows
with the Windows API (Application Programming Interface).
By default, a variable declared with a keyword such as Dim is local to the procedure in
which it's created. For example, if you declare a variable in the event procedure for a
CommandButton's Click() event procedure, it resides and is visible only within that event
procedure. Therefore, to create variables that have a scope other than local, you must
modify your declaration statement.
In most programs, unless you have only one form and no code modules, you'll find that
you need some variables that can be accessed from anywhere in the code. These are
called Public variables. (Other programming languages might refer to these as global
variables.) These variables are typically for holding information that's used throughout
the program. They can also be used to indicate various conditions in the program.
To create a Public variable, you 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 of type Boolean (True/False):
In a form, the Public keyword has a special meaning. Variables defined as Public are
considered to be very much like a property of the form and can be "seen" from anywhere
in the program. These properties are referenced like the built-in properties of a form or
control instead of like a variable. For example, you can have a string variable,
strMyName, declared Public in the form frmMain, and you would access the string
variable by using the following expression:
strSomeString = frmMain.strMyName
You can use the Public properties to pass information between forms and other parts of
your program.
If you don't need to access a variable from everywhere in your program, you don't want
to use the Public keyword in a declaration. Instead, you use the keyword Dim within a
procedure. When the variable is declared inside a procedure, it can be used only within
that procedure. This is typically known as a local variable.
The keyword Private is used within a form or module's Declaration section to make the
variable visible only to the form or module within which it's created. This is typically
known as a form- or module-level variable.
At first glance, you might think that making all variables global is the easiest thing to do,
but as your programs grow, this practice won't serve you well in the long run.
You saw in the preceding section that each procedure in a VB program can have its own
variables. Each procedure can have variable names that might be common across other
procedures, but because they are local to that procedure, none of the others know about
them. Thus, you avoid what are called name collisions.
Think of it this way: You might have two procedures, ProcA and ProcB. ProcA creates
two variables, x% and y%, and ProcB also creates two variables x% and y%. In ProcA, x
% and y% are assigned values that, in turn, are passed as values to the Left and Top
properties of a CommandButton, Command1.
In ProcB, the variable y% is assigned a value that's twice the value of x%. Both
procedures have variables of the same name. However, because each set of variables was
declared local to a distinct procedure, they are available only to the procedures in which
they were declared.
If you use the Static keyword to declare a procedure, all variables in the
procedure are treated as static.
To create a variable that retains its value even after the procedure is through running, 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 hold on to the value because it will be
needed again. For example, to declare a static variable for an integer, you use the
following:
A good use of a static variable would be where you needed to know how many times
somebody clicked a CommandButton. If you Dim a counting variable in a click event
procedure, the variable disappears when the click event is over and the variable goes out
of scope; thus, you couldn't know how many times it was clicked. If you made the
variable static, however, the value persists from click to click. Thus, if you put the
preceding line into a click event, you have a permanent way to keep track of the number
of clicks:
Sub MyButton_Click()
Static iNumOfClicks as Integer
iNumOfClicks = iNumOfClicks + 1
MsgBox "Number of Clicks: " & CStr(iNumOfClicks)
End Sub
Static variables are commonly used in timer event procedures. You will read more about
this in Chapter 16, "Working with Time and Timers."
Using Constants
Variables are only 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're defined for you by Visual Basic), you can't 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 hard-to-remember value, such as the color
value for the Windows title bar. It's easier to remember the constant vbActiveTitleBar
than the value 2147483646. You can also use a constant to avoid typing long strings if
they're used in a number of places. For example, you could set a constant such as
ERR_FILE_FOUND containing the string "The requested file was not found".
Often, constants are also used 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:
Visual Basic (as of version 4.0) supplies a number of sets of constants for various
activities. There are color-definition constants, data-access constants, keycode constants,
and shape constants, among others. The VB-supplied constants begin with the prefix vb.
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. Access the Object Browser by clicking its icon in the Visual Basic toolbar or
pressing the F2 key. 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.
Select the appropriate constants from the Classes list to view the constants internal to
Visual Basic.
Although Visual Basic defines a large number of constants for many activities, sometimes
you need to define your own constants. Constants are defined with the Const keyword
statement to give the constant a name and a value, as shown in the following syntax:
A function is a named section of code that returns a value. You can reuse
functions many times within your program. For calculation purposes, you
can pass information into functions. The information that you pass into a
function is called a parameter, also known as an argument. For more
information about functions, see Chapter 18, "Writing Reusable Code with
Subs and Functions."
NumStudents% = 25
SumScores% = 2276
AvgScore% = SumScores% / NumStudents%
TopStudent$ = "Janet Simon"
BadStudent$ = txtStudent.Text
You can consider most properties of forms and controls as variables. They can be set at
design time but also can be changed at runtime with 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. You saw this done in Listing 7.1. After the addition program
calculates the sum of the two entered numbers, it assigns the result to a third TextBox, as
shown in lines 23-26:
Dim x%
`Next line causes
`type mismatch error
x% = "Happy Birthday!"
Don't assume that users will always enter the data type that your program requires.
To prevent such an occurrence, you could use the Visual Basic IsNumeric() function to
check the value to make sure that the entry is indeed a numeric value. For example,
before line 13 in Listing 7.1, you would enter the following line to prevent users from
assigning any non-numeric character to the variable x%:
If IsNumeric(txtNumOne.Text) then
x = CInt(txtNumOne.Text)
End if
Obviously, making sure that the right type of data is assigned to the right type of variable
(what's referred to as data validation) is more than an academic exercise--it's a critical
programming skill. You'll find out how to solve this problem in Chapter 9, "Working with
Conditional Statements"; Chapter 21, "Debugging Your Applications"; and Chapter 12,
"Working with Strings and Typecasting."
-8-
Making Statements in a Program
Using the Assignment Statement
Using Variable Default Values
Using Math Operators
o Using Addition and Subtraction Operators
o Using the Multiplication Operator
o Using the Division Operator
o Using Exponents
Setting the Order of Precedence in Statements
Concatenating Strings
You learned in Chapter 7, "Using Data Types, Constants, and Variables," that you can
create a variable by using the Dim keyword:
Dim i as Integer
Just because you've created a variable, however, doesn't necessarily mean that the
variable has a useful value. At some point in the program, you have to give the variable
an appropriate value. This is often referred to as initializing the variable. This job is done
by the first assignment statement where the variable is the target of the assignment.
Making an assignment statement is easy: you specify a variable whose value you want to
set, place an equal sign after the variable name, and then follow it with the expression
that represents the value you want stored in the variable. The expression can be a literal
value (such as the number 1 or the characters "Frank"), a combination of other variables
and constants, or functions that return a value. The following statements illustrate
different types of assignment statements:
01 i = 6
02 SumScores = 2276
03 AvgScore = SumScores / NumStudents
04 TopStudent = "Sonja Swanson"
05 PrintedInvoice = true
06 txtFirstName.Text = FirstName
Line 6 assigns the value of a variable, FirstName, to the value of a TextBox's Text
property. This type of assignment is very common. Most properties of forms and controls
are variables. They can be set at design time, but they also can be changed at runtime by
using an assignment statement. You also can use a property on the right side of a
statement to assign its value to a variable for further processing. For example, you could
change line 6 to read a name from a text box and assign it to the variable FirstName as
follows:
FirstName = txtFirstName.Text
The assignment statement on line 3 of the previous example would be valid only if a prior
assignment statement had been made for the last variable on the right side of the
expression. If this variable, NumStudents, still had its default value of zero, the
assignment statement would create a divide-by-zero error because we used it before we
initialized it to the correct value.
Unfortunately, these types of errors are usually found through testing of the program at
runtime, because the values in the running program caused the error.
TABLE 8.2 Math Operations and the Corresponding Visual Basic Operator
Symbol
The two simplest math operations are addition and subtraction. If you've ever used a
calculator, 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 aren't limited to working with literal numbers
(for example, 1, 15, 37.63, and -105.2). Your program can add or subtract two or more
literal numbers, numeric variables, or any functions that return a numeric value. Also,
like a calculator, you can perform addition and subtraction operations in any
combination. Now let's look at exactly how you perform these operations in your
program.
As indicated in Table 8.2, the operator for addition in Visual Basic is the plus sign (+).
The general use of this operator is as follows:
Result is a variable (or control property) that contains the sum of the three numbers to the
right of the equal sign (=). The equal sign indicates the assignment of a value to the
variable. iNumberOne, iNumberTwo, and iNumberThree are numeric variables. As just
described, you can also add literal numbers or return values rather than numeric variables
from a function. 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:
Although the order doesn't 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, 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. This left-to-right processing is
used in the evaluation of expressions whenever similar operations are being performed.
If you really want to have 3 subtracted from 6 before it's subtracted from 15 for a Result
of 12, you have to change the operator or force the program to evaluate the expression in
the order you intended. (This order of execution is covered later in the section "Setting
the Order of Precedence in Statements.") For now, consider the following statements and
their resulting values:
If you aren't familiar with computer programming, line 5 may look a little
funny to you. In fact, that line isn't allowed in some programming
languages. In Visual Basic, however, 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. You also
can do this with string variables. (You'll see this done later in the section
"Using the Concatenating String.")
Lines 2 and 3 show that you can also use similar operators in combination with one
another. The following code lines are a few more valid math operations:
You simply use the multiplication operator--the asterisk (*)--to multiply two or more
numbers. The syntax of a multiplication statement is almost identical to the ones used for
addition and subtraction, as follows:
As before, Result is the name of a variable used to contain the product of the numbers
being multiplied, and iNumberOne, iNumberTwo, and iNumberThree are numeric
variables. Again, you also can use literal numbers or a return value from a function.
After you reach our Web site, you'll be asked to enter an ISBN. You should
enter 078971633x, and then click the Search button to go to the Book Info
page for Using VB6, where you can download the code.
It's a good idea to make sure that the value contained in a string variable "looks" like a
number and that the string isn't empty before you assign it to a numeric variable.
Starting at line 213 in the listing, notice that the program checks for zero values in all
variables that will be used as divisors. This is to prevent the error.
Division in Visual Basic is a little more complicated than multiplication. In Listing 8.1,
you saw three types of division used. The type you may find most familiar is the first one
used in line 234. This type is known as floating-point division (the normal type of
division). This type of division returns a number with its decimal portion, if one is
present.
Floating-point division is the typical division 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, (/), as seen in the following:
Visual Basic supports two other ways to divide numbers: integer division and modulus
(or remainder) division.
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 (\):
Modulus or remainder division divides one number into another and returns what's left
over after you obtain the largest integer quotient possible. The modulus operator is the
word Mod, as follows:
Modulus is used on Line 215 to calculate the amount of additional wallpaper required on
each cut length to allow for the pattern match. This remainder is then used to determine
the cut length of each strip of wallpaper for the project.
Using Exponents
Exponents also are known as powers of a number. For example, 2 raised to the third
power is equivalent to 2x2x2, or 8. Exponents are used quite a lot in computer operations,
in which many things are represented as powers of two. Exponents also are used
extensively in scientific and engineering work, where many things are represented as
powers of 10 or as natural logarithms. Simpler exponents are used in statistics, in which
many calculations depend on the squares and the square roots of numbers.
To raise a number to a power, you use the exponential operator, 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:
The following equations show several common uses of exponents. The operation
performed by each equation is also indicated.
x = 9 + 4 * 2
Depending on how you look at it, x could have two values--26 or 17. If you do the
addition of 9 + 4 first and then multiply by 2, you get 26. However, if you multiply 4 * 2
first and then add 9, you get 17. The answer you get depends on the order in which things
happen. This order is referred to as order of precedence.
When multiple types of operators are in a single statement, operator precedence controls
what's performed first. Math operators are performed first, then comparison operators,
and finally logical operators (see Table 8.3).
Parentheses are used to control specifically which parts of a statement are performed first.
Without parentheses, operator precedence allows the program to determine what
operation to do first. To ensure that arithmetic operations happen in the order you want
them to, you can use parentheses to group operations. For example, by using the
preceding statement, you could group operations as
x = (9 + 4) * 2 `results in 26
or
x = 9 + (4 * 2) `results in 17
Concatenating Strings
Visual Basic supports only one string operator, the concatenation operator. This operator
combines 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. (For more information about strings, read Chapter 12,
"Working with Strings and Typecasting.")
In this syntax, NewString represents the variable that contains the result of the
concatenation operation. stringOne, stringTwo, and stringThree all represent string
expressions. These can be any valid strings, including string variables, literal expressions
(enclosed in quotation marks), 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.
Also, you saw string concatenation used previously in the prjWallpaper example in
Listing 8.1. The statement used to build a message for the error MessageBox (on lines 24
and 25) is
This would have eliminated the second assignment statement, which would make the
code slightly more efficient.
-9-
Working with Conditional Statements
Making Decisions in Your Program
Writing If...Then Statements
o Writing a Single-Line If Statement
o Executing Multiple Commands in the Conditional Statement
o Using If...Then...Else Statements
o Working with Multiple If Statements
o Using Nested If Statements
Using the Select Case Statement
o Using Relational Operators in Select Case Blocks
One type of control statement is the decision statement. These statements are used to
control the execution of parts in your program, based on conditions that exist at the time
the statement is encountered. Two main types of decision statements are If...Then and
Select Case.
The IF Statement
The single-line If statement is used to perform a single task when the condition in the
statement is True. The following is the syntax of the single-line If statement:
The condition represents any type of statement or function that evaluates to True. The
condition can be any of the following:
The command represents the task to be performed if the condition is True. This can be
any valid Visual Basic statement other than a variable declaration.
The way this program works is that you enter a number in each of the two upper
TextBoxes, select a math operation, and then click the CommandButton. The program
performs the selected math operation on the numbers and displays the result in a third
TextBox.
The Simple Calculator makes decisions in an If...Then statement, based on the value of
the OptionButton.
The program decides which math operation to perform by evaluating the setting of the
Value property of the OptionButton assigned to each operation. If the Value property of
an OptionButton is set to True, the program does the associated math operation.
The following shows the If statement from the program. This conditional statement
performs the associated math operation if True and is an example of a single-line If
statement.
If condition Then
Command1
Command2
Commandn
End If
in which If and Then are the Visual Basic keywords that "bracket" the condition, and End
If are the keywords that end the code block.
Listing 9.2 shows a portion of code that enhances the cmdOperation_Click() event
procedure from Listing 9.1.
Whereas the code in Listing 9.1 invokes only one command when an If...Then statement
evaluates True (see line 21 of Listing 9.1), the code in Listing 9.2 invokes two commands
when the If...Then statement evaluates True (see lines 3-6 in Listing 9.2).
As you learned earlier, sometimes you might encounter this situation: If one condition
exists, you do one set of commands, and if it doesn't, you do another set. For example, If
you have money in your checking account, write a check; Else, transfer funds from your
savings account into the checking account. This is called an If...Then...Else statement.
If...Then...Else takes the following format:
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 in
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 before the Else statement and
starts processing with the first statement after the Else.
You saw the following code snippet at the end of Listing 9.1. This is an excellent example
of a simple If...Then...Else statement. If the value of the variable y doesn't equal zero
(line 30), the program does some division (line 31); otherwise, the program displays a
Windows message box with an error message (line 34).
If you want to execute code for only the False portion of the statement, you can place
code statements between the Else and End If statements; you aren't required to place any
statements between the If and Else statements:
If x <= 1 then
Else
MsgBox "X is not greater than 1"
End If
In the preceding sections, you saw simple If...Then statements, which evaluate one
condition and can execute commands for a True or False condition. You can also evaluate
multiple conditions with an additional statement in the block. If...Then...ElseIf statements
let you specify another condition to evaluate whether the first condition is False. By using
the ElseIf statement, you can evaluate any number of conditions.
Listing 9.3 shows a snippet of code from the program Grader.EXE from the project
grader.vbp, available from the Web site associated with this book. The code snippet uses
the ElseIf conditional structure as a way to determine the grade for a test, based on a
range of correct answers.
This code works first by evaluating the condition in the If statement (line 1). If the
condition is True, the statement (or statements) immediately following the If statement is
executed (line 2), and then the program skips to the first statement after the End If
statement (line 19).
If the first condition is False, the program skips to the first ElseIf statement (line 3) and
evaluates its condition. If this condition is True, the statements following the ElseIf are
executed (line 4), and control again passes to the statement after the End If. If the
condition evaluates to False, control passes to the next ElseIf statement. 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 (line 17) and the End If statements. The Else statement isn't
required.
If you need to test for a condition that depends on whether another condition is already
True (such as "If it's 6:30 a.m. and if it's a weekday"), use nested If statements. A nested
If statement is one that's enclosed within another If statement. The format for a nested If
statement is as follows:
If condition Then
If another_condition Then
statement
Else
another statement
End If
End If
The following code snippet demonstrates a nested If statement. You originally saw it in
the cmdOperation Click() event procedure in Listing 9.1.
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 a
literal, a variable, a logical expression, or a function.
Each conditional group of commands (run if the condition is met) is started by a Case
statement. The Case statement identifies the expression to which the TestValue is
compared. The Case statement can express a single value or a range of values. If the
TestValue is equal to or within range of 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 isn't equal to the
value expression or doesn't fall within a range defined for the Case statement, the
program proceeds to the next Case statement.
Listing 9.4 shows you a Select Case statement that tests for equality. Listing 9.5 shows
you a Select Case statement that tests for a range.
01 Select Case x%
02 Case 1:
03 MsgBox "I am 1"
04 Case 2:
05 MsgBox "I am 2"
06 End Select
01 Select Case x%
02 Case 6 To 9
03 MsgBox "I am more than 5 and less than 10"
04 Case 101 To 199
05 MsgBox "I am more than 100 and less than 200"
06 Case Else
07 MsgBox "Not in Range"
08 End Select
The simplest form of the Select Case block uses only a single value for the comparison
expression. Listing 9.6 shows a Select Case statement that accomplishes the same thing
that the If...Then...ElseIf code in Listing 9.3 does. The benefit of using a Select Case to
accomplish the grading task is that the code is easier to read and easier to extend.
When it comes time to add another grade level--say, an A+ if the student correctly
answers 11 in the following example--all you need is to add a new case, Case 11 (see
Listing 9.7, line 3). If you were to use the ElseIf technique, you would have to rewrite
significant portions of the If...Then...ElseIf code block.
You can also use relational operators in a Select Case block. Sometimes you might want
to test for cases within a range perhaps greater than or less than a certain number. To
accomplish this with a Select Case block, you must use the Is keyword. To test within a
certain range, use the To keyword as you saw earlier in Listing 9.5.
Just as you can check to see whether equality exists between two quantities with the =
sign, you can also check to see whether numbers are less than, greater than, or not equal
to one another. Table 9.1 shows the relational operators that you can use in your
conditional statements.
Line 3 of Listing 9.8 shows you how to use the Is keyword to create a greater-than
statement within a Select Case block. Notice that the relational operator (>) is used to
make any number of correct answers greater than 11 result in a grade of A++.
Select Case statements are a powerful addition to your programming toolkit and take you
to the next level of programming expertise. As you learn more about them, you will
understand how to use If statements and Select Case statements together to make very
detailed, extended decisions within your programs.
- 10 -
Working with Loops
Putting Loops to Work
Using For...Next Loops
o Terminating the For...Next Loop Early
Using Do...Loop Statements
o Using Do...While Loops
o Do loops will always run once if tested at the end
o Using Do...Until Statements
Breaking an Infinite Loop
o Nesting Loops
o Working with Multiple Loops
o Using Nested Loops to Eliminate Loops
o Loading Data with Nested Loops
Visual Basic supports two commonly used types of loops: counter loops, which perform a
task a set number of times, and conditional loops, which perform a task while a specified
condition exists or until a specified condition exists.
At the beginning of a For...Next loop, you define a counter variable, as well as the
beginning and end points of the variable's value. The first time the loop is run, the counter
variable is set to the value of the beginning point. Each time the program runs through the
loop, the value of the counter increments. If the Step keyword is used, the counter
variable increments as dictated by the number following the Step keyword. For example,
in the following statement, intCntr will increment by 2:
As the counter variable increments, it's checked against the value of the end point. If the
counter is larger than the end point, the program skips out of the loop and onto the first
statement following the loop.
If the beginning value of the loop is greater than the ending value, the loop won't execute
at all, unless you set up the loop to count backward. For example, the following loop
doesn't cause an error, but because the start boundary of the loop (9) is greater than the
end boundary (0), the loop is ignored and the message box doesn't appear:
The default or assumed value for the Step in a For...Next loop is a positive
1, which increments the counter. Including the step value on all For...Next
loops, even when the value is 1, improves readability and aids
maintenance.
Concatenation
You concatenate a string when you add another string onto a string. An
example of concatenating three strings onto one string is FullName = First
& " " & Last, which performs two successive concatenations into the
string variable FullName.
The following loop works, however, because the loop uses the Step keyword to
decrement >backward (-1) from 9 to 0:
The counter variable is changed each time the loop reaches the Next statement. Unless
otherwise specified with the Step keyword, the counter is increased by one for each loop.
Listing 10.1, the event handler for the For...Next button click event, shows a For...Next
loop that exposes the counter variable within a larger string displayed in a TextBox. As
the loop progresses, the counter variable is converted to a string and inserted within
strings, StrBegin and StrEnd. Those strings are concatenated onto a master "holding"
string, StrMsg, which grows with each trip through the loop. A carriage return and line-
break character is added to StrMsg at the end of the loop, and then the StrMsg is assigned
to the Text property of txtDisplay. The loop then refreshes the form to repaint the
TextBox.
For ease of reading your program code, it's good practice to include the
variable name in the Next statement (like on line 32 of Listing 10.1). This
is especially important in nested loops.
When you set a TextBox's MultiLine property to True, make sure that you set the
TextBox's ScrollBars property accordingly. Otherwise, you may not see all the text.
vbCrLf is a Visual Basic global constant that could have been substituted
with the string "Chr(13) & Chr(10)". Both the VBA constant and this
literal string are equivalent to a carriage return/line feed combination. For
more information about using VBA constants, see Chapter 7, "Using Data
Types, Constants, and Variables."
An alternative method would be to only update the screen after leaving the loop. You
would move the assignment statement immediately after the Next command to prevent
the program from displaying any text until the loop is completed. In the case of a long-
running process, you should give users a visual indication that the program is running. In
long-running loops, if you wait to the end of the loop to display the results onscreen, your
users may think the program has locked up.
Although you can use any numeric variable for the counter, you need to be aware of the
limits of each variable type. For example, trying to run a loop 40,000 times starting from
0 with a step of 1 and an integer variable as the CounterVar causes an overrun error
during execution. This is because an integer has a maximum positive value of 32,767.
Using a Long integer will solve this problem when larger loop counters are required. The
limitation on Long integers is negative 2,147,483,648 to positive 2,147,483,647.
Using floating-point variables such as Singles and Doubles for a CounterVar will work.
There's even the capability to support fractional Step variables, although these can
become difficult to maintain and should be avoided unless required by the functionality
of the statements inside the loop.
You should exercise great care when manually changing the value of the counter variable
inside the loop. Never reset the value of the counter variable inside a For...Next loop,
because doing so may create an infinite loop or a program lockup. For example, the
following code causes the For...Loop to go into an infinite loop, because the end value of
4 is never reached:
For intCntr = 0 to 4
intCntr = 0 ` This line causes an infinite loop
Next intCntr
Typically, your For...Next loop should run through all the values of the counter variable,
but sometimes you'll want the loop to terminate early. To do this, simply place an Exit
For statement where you want the loop to stop. This statement is typically associated
within an If...Then statement.
Listing 10.2 shows an enhancement to the code in Listing 10.1. Lines 16 through 22 show
an added If...Then statement at the beginning of the For...Next loop. When the loop
begins, the code enters the If...Then statement to take a look at the value of the CheckBox
on the form. Selecting the CheckBox on the form tells the program that the loop needs to
terminate when the value of the counting variable exceeds the quantity 10. Therefore, if
this condition exists (the CheckBox is checked), the Exit For statement--contained in the
If...Then statement within the first If...Then statement--forces the program out of the
For...Next loop.
CheckBoxes are a good means of control when you need to set or clear a condition.
A Do...While loop works pretty much as the name implies--it does something while a
certain condition is true. For example, to keep adding one to MyNum while MyNum is
less than 20, you would use this:
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 out of the loop and onto the next statement after the
Loop statement.
Do While condition
statement(s)
Loop
The state that must exist (for example, x = 10, MyVal <> True, or y < x)
Do
statement(s)
Loop While condition
As you can see in this example, the Do...While loop has two forms. The difference
between the two is the placement of the condition--at the beginning of the loop or at the
end.
Listing 10.3 looks similar to the For...Next loop code in Listing 10.2. When you take a
closer look at Lines 13 through 41, however, you'll notice that where there was a
For...Next loop, there's now a Do...While loop that runs while the value of intCntr is less
than or equal to 20. Line 21 has also been changed from Exit For to Exit Do because the
loop is now change to a Do loop. The Exit Do command is used with both types of Do
loops.
LISTING 10.3 10LIST03.TXT--A Do...While Loop That Does the Same Thing as a
For...Next Loop
You can us Do...While to loop while intCntr is less than or equal to 20.
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.
Don't put the While condition clause in both the Do and Loop statements
because this causes an error when you try to run your program.
When the form of the loop is located with the While keyword right after the Do keyword,
the statements inside the loop may 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, use the second form of the Do...While loop, which places
the condition after the Loop statement. For example,
Do
Text1.Text = Text1.Text & CStr(intCntr )
intCntr = intCntr + 1
Loop While intCntr < 10
This form of the Do...Loop 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.
Dim intCntr
intCntr = 0
txtMessage.Text = ""
Do While intCntr < 10
txtMessage.Text = txtMessage.Text _
& CStr(intCntr)
Loop
The following code loops, terminates, and displays the TextBox's text just fine:
Dim intCntr
intCntr = 0
txtMessage.Text = ""
Do While intCntr < 10
txtMessage.Text = txtMessage.Text _
& CStr(intCntr)
intCntr = intCntr + 1
Loop
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--in other
words, as long as the condition isn't met. When the condition becomes true, the loop
terminates.
Do Until condition
statement(s)
Loop
There are two forms of syntax for the Do...Until loop, just as there are two forms of
syntax for the Do...While 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 same line as the Do
keyword, the condition is evaluated before the statements in the loop are executed. If you
place the condition in the same line as the Loop keyword, the loop is run at least once
before the condition is evaluated.
Listing 10.4 shows the event procedure for the cmdDoUntil button's Click event . A
Do...Until loop within the event procedure runs until the counter variable, intCntr, is
greater than 20, or the Stop at 10 CheckBox is selected. This code is similar to the code
for the cmdDoWhile_Click() event procedure in Listing 10.3. The only difference is that
the Do...While loop is changed to a Do...Until loop (Lines 13 through 41). Also, the
StrEnd string on Line 11 is changed from " of a Do...While loop" to " of a Do...Until
loop". As you can see, Do...While loops and Do...Until loops are closely related.
Generally, which one you use is a matter of personal style.
If your program is running within the Visual Basic IDE, press Ctrl+Break.
When you press these keys, the loop breaks at a line of code within the
infinite loop. If your program isn't running within the IDE, the only way to
terminate it is to end the program from within the Windows Task Manager.
(For detailed information about the Task Manager, read the online
documentation that comes with Windows.)
Getting comfortable using loops takes time. The more you use them, the better you'll get
at identifying situations in which to use them. Loops can be a powerful programming
tool, but they can cause enormous headaches if not properly written.
The following shows a programmer's worst nightmare--the infinite loop:
The command inside the loop sets the conditional variables and prevents the program
from going beyond loop. So the code tells the program to loop forever. When the
program enters this loop, it's locked into the loop; everything else waits for the loop to
complete, which never happens. If you run this program within the Visual Basic IDE, be
aware that infinite loops will often lock it up and you may lose any program changes you
made since your last update.
The best way to avoid an infinite loop is to carefully double-check any code you write
that changes the conditional or counter variables in your loops. This may seem simplistic,
but the power of loops is also the danger of loops. A loop can just as quickly tie up your
system doing a desired productive task as it can counting to 2 billion for no reason.
Nesting Loops
In some situations, it becomes important to repeat a subtask several times during a larger
task that's also being repeated. The way you write this type of program is by including a
loop inside the set of instructions being repeated by a loop. This loop-within-a-loop
structure is called nesting, or a nested loop. Nested loops can be a powerful programming
tool, but they're confusing to understand if they're not properly written and documented.
Listing 10.5 shows an example of multiple loops that change the Background Color
property of the vpjLoops form and CheckBox during runtime. The main form and the
CheckBox are changed to include all the visible background on the frame. This sample
program is run from the Simple Color command button.
The program first saves the current background color and then proceeds to remove each
of the three screen colors through a set of 255 increments. The first color removed is red,
then green, and finally blue. The second set of three loops does just the opposite: first it
adds in the red, then green, and finally blue. The last two lines (65 and 66) put both
elements back to their original background color settings.
There are six separate loops for 67 total lines of code. These loops have many lines in
common, and with a little effort, you can identify those common elements.
You'll notice the use of a long integer array to accomplish the function of the inner loop.
Arrays are covered in depth in Chapter 11, "Working with Arrays."
Listing 10.6 shows Listing 10.5 rewritten as two nested loops. The first loop dims the
background color by color. The second, as in Listing 10.5, adds the colors back in. This
sample program is run from the Nested Color command button.
LISTING 10.6 10LIST06.TXT--An Wxample of Two Nested Loops That Use a Long
Integer Array
There are only 41 lines of code and only two nested loops to maintain in this new version
of the program. This reduces line count by 35 percent with no loss of functionality. The
key benefits that nested loops provide are consistent operation and ease of maintenance.
If the same code is being used every time a loop is run, it becomes easy to make sure that
it does the same tasks.
Nested loops require more effort to write and debug than simple loops. Reusable code is
harder to develop than redundant code by at least a factor of 2. This topic is covered more
in Chapter 18, "Writing Reusable Code with Subs and Functions."
Visual Basic's IDE makes it very tempting to write a simple loop and then cut and paste it
six, seven, or 200 times in a row. Most programming tools make it very easy to copy lines
of code. The challenge comes in learning to write better programs that are easier to
maintain and that perform consistently.
There are more useful examples where nested loops are invaluable. The final example in
this chapter is based on the MSFlexGrid ActiveX control and how it could be loaded
from a text file by using a nested loop. In this example, the control isn't bound to any data
source. The example program uses a simple text file that contains one field or cell per
row. The nested loop is a big help here, as it can be used to step through the rows in the
grid column by column. This allows the read or input statement to appear only once in the
program.
Loading the MSFlxGrd.ocx file
An enhanced version of MSFlexGrid comes with VB6. Before you can use
the MSFlexGrid control in your application, you must add the
MSFlxGrd.ocx file to your Microsoft Windows System directory. For
more information about adding an ActiveX control to a project, see
Chapter 4, "Using the Intrinsic Controls."
Listing 10.7 lists the setup commands for the MSFlexGrid control that are executed when
the form loads. These commands set the width of the four columns used in the example.
(The details of this are covered in Chapter 32, "Enhancing Your Programs Using the
Advanced Data Controls.")
By default, the Load event fires when a form is displayed. By using this event, the
program adjusts the width of the four columns to values that fit the amount of data in
each column. These were identified by trial and error, but a routine could have been
written to inspect the data in each grid cell and then determine the right width for each
column. This function would work like the Format menu's Column and Autofit
command in Microsoft Excel.
When you load the MSFlexGrid ActiveX control, you can specify runtime properties.
Now that the control is set up, the actual program is straightforward. An ASCII text file
contains 24 lines or rows. Each line is read in turn and loaded into the grid. Listing 10.8
shows a partial listing of the text file; the full listing can be downloaded from the Web
site, along with the sample program and the actual IMPORT.TXT file.
01 StoreID
02 Location
03 Manager
04 Sales
05 1566
06 Minneapolis
07 James Archie
08 "$14,187,944"
...
21 1032
22 New York
23 Elmer Doren
24 "$5,437,104"
The IMPORT.TXT file was created with Microsoft Notepad and can be
edited. The name of the file, its location, and the number of rows is part of
the program statements and must be changed to read different filenames.
Rows 1 through 4 of Listing 10.8 are used as the column headings in the grid control.
There's nothing special about these rows, other than they are first, and the background
and font in the MSFlexGrid control was formatted. Rows 5 though 24 are the detailed
records for each of five stores, including the store ID, location, manager's name, and total
sales.
The program in Listing 10.9 shows the 39 lines of code required to accomplish the task of
loading the grid. Lines 21 through 34 are the nested loop that reads each line from the file
and moves it into the proper cell of the grid.
Lines 7 through 18 in Listing 10.9 are for finding and opening the text file for input. The
MessageBox displays the current default path of the local user's system. This is important
because the default path is used with the file handler number given by the FileFree
function to locate and open IMPORT.TXT. If the file isn't at this location, an error
message will occur.
When the Click event on the Nested Data Read command button is fired, IMPORT.TXT
is read row by row.
The nested loop reads the text file and loads the control.