Using Visual Basic 6

Previous chapterNext chapterContents


- 8 -
Making Statements in a Program


Using the Assignment Statement


Learning the VB language

Computer programming is more than learning the Visual Basic language--it's about being able to describe and implement your ideas through the syntax of the programming language. One way to do this is by making statements, which are used to assign, compare, or calculate information in your programs. When you understand the steps your program must perform and can describe those steps through statements and the syntax of the Visual Basic language, you're ready to begin programming.


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

Using Variable Default Values

When you create a variable, Visual Basic assigns a default value to it. The actual default value depends on the variable's data type, as shown in Table 8.1.

TABLE 8.1 Default Values for a Variable

Data Type Value
Integer 0
Long 0
Single 0
Double 0
String "" (blank)
Boolean False
Variant EMPTY
Date 0
Currency 0

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 (see Figure 8.1).

FIGURE 8.1 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.

Using Math Operators

Math operations are used to determine customer bills, interest due on savings or credit card balances, average scores for a class test, and many other tasks. Visual Basic supports a number of different math operations that can be used in program statements. Table 8.2 summarizes these operations and the Visual Basic symbol for each operation.

TABLE 8.2 Math Operations and the Corresponding Visual Basic Operator
Symbol

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

Using Addition and Subtraction Operators

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 = iNumberOne + iNumberTwo + iNumberThree

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:

Result = NumberOne - NumberTwo - NumberThree

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:

1 Result = 15 "-" 3 "-" 6  `results in 6
2 Result = 15 "-" 6 + 3    `results in 12
3 Result =  3 - 6 + 15     `results in 12


Using a variable on both sides of the assignment operator

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:

1 dValOne = 1.25 + 3.17              `results in 4.42
2 dValTwo = 3.21 - 1                 `results in 2.21
3 dValThree = dValTwo + dValOne      `results in 6.63
4 dValFour = dValThree + 3.75 - 2.1  `results in 8.28
5 dValFour = dValFour + 1            `results in 9.28

Using the Multiplication Operator

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:

Result = iNumberOne * iNumberTwo * iNumberThree

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.


Complete listings and sample programs on the Web site

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.


