Introduction To Visual Basic Programming: Objectives
Introduction To Visual Basic Programming: Objectives
Introduction to Visual
Basic Programming
Objectives
• To write simple programs in Visual Basic.
• To become familiar with fundamental data types.
• To understand computer memory concepts.
• To be able to use arithmetic operators.
• To understand the precedence of arithmetic
operators.
• To be able to write simple decision-making
statements.
“Where shall I begin, please your majesty?” she asked.
“Begin at the beginning,” the king said, very gravely, “and go
on till you come to the end; then stop.”
Lewis Carroll
It is a capital mistake to theorize before one has data.
Arthur Conan Doyle
. . . the wisest prophets make sure of the event first.
Horace Walpole
An actor entering through the door, you’ve got nothing. But if
he enters through the window, you’ve got a situation.
Billy Wilder
You shall see them on a beautiful quarto page, where a neat
rivulet of text shall meander through a meadow or margin.
Richard Brinsley Sheridan
Exit, pursued by a bear.
William Shakespeare
52 INTRODUCTION TO VISUAL BASIC PROGRAMMING CHAPTER 3
Outline
3.1 Introduction
3.2 Visual Programming and Event-Driven Programming
3.3 A Simple Program: Printing a Line of Text on the Form
3.4 Another Simple Program: Adding Integers
3.5 Memory Concepts
3.6 Arithmetic
3.7 Operator Precedence
3.8 Decision Making: Comparison Operators
Summary • Terminology • Common Programming Errors • Good Programming Practices •
Testing and Debugging Tip • Software Engineering Observation • Self-Review Exercises •
Answers to Self-Review Exercises • Exercises
3.1 Introduction
The Visual Basic language facilitates a structured and disciplined approach to computer
program design. In this chapter we introduce Visual Basic programming and present sev-
eral examples that illustrate many important features. Each example is carefully analyzed
one statement at a time. In Chapters 4 and 5 we present an introduction to structured pro-
gramming.
events. Only events that are relevant to a program need be coded. In the next section we
demonstrate how to locate event procedures and add code to respond to events.
The Properties window contains the Object box that determines which object’s
properties are displayed (Fig. 3.3). The Object box lists the form and all objects on the
form. A selected object’s properties are displayed in the Properties window.
The TabIndex property determines which control gets the focus (i.e., becomes the
active control) when the Tab key is pressed at runtime. The control with a TabIndex
value of 0 gets the initial focus. Pressing the Tab key at runtime transfers the focus to the
control with a TabIndex of 1. Eventually, if the Tab key is pressed enough times, the
focus is transferred back to the control with a TabIndex of 0. The focus for each control
is displayed differently. For buttons, the one with the focus has a darker border around it
and a dotted inner square on its face as shown in Fig. 3.1. Some controls, such as Labels,
have a TabIndex property but are not capable of receiving the focus. In this situation, the
next control (based upon TabIndex values) capable of receiving the focus gets it. By
default, a control receives a TabIndex property based on the order in which it is added to
the form. The first control added gets 0, the next control added gets 1, etc. A control’s
TabIndex property can be changed in the Properties window.
Object box
Object box
expanded
We now switch over from the visual programming side to the event-driven program-
ming side. If our program is going to print on the form, we must write code to accomplish
this. With GUI and event-driven programming, the user decides when text is printed on the
form by pressing Print. Each time Print is pressed, our program must respond by printing
to the form. When the button is pressed does not matter; the fact that the button is pressed
matters. Code must be written for the Print button’s event procedure that receives this
clicking (i.e., pressing) event.
When pressed, the End button terminates the program. Code must be written for the
End button’s event procedure that receives this clicking event. This event procedure for
End is completely separate from the event procedure for Print. Separate event procedures
make sense, because each button needs to respond differently.
Code is written in the Code window (Fig. 3.4). The Code window is displayed by
either clicking the Properties window’s View Code button or by double-clicking an
object. The View Code button is disabled unless the form is visible. Figure 3.4 is the result
of double-clicking the Print button at design time.
The code shown in Fig. 3.4 is generated by Visual Basic. The line
begins the event procedure definition and is called the procedure definition header. The
event procedure’s name is cmdDisplay_Click (the parentheses () are necessary for
syntax purposes). Visual Basic creates the event procedure name by appending the event
type (Click) to the property Name with an underscore (_) added. Private Sub marks
the beginning of the procedure. The End Sub statement marks the end of the procedure.
Code that the programmer wants executed when Print is pressed is placed between the pro-
cedure definition header and the end of the procedure (i.e., End Sub). Figure 3.5 shows the
Code window with code. We will discuss the code momentarily.
Blinking
cursor
Margin
Indicator
bar
Programmer
writes code here
Click and drag here to resize
Figure 3.6 labels two buttons Procedure View and Full Module View. Procedure
View lists only one procedure at a time. Full Module View lists the complete code for the
whole module (the form in this example) as shown in Fig. 3.6. The Procedure Separator
separates one procedure from another. The default is Full Module View. We pressed the
Procedure View button in Fig. 3.5. Any object’s code can be accessed with the Code
window’s Object box and Procedure box. The Object box lists the form and all
objects associated with the form. The Procedure box lists the procedures associated with
the object displayed in the Object box.
The program code is shown in Fig. 3.7. The line numbers to the left of the code are not
part of the code but are placed there for reference purposes.
Procedure cmdDisplay_Click executes when button Print is pressed. The lines
' Every time this button is clicked, the message
' "Welcome to Visual Basic!" is printed on the form
are comments. Programmers insert comments to document programs and improve program
readability. Comments also help other people read and understand your program code.
Comments do not cause the computer to perform any action when a program is run. A com-
ment can begin with either ' or Rem (short for “remark”) and is a single-line comment that
terminates at the end of the current line. Most programmers use the single-quote style.
Good Programming Practice 3.2
Comments written to the right of a statement should be preceded by several spaces to en-
hance program readability. 3.2
The line
prints the text “Welcome to Visual Basic!” on the form using the Print method. Each
time this statement executes, the text is displayed on the next line. Method Print is a fea-
ture of the Visual Basic language and is unrelated to cmdDisplay’s Caption (Print).
Good Programming Practice 3.5
Indent statements inside the bodies of event procedures. We recommend three spaces of in-
dentation. Indenting statements increases program readability. 3.5
Drawing directly on the form using Print is not the best way of displaying informa-
tion, especially if the form contains controls. As is shown in Fig. 3.1, a control can hide text
that is displayed with Print. This problem is solved by displaying the text in a control.
We demonstrate this in the next example.
The only statement in the cmdExit_Click event procedure is
End ' Terminate program
The End statement terminates program execution (i.e., places the IDE in design mode).
Note the comment’s placement in the statement.
Software Engineering Observation 3.1
Even though multiple End statements are permitted, use only one. Normal program termi-
nation should occur in only one place. 3.1
When the user types a line of code and presses the Enter key, Visual Basic responds
either by generating a syntax error (also called a compile error) or by changing the colors
on the line. Colors may or may not change depending on what the user types.
A syntax error is a violation of the language syntax (i.e., a statement is not written cor-
rectly). Syntax errors occur when statements are missing information, when statements
have extra information, when names are misspelled, etc. When a syntax error occurs, a
dialog like Fig. 3.8 is displayed. Note that some syntax errors are not generated until the
programmer attempts to enter run mode.
Testing and Debugging Tip 3.1
As Visual Basic processes the line you typed, it may find one or more syntax errors. Visual
Basic will display an error message indicating what the problem is and where on the line the
problem is occurring. 3.1
If a statement does not generate syntax errors when the Enter key is pressed, a coloring
scheme (called syntax color highlighting) is imposed on the line of code. Comments are
changed to green. The event procedure names remain black. Words recognized by Visual
Basic (called keywords or reserved words) are changed to blue. Keywords (i.e., Private,
Sub, End, Print, etc.) cannot be used for anything other than for the feature they repre-
sent. In addition to syntax color highlighting, Visual Basic may convert some lowercase let-
ters to uppercase, and vice versa.
Common Programming Error 3.1
Using a keyword as a variable name is a syntax error. 3.1
The colors used for comments, keywords, etc. can be set using the Editor Format tab
in the Options dialog (from the Tools menu). The Option dialog displaying the Editor
Format tab is shown in Fig. 3.9.
Editor
Format
tab
Font
Element choices
that is color
highlighted Font size
choices
Margin
Indicator
Color bar
choices
Sample
area
The TextBox control is introduced in this example. This is the primary control for
obtaining user input. TextBoxes can also be used to display text. In our program one
TextBox accepts input from the user and the other outputs the sum.
Like other controls, TextBoxes have many properties. Text is the most commonly
used TextBox property. The Text property stores the text for the TextBox. Text-
Boxes have their Enabled property set to True by default. If the Enabled property is
set to False, the user cannot interact with the TextBox and any text displayed in the
TextBox is grayed. Object txtSum has its Enabled property set to False. Note that
the text representing the sum appears gray, indicating that it is disabled.
CHAPTER 3 INTRODUCTION TO VISUAL BASIC PROGRAMMING 63
The MaxLength property value limits how many characters can be entered in a
TextBox. The default value is 0, which means that any number of characters can be input.
We set txtInput’s MaxLength value to 5.
The first line of code resides in the general declaration. Statements placed in the gen-
eral declaration are available to every event procedure. The general declaration can be
accessed with the Code window’s Object box. The statement
Dim sum As Integer
declares a variable named sum. A variable is a location in the computer's memory where
a value can be stored for use by a program. A variable name is any valid identifier. Variable
names cannot be keywords and must begin with a letter. The maximum length of a variable
name is 255 characters containing only letters, numbers, and underscores. Visual Basic is
not case-sensitive—uppercase and lowercase letters are treated the same, so a1 and A1 are
considered identical. Keywords appear to be case-sensitive but they are not. Visual Basic
automatically sets to uppercase the first letter of keywords, so typing dim would be
changed to Dim.
Good Programming Practice 3.7
Begin each identifier with a lowercase letter. This will allow you to distinguish between a
valid identifier and a keyword. 3.7
Keyword Dim explicitly (i.e., formally) declares variables. The clause beginning with
the keyword As is part of the declaration and describes the variable’s type (i.e., what type
of information can be stored). Integer means that the variable holds Integer values
(i.e., whole numbers such as 8, –22, 0, 31298). Integers are stored in two bytes of
memory and have a range of –32767 to +32768. Integer variables are initialized to 0 by
default. We discuss other data types in the next several chapters.
Common Programming Error 3.3
Exceeding an Integer’s range is a run-time error. 3.3
Variables can also be declared using special symbols called type declaration charac-
ters. For example, the declaration
Dim sum As Integer
The percent sign, %, is the Integer type declaration character. Not all types have type
declaration characters.
64 INTRODUCTION TO VISUAL BASIC PROGRAMMING CHAPTER 3
Variables can also be declared implicitly (without giving them a formal type) by men-
tioning the name. For example, consider the line
which declares and initializes someVariable. When Visual Basic executes this line,
someVariable is declared and given a value of 8 with assignment operator =. Visual
Basic provides a means of forcing explicit declaration which we discuss later in this chap-
ter.
Good Programming Practice 3.9
Explicitly declaring variables makes programs clearer. 3.9
If a variable is not given a type when its declared, its type defaults to Variant. The
Variant data type can hold any type of value (i.e., Integers, Singles, etc.).
Although the Variant type seems like a convenient type to use, it can be very tricky
determining the type of the value stored. We discuss the Variant type in Chapter 4.
Common Programming Error 3.5
It is an error to assume that the As clause in a declaration distributes to other variables on
the same line. For example, writing the declaration Dim x As Integer, y and assuming
that both x and y would be declared as Integers would be incorrect, when in fact the dec-
laration would declare x to be an Integer and y (by default) to be a Variant. 3.5
Line 4
gets txtInput’s text and adds it to sum, storing the result in sum. To access a property,
use the object’s name followed by a period and the property name. Before the addition op-
erator, +, adds the value input, the Text property value must be converted from a string
(i.e., text) to an Integer. The conversion is done implicitly—no code need be written to
force the conversion.
Common Programming Error 3.6
Expressions or values that cannot be implicitly converted result in run-time errors. 3.6
which uses keyword Let. When writing an assignment statement, keyword Let is option-
al. Our convention is to omit the keyword Let.
The lines
txtInput.Text = ""
txtSum.Text = sum
CHAPTER 3 INTRODUCTION TO VISUAL BASIC PROGRAMMING 65
“clear” the characters from txtInput and display text in txtSum. The pair of double
quotes, "", assigned to txtInput.Text is called an empty string. Assigning an empty
string to txtInput.Text clears the TextBox. When sum (an Integer) is assigned
to txtSum.Text, Visual Basic implicitly converts sum’s value to a string.
places into sum’s memory location the result of adding sum to txtInput.Text. Sup-
pose the value of txtInput.Text is "22". Visual Basic converts the string "22" to
the Integer 22 and adds it to the value contained in sum’s memory location. The result
is then stored in sum’s memory location as shown in Fig. 3.13.
Whenever a value is placed in a memory location, the value replaces the previous value
in that location. The process of storing a value in a memory location is known as destructive
read-in. The statement
that performs the addition involves destructive read-in. This occurs when the result of the
calculation is placed into location sum (destroying the previous value in sum).
Variable sum is used on the right side of the assignment expression. The value con-
tained in sum’s memory location must be read in order to do the addition operation. Thus,
when a value is read out of a memory location, the original value is preserved and the pro-
cess is nondestructive.
3.6 Arithmetic
Most programs perform arithmetic calculations. The arithmetic operators are summarized
in Fig. 3.14. Note the use of various special symbols not used in algebra. The caret (^) in-
dicates exponentiation, and the asterisk (*) indicates multiplication. The Integer divi-
sion operator (\) and the modulus (Mod) operator will be discussed shortly. Most
arithmetic operators are binary operators because they each operate on two operands. For
example, the expression sum + value contains the binary operator + and the two operands
sum and value.
Fig. 3.13 Memory locations showing the names and values of variables.
66 INTRODUCTION TO VISUAL BASIC PROGRAMMING CHAPTER 3
Addition + x+y x + y
Subtraction - z–8 z – 8
Multiplication * yb y * b
Division (float) / v v / u
v / u or --
u
Division (Integer) \ none v \ u
Exponentiation ^ q p q ^ p
Negation - –e —e
Modulus Mod q mod r q Mod r
Visual Basic has separate operators for Integer division (the backslash, \) and
floating-point division (the forward slash, /). Integer division yields an Integer
result; for example, the expression 7 \ 4 evaluates to 1, and the expression 17 \ 5 evalu-
ates to 3. Note that any fractional part in Integer division is rounded before the division
takes place. For example, the expression 7.7 \ 4 would yield 2. The value 7.7 is rounded
to 8. The expression 7.3 \ 4 would yield 1. The value 7.3 is rounded to 7.
Floating-point division yields a floating-point number (i.e., a number with a decimal
point such as 7.7). We will discuss floating-point numbers in Chapter 4.
The modulus operator, Mod, yields the Integer remainder after Integer division.
Like the Integer division operator, the modulus operator rounds any fractional part
before performing the operation. The expression x Mod y yields the remainder after x is
divided by y. A result of 0 indicates that y divides evenly into x. Thus, 20 Mod 5 yields 0,
and 7 Mod 4 yields 3.
The negation operator, -, changes the sign of a number from positive to negative (or
from negative to positive). The expression -8 changes the sign of 8 to negative, which
yields -8. The negation operator is said to be a unary operator, because it operates on only
one operand. The operand must appear to the right of the negation operator.
Arithmetic expressions must be written in straight-line form when entering programs
into the computer. Thus, expressions such as “a raised to the power b” must be written as
a ^ b
so that all constants, variables and operators appear in a straight line. The algebraic notation
ab
is generally not acceptable to compilers, although some special-purpose software packages
do exist that support more natural notation for complex mathematical expressions.
Parentheses are used in expressions in much the same manner as in algebraic expres-
sions. For example, to multiply b times the quantity e + n we write
b * (e + n)
CHAPTER 3 INTRODUCTION TO VISUAL BASIC PROGRAMMING 67
\ Division (Integer) Evaluated fifth. If there are several, they are evaluated left
to right.
Mod Modulus Evaluated sixth. If there are several, they are evaluated
left to right.
+ or - Addition and subtrac- Evaluated last. If there are several, they are evaluated left
tion to right.
Now let us consider several expressions in light of the rules of operator precedence.
Each example lists an algebraic expression and its Visual Basic equivalent.
The following is an example of an arithmetic mean (average) of five terms:
a+b+c+d+e
Algebra: m = ----------------------------------------
5
Visual Basic: m = (a + b + c + d + e) / 5
The parentheses are required because floating-point division has higher precedence
than addition. The entire quantity (a + b + c + d + e) is to be divided by 5. If the paren-
theses are erroneously omitted, we obtain a + b + c + d + e / 5, which evaluates as
e
a + b + c + d + ---
5
The following is the equation of a straight line:
Algebra: y = mx + b
Visual Basic: y = m * x + b
No parentheses are required. Multiplication has a higher precedence than addition and is
applied first.
The following example contains exponentiation, multiplication, floating-point divi-
sion, addition and subtraction operations:
Algebra: z = pr q + w/x – y
Visual Basic: Z = p * r ^ q + w / x – y
6 2 1 4 3 5
The circled numbers under the statement indicate the order in which the operators are ap-
plied. The exponentiation operator is evaluated first. The multiplication and floating-point
division operators are evaluated next in left-to-right order since they have higher prece-
dence than assignment, addition and subtraction. Addition and subtraction operators are
evaluated next in left-to-right order (addition followed by subtraction). The assignment op-
erator is evaluated last.
CHAPTER 3 INTRODUCTION TO VISUAL BASIC PROGRAMMING 69
Not all expressions with several pairs of parentheses contain nested parentheses. For
example, the expression
a * (b + c) + c * (d + e)
does not contain nested parentheses. Rather, the parentheses are said to be on the same level
of precedence.
To develop a better understanding of the rules of operator precedence, consider how a
second-degree polynomial is evaluated.
y = a * x ^ 2 + b * x + c
6 2 1 4 3 5
The circled numbers under the statement indicate the order in which Visual Basic applies
the operators.
Suppose that variables a, b, c and x are initialized as follows: a = 2, b = 3, c = 7 and
x = 5. Figure 3.16 illustrates the order in which the operators are applied in the preceding
second-degree polynomial.
Step 1. y = 2 * 5 ^ 5 + 3 * 5 + 7
5 ^ 5 is 25 (Exponentiation)
Step 2. y = 2 * 25 + 3 * 5 + 7
2 * 25 is 50 (Leftmost multiplication)
Step 3. y = 50 + 3 * 5 + 7
Step 4. y = 50 + 15 + 7
50 + 15 is 65 (Leftmost addition)
Step 5. y = 65 + 7
65 + 7 is 72 (Last addition)
y = (a * x ^ 2) + (b * x) + c
= = d = g d is equal to g
≠ <> s <> r s is not equal to r
> > y > i y is greater than i
< < p < m p is less than m
≥ >= c >= e c is greater than or equal to e
≤ <= m <= s m is less than or equal to s
The next example uses six If/Then statements to compare two numbers input by the
user. The GUI is shown in Fig. 3.18, the properties in Fig. 3.19 and the code in Fig. 3.20.
Fig. 3.19 Object properties for program that compares two Integers.
CHAPTER 3 INTRODUCTION TO VISUAL BASIC PROGRAMMING 73
The statement
74 INTRODUCTION TO VISUAL BASIC PROGRAMMING CHAPTER 3
Option Explicit
Note that Fig. 3.21 labels a few Editor tab features relevant to our earlier discussion
of Full Module View (Fig. 3.6). The user can also set the number of spaces that corre-
sponds to a tab in the Tab Width TextBox.
Forces explicit
declarations by adding
the line Option
Explicit to the
general declaration
(when checked)
Full Module
View is the
default when
checked
When checked,
displays Procedure
Separator lines in Full
Module View
Function InputBox is used to get the values for num1 and num2 with the lines
num1 = InputBox("Enter first integer", "Input")
num2 = InputBox("Enter second integer", "Input")
Function InputBox displays an input dialog, which is shown in Fig. 3.22. The first argu-
ment (i.e., "Enter first integer") is the prompt and the second argument (i.e.,
"Input") determines what is displayed in the input dialog’s title bar. When displayed, the
dialog is modal—the user cannot interact with the form until the dialog is closed.
The input dialog contains a Label, two buttons and a TextBox. The Label displays
the first argument passed to InputBox. The user clicks the OK button after entering a
value in the TextBox. The Cancel button is pressed to cancel input. For this example,
the values returned by successive calls to InputBox are assigned to Integers num1
and num2. The text representation of a number is implicitly converted (i.e., "78" is con-
verted to 78). If a value entered cannot be properly converted, a run-time error occurs.
Pressing Cancel also creates a run-time error, because the empty string cannot be con-
verted to an Integer. We discuss handling run-time errors in Chapter 13.
The line
If num1 = num2 Then
compares the contents of num1 to the contents of num2 for equality. If num1 is equivalent
to num2, the statement
Notice the use of spacing in Fig. 3.20. White-space characters such as tabs and spaces
are normally ignored by the compiler (except when placed inside a set of double quotes).
Statements may be split over several lines if the line-continuation character, _, is used
(e.g., lines 36-38). A minimum of one white-space character must precede the line-contin-
uation character.
Common Programming Error 3.10
Splitting a statement over several lines without the line-continuation character is a syntax
error. 3.10
Several statements may be combined onto a single line by using a colon, :, between
the statements. For example, the two statements
square = number ^ 2
cube = number ^ 3
could be combined on the single line
square = number ^ 2 : cube = number ^ 3
Statements can be spaced according to the programmer's preferences.
CHAPTER 3 INTRODUCTION TO VISUAL BASIC PROGRAMMING 77
Summary
• With visual programming, the programmer has the ability to create graphical user interfaces
(GUIs) by pointing and clicking with the mouse.
• Visual programming eliminates the need for the programmer to write code that generates the form,
code for all the form’s properties, code for form placement on the screen, code to create and place
a Label on the form, code to change foreground and background colors, etc.
• The programmer creates the GUI and writes code to describe what happens when the user interacts
(clicks, presses a key, double-clicks, etc.) with the GUI. These interactions, called events, are
passed into the program by the Windows operating system.
• With event-driven programs, the user dictates the order of program execution.
• Event procedures are bodies of code that respond to events and are automatically generated by the
IDE. All the programmer need do is locate them and add code to respond to the events. Only events
relevant to a particular program need be coded.
• The Properties window contains the Object box that determines which object’s properties are
displayed. The Object box lists the form and all objects on the form. An object’s properties are
displayed in the Properties window when an object is clicked.
• Property TabIndex determines which control gets the focus (i.e., becomes the active control)
when the Tab key is pressed at runtime. The control with a TabIndex value of 0 gets the initial
focus. Pressing the Tab key at runtime transfers the focus to the control with a TabIndex of 1.
• Pressing the End button terminates the program.
• Code is written in the Code window. The Code window is displayed by clicking the Properties
window’s View Code button.
• Visual Basic creates the event procedure name by appending the event type (Click) to the prop-
erty Name (with an underscore _ added). Private Sub marks the beginning of the procedure.
The End Sub statement marks the end of the procedure. Code the programmer wants executed is
placed between the procedure definition header and the end of the procedure (i.e., End Sub).
• The Object box lists the form and all objects associated with the form. The Procedure box lists
the procedures associated with the object displayed in the Object box.
• Programmers insert comments to document programs and improve program readability. Com-
ments also help other people read and understand the program code. Comments do not cause the
computer to perform any action when a program is run. A comment can begin with either ' or Rem
(for “remark”) and is a single-line comment that terminates at the end of the current line.
• A program can print on the form using the Print method. Drawing directly on the form using
Print is not the best way of displaying information, especially if the form contains controls be-
cause a control can hide text that is displayed with Print. This problem is solved by displaying
the text in a control.
• The End statement terminates program execution (i.e., places the IDE in design mode).
• When a line of code is typed and Enter pressed, Visual Basic responds either by generating a syn-
tax error (also called a compile error) or by changing the colors on the line.
78 INTRODUCTION TO VISUAL BASIC PROGRAMMING CHAPTER 3
• A syntax error is a violation of the language syntax (i.e., a statement is not written correctly). As
a general rule, syntax errors tend to occur when statements are missing information, statements
have extra information, names are misspelled, etc.
• If a statement does not generate syntax errors when the Enter key is pressed, a coloring scheme
(called syntax-color highlighting) is imposed on the line of code. Comments are changed to green.
The event procedure names remain black. Words recognized by Visual Basic are called keywords
(also called reserved words) and appear blue.
• Keywords (i.e., Private, Sub, End, Print, etc.) cannot be used for anything other than for the
feature they represent. Any improper use results in a syntax error. In addition to syntax color high-
lighting, Visual Basic may convert some lowercase letters to uppercase, and vice versa. The colors
used for comments, keywords, etc. can be set using the Editor Format tab in the Options dialog
(from the Tools menu).
• The TextBox control is the primary control for obtaining user input. TextBoxes can also be
used to display text.
• Text is the most commonly used TextBox property. The Text property stores the text for the
TextBox. TextBoxes have their Enabled property set to True by default. If the Enabled
property is False, the user cannot interact with the TextBox.
• The MaxLength property value limits how many characters can be entered in a TextBox. The
default value is 0, which means that any number of characters can be input.
• Code that resides in the general declaration is available to every event procedure. The general dec-
laration can be accessed with the Code window’s Object box.
• A variable is a location in the computer's memory where a value can be stored for use by a pro-
gram. A variable name is any valid identifier. Variable names cannot be keywords and must begin
with a letter. The maximum length of a variable name is 255 characters containing only letters,
numbers and underscores.
• Visual Basic is not case-sensitive—uppercase and lowercase letters are treated the same.
• Keyword Dim explicitly declares variables. Keyword As describes the variable’s type (i.e., what
type of information can be stored). Integer means that the variable holds Integer values (i.e.,
whole numbers such as 8, –22, 0, 31298). Integers have a range of +32768 to –32767. Inte-
ger variables are initialized to 0 by default.
• Variables can also be declared special symbols called type-declaration characters such as the per-
cent sign, %, for Integer. Not all types have type declaration characters.
• If a variable is not given a type when its declared, its type defaults to Variant. The Variant
data type can hold any type of value (i.e., Integers, Singles, etc.).
• When writing an assignment statement, the keyword Let is optional.
• The pair of double quotes, "", is called an empty string. Assigning an empty string to a Text-
Box’s Text property “clears” the TextBox.
• Variable names correspond to locations in the computer's memory. Every variable has a name, a
type, a size and a value.
• Whenever a value is placed in memory, the value replaces the previous value in that location. Stor-
ing a value in a memory location is known as destructive read-in. When a value is read out of a
memory location, the process is nondestructive.
• Caret (^) indicates exponentiation and asterisk (*) indicates multiplication.
• Most of the arithmetic operators are binary operators because they each operate on two operands.
• Visual Basic has separate operators for Integer and floating-point division. Integer division
yields an Integer result. Fractional parts in Integer division are rounded before the division.
CHAPTER 3 INTRODUCTION TO VISUAL BASIC PROGRAMMING 79
Terminology
addition operator, + binary operator
arithmetic operators button
As keyword Cancel button
assignment operator, = caret, ^
asterisk, * Code window
80 INTRODUCTION TO VISUAL BASIC PROGRAMMING CHAPTER 3
3.7 Reversing the order of the symbols in the operators <>, >= and <= as in ><, => and =<,
respectively, are syntax errors.
3.8 Writing a statement such as x = y = 0 and assuming that the variables x and y are both
assigned zero, when in fact comparisons are taking place. This can lead to subtle logic errors.
3.9 If variable names are misspelled when not using Option Explicit, a misspelled variable
name will be declared and initialized to zero, usually resulting in a run-time logic error.
3.10 Splitting a statement over several lines without the line-continuation character is a syntax
error.
3.11 Not preceding the line-continuation character with at least one white-space character is a
syntax error.
3.12 Placing anything, including comments, after a line-continuation character is a syntax error.
3.13 Splitting an identifier or a keyword is a syntax error.
Self-Review Exercises
3.1 Fill in the blanks in each of the following:
a) Keywords begin the body of an event procedure and keywords end
the body of an event procedure.
b) When a value is placed into a memory location, it is known as read-in.
c) What arithmetic operation(s) is/are on the same level of precedence as multiplication?
d) When parentheses are nested in an arithmetic expression, which set of parentheses is
evaluated first?
e) A location in a computer's memory that may contain different values at various times
throughout program execution is called a .
f) By default, Integer variables are initialized to the value .
3.2 State whether each of the following is true or false. If false, explain why.
a) A comment’s text is printed on the form as the comment is executed.
b) The Rem statement stores a string in the Visual Basic variable Remark.
c) Option Explicit forces explicit variable declaration.
d) All variables, when declared explicitly, must be given a data type either by using the As
keyword or by using a type-declaration character (if the data type has one).
e) The variables number and NuMbEr are identical.
f) Declarations can appear almost anywhere in the body of an event procedure.
g) The modulus operator, Mod, can be used only with Integer operands. Attempts to use
floating-point numbers (e.g., 19.88, 801.93, 3.14159, etc.) are syntax errors.
h) The arithmetic operators *, / and \ all have the same level of precedence.
i) Visual Basic syntax always requires arithmetic expressions to be enclosed in parenthe-
ses—otherwise, syntax errors occur.
d) Assign the sum of x, y and z to the variable sum. Assume that each variable is of type
Integer.
e) Decrement the variable count by 1, then subtract it from the variable total, and as-
sign the result to the variable u. Assume all variables to be of type Integer.
f) Assign the product of the Integer variables r, i, m, e and s to the variable g.
g) Calculate the remainder after total is divided by counter and assign the result to
remainder. Assume the variables to be of type Integer.
h) Assign the value returned from function InputBox to the variable userInput. The
function InputBox should display the message “Enter your data.” The Input-
Box's title bar should display “Data Input.” Assume the variable userInput to be
of type Integer.
3.5 Write a statement or comment to accomplish each of the following:
a) State that a program will calculate the product of three Integers.
b) Print the message “printing to the form” on the form using the Print method.
c) Force variable declarations.
d) Compute the Integer average of the three Integers contained in variables x, y and
z, and assign the result to the Integer variable result.
e) Print on the form “The product is” followed by the value of the Integer variable
result.
f) Compare the Integer variables sum1 and sum2 for equality. If the result is true, set
the Integer variable flag to 76.
3.6 Identify and correct the error(s) in each of the following statements:
a) Dim False As Integer
b) Dim variable, inputValue As Integers
c) Integer oscii Rem declare variable
d) a + b = c ’ add a, b and assign result to c
e) d = t Modulus r + 50
f) variable = -65800 ’ variable is of type Integer
g) " Change BackColor property’s value
h) If (x > y)
frmMyForm.Print x
i) Dim triplett As Integer, picks As Integer, End As Integer
j) triplett = picks = 10 ’ Initialize both variables to 10
k) x : y = oldValue Rem assign oldValue to both x and y
3.7 Given the equation b = 8e5 – n, which of the following, if any, are correct statements for this
equation?
a) b = 8 * e ^ 5 - n
b) b = ( 8 * e ) ^ 5 - n
c) b = 8 * ( e ^ 5 ) - n
d) b = 8 * e ^ ( 5 - n )
e) b = ( 8 * e ) ^ ( ( 5 ) - n )
f) b = 8 * e * e ^ 4 - n
3.8 State the order of evaluation of the operators in each of the following statements, and show
the value of m after each statement is performed. Assume m to be an Integer variable.
a) m = 7 + 3 * 6 \ 2 - 1
b) m = 2 Mod 2 + 2 * 2 - 2 / 2
c) m = 8 + 10 \ 2 * 5 - 16 \ 2
d) m = -5 - 8 Mod 4 + 7 * (2 ^ 2 + 2)
e) m = 10 Mod 3 ^ 1 ^ 2 - 8
84 INTRODUCTION TO VISUAL BASIC PROGRAMMING CHAPTER 3
3.7 a, c, f.
3.8 a) m = 7 + 3 * 6 \ 2 - 1
m = 7 + 18 \ 2 - 1
m = 7 + 9 - 1
m = 16 - 1
m = 15
b) m = 2 Mod 2 + 2 * 2 - 2 / 2
m = 2 Mod 2 + 4 - 2 / 2
m = 2 Mod 2 + 4 - 1
m = 0 + 4 - 1
m = 4 - 1
m = 3
c) m = 8 + 10 \ 2 * 5 - 16 \ 2
m = 8 + 10 \ 10 - 16 \ 2
m = 8 + 1 - 16 \ 2
m = 8 + 1 - 8
m = 9 - 8
m = 1
d) m = -5 - 8 Mod 4 + 7 * (2 ^ 2 + 2)
m = -5 - 8 Mod 4 + 7 * (4 + 2)
m = -5 - 8 Mod 4 + 7 * 6
m = -5 - 8 Mod 4 + 42
m = -5 - 0 + 42
m = -5 + 42
m = 37
e) m = 10 Mod 3 ^ 1 ^ 2 - 8
m = 10 Mod 3 ^ 1 - 8
m = 10 Mod 3 - 8
m = 1 - 8
m = -7
Exercises
3.9 Identify and correct the error(s) in each of the following statements:
a) Assume that Option Explicit has been set.
Dim x As Integer
If c =< j Then
x = 79
frmMyForm.Print x
End If
3.10 Write a single statement or line that accomplishes each of the following:
a) Print the message "Visual Basic 6!!!!" on the form.
b) Assign the product of variables width22 and height88 to variable area51.
c) State that a program performs a sample payroll calculation (i.e., use text that helps to doc-
ument a program).
d) Calculate the area of a circle and assign it to the Integer variable circleArea. Use
the formula area = (πr2), the variable radius and the value 3.14159 for π.
e) Concatenate the following two strings using the string concatenation operator and assign
the result to Label lblHoliday's Caption: "Merry Christmas" and " and
a Happy New Year".
3.12 State which of the following are true and which are false. If false, explain why.
a) Integer division has the same precedence as floating-point division.
b) The following are all valid variable names: _under_bar_, m928134, majestic12,
her_sales, hisAccountTotal, cmdWrite, b, creditCardBalance1999,
YEAR_TO_DATE, __VoLs__LiSt__.
c) The statement squareArea = side ^ 2 is a typical example of an assignment state-
ment.
CHAPTER 3 INTRODUCTION TO VISUAL BASIC PROGRAMMING 87
d) A valid arithmetic expression with no parentheses is evaluated from left to right regard-
less of the operators used in that expression.
e) The following are all invalid variable names: 2quarts, 1988, &67h2, vols88,
*true_or_FALSE, 99_DEGREES, _this, Then.
f) Visual Basic automatically generates the beginning and end code of event procedures.
3.13 Given the following declarations, list the type for each variable declared.
a) Dim traveler88 As Integer
b) number% = 76
c) Dim cars As Integer, trucks
d) Dim touchDowns, fieldGoals As Integer
e) portNumber = 80 ’ Implicit declaration
3.14 Given the equation y = ax3 + 7, which of the following, if any, are correct statements for this
equation?
a) y = a * ( x ^ 3 + 7 )
b) y = ( a * x ) ^ 3 ) + 7
c) y = ( a * x * x * x + 7 )
d) y = ( a * ( x * ( x * x ) ) + 7 )
e) y = ( a * ( x * x ) ^ 2 ) + 7
f) y = (a) * (x) * (x) * (x) + (7)
3.15 State the order of evaluation of the operators in each of the following statements, and show
the value of x after each statement is performed. Assume x to be an Integer variable.
a) x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) ) ) )
b) x = 1 + 2 * 3 - 4 / 4 - 12 \ 6 * 6
c) x = ( ( 10 - 4 * 2 ) \ 2 + ( 13 - 2 * 5 ) ) ^ 2
d) x = 8.2 Mod 3 + 2 / 2 - -3
e) x = -2 + 7.4 \ 5 - 6 / 4 Mod 2
3.16 Which, if any, of the following statements contain variables involved in destructive read-in?
a) myVariable = txtTextBox.Text
b) V = O + L + S + 8 * 8
c) Print "Destructive read-in"
d) Print "a = 8"
e) Print x = 22
f) Print userName
3.17 What, if anything, prints when each of the following statements is performed? If nothing
prints, then answer "nothing." Assume that x = 2 and y = 3.
a) Print x
b) Print -y ^ 2
c) Print x + x
d) Print "x ="
e) txtTextBox.Text = "x + y"
f) z = x + y
g) Print x + y * 4 ^ 2 / 4 & " is the magic number!"
3.18 Write a program that inputs three different Integers using function InputBox and prints
the sum, the average, the product, the smallest and the largest of these numbers on the form using
Print. Use only the single-selection version of the If/Then statement you learned in this chapter.
88 INTRODUCTION TO VISUAL BASIC PROGRAMMING CHAPTER 3
Provide an Exit button to terminate program execution. (Hint: Each Print statement is similar to
Print "Sum is "; sum. The semicolon (;) instructs Visual Basic to print the variable's value
immediately after the last character printed.)
3.19 Write a program that reads in the radius of a circle as an Integer and prints the circle's
diameter, circumference and area to the form using the Print method. Do each of these calculations
inside a Print statement. Use the following formulas (r is the radius): diameter = 2r, circumference
= 2πr, area = πr2. Use the value 3.14159 for π. (Note: In this chapter, we have discussed only In-
teger variables. In Chapter 4 we will discuss floating-point numbers (i.e., values that can have dec-
imal points and data type Single).
3.20 Enhance Exercise 3.19 by displaying the diameter, circumference and area in Labels.
3.21 Write a temperature conversion program that converts a Fahrenheit temperature to a Celsius
temperature. Provide a TextBox for user input and a Label for displaying the converted tempera-
ture. Provide a Input button to read the value from the TextBox. Also provide the user with an Exit
button to end program execution. Use the following formula: Celsius = 5 / 9 x (Fahrenheit – 32).
3.22 Enhance Exercise 3.21 to provide a conversion from Fahrenheit to Kelvin. Display the con-
verted Kelvin temperature in a second Label. Use the formula: Kelvin = Celsius + 273.