As a demonstration of how multiplication and division might be used in a program, consider the example of a program to determine the number of rolls of wallpaper needed to cover a wall in a room. This program contains a form that lets the homeowner enter the width and height of the wall with the length, width, pattern match, and cost of the wallpaper. The program then calculates the number of wallpaper rolls required and the total cost of the project. Figure 8.2 shows an example of the form from the program; Listing 8.1 shows some of the actual code used to perform the calculations. The complete code listing for this example is in the project prjWallpaper.vbp on the MCP Web site (http://www.mcp.com/info) that supports this book.

FIGURE 8.2 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.


Line numbering and VB example code

The code in the listing text throughout this chapter is syntactically and operationally identical to the code in the sample programs on the Web site, except that each line of code is numbered. The code in the sample programs is fully commented to help you understand the various ideas and techniques used to create the program without having to reference back to the book.


LISTING 8.1 08LIST01.TXT--Using Multiplication and Division Operators to Estimate

01 Private Sub cmdCalc_Click()
02 Dim WallWidth As Integer `Width of walls
03 Dim WallHeight As Integer `Height of walls
04 Dim RollLength As Integer `Length of the roll
05 Dim RollWidth As Integer `Width of the roll
06 Dim PatternMatch As Integer `Amount of pattern match
07 Dim CutLength As Integer `Length of each piece
08 Dim Remn As Integer `Length of remnant
09 Dim PiecePerRoll As Integer `Number pieces per roll
10 Dim NumofRoll As Integer `Number rolls needed
11 Dim dRollCost As Double `Cost of each roll
12 Dim dProjectCost As Double `Total project cost
13 Dim Msg As String `Message variable
14
15 `Make sure the txtWallWidth TextBox is not blank
16 If txtWallWidth.Text <> "" Then
17 `Check to make sure the text is a numeral then
18 `convert the text to the appropriate data type
19 `and assign the numeric value to the variables
20 If IsNumeric(txtWallWidth.Text) Then
21 WallWidth = CInt(txtWallWidth.Text)
22 Else
23 `It is not a number go back to the TextBox.
24 `Make a message
25 Msg = "Wall Width needs to be numeric. "
26 Msg = Msg & "Please enter a number."
27 `Display the message
28 MsgBox Msg, vbExclamation, "Data entry error"
29 `Send the mouse cursor back to the TextBox
30 txtWallWidth.SetFocus
31 `Leave the Sub
32 Exit Sub
33 End If
34 Else
35 `If it is blank, send the cursor back to the
36 `blank TextBox.
37 `Make a message
38 Msg = "You cannot leave Wall Width blank. "
39 Msg = Msg & "Please enter a number."
40 `Display the message
41 MsgBox Msg, vbExclamation, "Data entry error"
42 `Send the mouse cursor back to the TextBox
43 txtWallWidth.SetFocus
44 `Leave the Sub
45 Exit Sub
46 End If
...
213 `Make sure PatternMatch is greater than zero
214 If PatternMatch > 0 Then
215 Remn = (WallHeight Mod PatternMatch)
216 If Remn > 0 Then
217 CutLength = ((WallHeight - Remn) _
+ PatternMatch)
218 Else
219 CutLength = WallHeight
220 End If
221 Else
222 CutLength = WallHeight
223 End If
224
225 `Make sure RollLength is greater than zero
226 If CutLength > 0 Then
227 PiecePerRoll = RollLength \ CutLength
228 Else
229 PiecePerRoll = RollLength
230 End If
231
232 `Make sure RollWidth and PiecePerRoll greater than 0
233 If RollWidth > 0 And PiecePerRoll > 0 Then
234 NumofRoll = (WallWidth / RollWidth)
235 NumofRoll = (NumofRoll / PiecePerRoll) + 0.4999
236 Else
237 NumofRoll = 0
238 End If
239
240 `Calculate the project cost
241 dProjectCost = NumofRoll * dRollCost
242
243 `Display the results in the answer boxes
244 lblCutLen.Caption = CStr(CutLength)
245 lblNumRolls.Caption = CStr(NumofRoll)
246 lblTotalCost.Caption = CStr(dProjectCost)
247 End Sub


Error checking and documentation

Being able to make concise, robust statements is fundamental to computer programming. As your Visual Basic programming skills develop, you'll find that the functional line count in your code will shrink while the error handling and documentation line count will grow. As you can write well-behaved statements that do more with less, you will want to document and protect your programs. Getting to this point, however, takes time, practice, and experience. Right now, if you can write clear and accurate statements, you'll be in good shape.


Notice that line 20 of Listing 8.1 uses the IsNumeric() function. This function tests that the values input are numeric. The txtWallWidth TextBox is also checked for blank values. The purpose of lines 15 to 46 is purely for error checking this one TextBox. (In the complete listing, you'll find that each TextBox is checked in turn before the calculations are made.)

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 you saw in Figure 8.1.

Using the Division Operator

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.


Math operators work left to right

As with addition, subtraction, and multiplication, if you perform division on more than two successive numbers, a division operator must separate each number. Also, as with the other operations, multiple operators are handled by reading the equation from left to right.


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:

Result = NumberOne / NumberTwo
Result = 2.3 / 2    `result in 1.15

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 (\):

Result = NumberOne \ NumberTwo
Result = 2.3 \ 2 `The value of Result is 1

An example in Listing 8.1 is located on line 227, where the goal is to find out the number of cut lengths that can be cut from each roll.

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:

Result = NumberOne Mod NumberTwo
Result = 11 Mod 3     `result in 2
                      `(11/3 = 3 with a remainder of 2)

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:

Result = NumberOne ^ Exponent

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

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

Setting the Order of Precedence in Statements

Consider the following statement:

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.

In Visual Basic, the default order of precedence is that in a statement with multiplication/division operators and addition/subtraction operators, multiplication/division is performed first, before the addition/subtraction. In the preceding example, the default answer is 17. Other operators, such as comparison, logical, and string, are also affected by 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).

TABLE 8.3 Precedence Order of Visual Basic Operators

Operation Operator Symbol
Exponentiation ^
Negation (unary) -
Multiplication, division *, /
Integer division \
Modulus mod
Addition, subtraction +, -
Concatenation (string) &
Comparison operators =, <>, <, >, <=, >+
Logical operators Not, And, Or, Xor, Eqv, Imp, Like, Is


Controlling the order of operations

Experienced programmers use parentheses to define the ordering of operations within their programs. Using parentheses to define order of precedence removes ambiguity. You'll want to use parentheses in your code. Doing so doesn't affect the speed of your program and assures the accuracy and clarity of your code.


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

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

NewString = stringOne & stringTwo & stringThree

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.


Concatenation operator from previous versions is supported

If you're working on converting programs from an older version of Visual Basic, you may find strings combined with the plus- sign operator. This was prevalent in versions of Visual Basic prior to version 4, as well as in older BASIC languages. Although Visual Basic still supports the plus-sign operator for backward compatibility, you should 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 is used in a simple program to generate mailing labels. On line 48, the fields from the different text boxes are combined to create the different lines of the mailing label. Figure 8.3 shows the form for this program. The complete code for this example is in the project prjName.vbp on the MCP Web site (http://www.mcp.com/info) that supports this book.

LISTING 8.2 08LIST02--How OptionButtons are Used to Make Exclusive Choices

01 Private Sub cmdShowName_Click()
02 Dim strTitle As String
03 Dim strFirst As String
04 Dim strLast As String
05 Dim strFullName As String
...
37 `Assign the value in the TextBox to a string
38 strFirst = txtFirstName.Text
39 strLast = txtLastName.Text
40
41 `Assign the Title of the selected one to a string
42 If optMr.Value Then strTitle = "Mr. "
43 If optMrs.Value Then strTitle = "Mrs. "
44 If optMiss.Value Then strTitle = "Miss "
45 If optMs.Value Then strTitle = "Ms. "
46
47 `Put the strings together
48 strFullName = strTitle & strFirst & " " & strLast
49
50 `Display the results in the answer box
51 lblFullName.Caption = strFullName
52 End Sub

FIGURE 8.3 A simple name-reporting program illustrates the function of the concatenation operator.

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

Msg  = "Wall Width needs to be numeric. "
Msg  = Msg  & "Please enter a number."

This is an example of concatenating a string onto a single-string variable. Another way to solve the problem above is to use the line-continuation characters (_), which are used on line 217 in Listing 8.1. The "space + underscore" characters allow a single program statement to extend over several contiguous lines in the program. There are limitations in its use, such as not following the line-continuation characters with a comment. The previous example would have been written as follows if the line- continuation character had been used:

Msg  = "Wall Width needs to be numeric. " & _
       "Please enter a number."

This would have eliminated the second assignment statement, which would make the code slightly more efficient.


Previous chapterNext chapterContents

© Copyright, Macmillan Computer Publishing. All rights reserved.