Advanced Visual Programming

Advanced Visual Programming
Advanced Visual Programming
Need for Visual Programming, Advantages and Disadvantages of Visual Programming, Event based
Introduction to Visual Basic, Visual Basic Editions, Writing Visual Basic Projects,
Positioning of Controls, Coding with Controls, Code writing mechanics, understanding numbering systems,
Coding for controls, focus, setting tab orders.
coding basics, use of variables and literals, declaring variables, storing and retrieving data in variables, use of
constants and operators, creating your own constants, arithmetic operators and expressions, logical operators
Decision structure, and introduction to looping constructs
Types of arrays, adding controls at run time, menus, designing a menu, attaching code to menus, introduction to
procedures, event procedures, working with procedures, multiple forms, standard code modules
1. J. David Kruglirski, “Programming Microsoft Visual C++”, Fifth Edition, Microsoft press
2. Marion Cottingham “Visual Basic”, Peachpit Press
3. Steve Holzner, “Visual C++ 6 programming”, Wiley Dreamtech India Private Ltd.
4. Kate Gregory “Using Visual C++”, Prentice Hall of India Pvt., Ltd
Welcome to the first step to word the process of learning Visual
By far the largest changes have been made in the area of database
Basic Programming. This course pack fills the gap between the
access. There are several new data bound control, as well as new
beginners Visual Basic programmer and the professional one.
ActiveX Data Control that combines the functionality of the
In this processing you will learn about the basic concept of
standard Data Control and the remote Data Control.
designing and the creation that you can apply to any Windows
A form Layout windows has been added to the environment
applications you might create in future.
allowing you to position you
In the beginning you will learn about the basic Visual Basic
Application’s forms by visual Positioning a small representation
Interface and Programming language. In the learning processing
of it in a screen display at design time. If you are working with
you should familiar and comfortable withal the aspects of
several projects that will included in a single application, such as
developing a professional a Windows Application Method.
custom controls and programs, you can now have them all
You should also understand the concept of Visual Basic Project
included in a single project group. This will allows you to work
concept, which include forms, Modules and New Controls that
with multiple projects within a single instance of visual Basic.
have been added in this courses pack. There are even more
function, feature, and tools that you will use while creating an
Lesson No.
Page No.
Visual Basic Programming
Visual Basic Programming
Lesson 1
Introduction To Visual Basic
Lesson 2
Visual Basic Programming Part 2
Analyzing Visual Basic Programs
Lesson 3
Introduction To Events
Analyzing Visual Basic Programs Part 2
Lesson 4
Event Procedures
Controls and Properties
Lesson 5
Creation Of Application
Controls and Properties Part 2
Lesson 6
Tools Tips Feature
How to Create Labels, Buttons, and Text Boxes
Lesson 7
Labels, Buttons And Its Properties
Coding In Visual Basic
Lesson 8
Coding Basic
Coding In Visual Basic Part 2
Lesson 9
Coding Basic (The Dim Statements Location)
Advance Programming
Improvements In Coding
Lesson 10
Lesson 11
Message Box And Input Box
Working With Comparison Operators
Making Decisions Part 2
Lesson 12
Compound Comparisons with the Logical Operators
Visual Basic Looping Part
Lesson 13
Looping And Coding
Lesson 14
Looping And Coding Part 2
Combining Code and Controls
Lesson No.
Lesson 15
Calculation Application And Control Arrays
Page No.
Combining Code and Controls
Lesson 16
Calculation Application And Control Arrays Part
List Boxes and Data Lists
Lesson 17
Basic of List Boxes and Data Lists Control
List Boxes and Data Lists Part 2
Lesson 18
Data Arrays And Control Arrays
Additional Controls
Lesson 19
Frame And Option Button
Learning Objectives
Introduction of Visual Basic
What Visual Basic does
How to start Visual Basic
Introduction of Visual Basic
Controls are tools on the Toolbox window that you place on a
form to interact with the user and control the program flow.
Microsoft Visual Basic 6.0, the latest and greatest incarnation of
the old BASIC language, gives you a complete Windows
application development system in one package. Visual Basic (or
VB, as we often call it) lets you write, edit, and test Windows
applications. In addition, VB includes tools you can use to write
and compile help files, ActiveX controls, and even Internet
New Term: A program is a set of instructions that make the
computer do something such as perform accounting. (The term
program is often used synonymously with application.)
Visual Basic is itself a Windows application. You load and
execute the VB system just as you do other Windows programs. You will use this running VB program to create other
programs. VB is just a tool, albeit an extremely powerful tool,
that programmers (people who write programs) use to write,
test, and run Windows applications.
New Term: A project is a collection of files you create that
comprises your Windows application.
Although programmers often use the terms program and
application interchangeably (as will be done throughout this 24lesson course), the term application seems to fit the best when
you’re describing a Windows program because a Windows
program typically consists of several files. These files work
together in the form of a project. The project generates the final
program that the user loads and runs from Windows by
double-clicking an icon or by starting the application with the
Windows Start menu.
New Term: An application is a collection of one or more files
that compile into an executable program.
The role of programming tools has evolved over the past 45
years along with computer hardware. A programming language
today, such as Visual Basic, differs greatly from programming
languages of just a few years ago. The visual nature of the
Windows operating system requires more advanced tools than
were available a few years ago. Before windowed environments,
a programming language was a simple text-based tool with
which you wrote programs. Today you need much more than
just a language; you need a graphical development tool that can
work inside the Windows system and create applications that
take advantage of all the graphical, multimedia, online, and
multiprocessed activities that Windows offers. Visual Basic is
such a tool. More than a language, Visual Basic lets you generate
applications that interact with every aspect of today’s Windows
operating systems.
NOTE: Although Visual Basic is a comprehensive programming tool, VB retains its BASIC language heritage. Designers in
the late 1950s developed the BASIC programming language for
beginning programmers. BASIC was easier to use than other
programming languages of the time, such as COBOL and
FORTRAN. Microsoft never forgot VB’s roots when developing Visual Basic. Newcomers to programming can learn to create
simple but working Windows programs in just a short time.
You will be using Visual Basic to write Windows programs
before the next lesson is complete.
New Term: Wizards are question-and-answer dialog boxes
that automate tasks.
New Term: A compiler is a system that converts the program
you write into a computer-executable application.
If you’ve taken a look at Visual Basic in the past, you’ll be
amazed at today’s Visual Basic system. VB now sports a true
compiler that creates standalone runtime .EXE files that execute
more quickly than previous VB programs. VB also includes
several wizards that offer step-by-step dialog box questions that
guide you through the creation of applications. VB’s development platform, a development environment called the
Developer Studio, now supports the same features as the
advanced Visual C++ and Visual J++ compilers. Therefore,
once you learn one of Microsoft’s Visual programming
products, you will have the skills to use the other language
products without a long learning curve ahead of you.
New Term: The Developer Studio is Visual Basic’s development environment.
Programming languages today are not what they used to be.
The language itself has not gotten less important; rather, the
graphical interfaces to applications have gotten more important.
A computer cannot understand any person’s spoken language.
A spoken language, such as Italian or English, is simply too
general and ambiguous for computers to understand. Therefore, we must adapt to the machine and learn a language that
the computer can understand. VB’s programming language is
fairly simple and uses common English words and phrases for
the most part. The language is not ambiguous, however. When
you write a statement in the Visual Basic language, the statement never has multiple meanings within the same context.
New Term: Code is another name for the programming
statements you write.
As you progress through the next 24 lesson, you will learn
more and more of the Visual Basic language’s vocabulary and
syntax (grammar, punctuation, and spelling rules). You will use
the VB programming language to embed instructions within
applications you create. All the code you write (code is the
program’s instructions) must work together to instruct the
computer. Code is the glue that ties all the graphics, text, and
processes together within an application. Code tells a checkbook
application, for example, how to be a checkbook application and
not something else. The program code lets the application
know what to do given a wide variety of possible outcomes
and user actions.
Rarely will you perform all these steps sequentially in one sitting.
The six steps are not sequential steps, but stages that you go
through and return to before completing your application.
The VB Programming Process
might be called something different due to installation differences. You will see additional programs listed on the Microsoft
Visual Basic 6.0 submenu, but when you select Visual Basic 6.0
from the submenu, Visual Basic loads and appears on your
When you want to use Visual Basic, you’ll follow these basic
1. Start Visual Basic.
2. Create a new application or load an existing application.
When you create a new application, you might want to use
Visual Basic’s VB Application Wizard to write your
program’s initial shell, as you’ll do in the next lesson.
New Term: A bug is a program error that you must correct
(debug) before your program executes properly.
3. Test your application with the debugging tools Visual Basic
supplies. The debugging tools help you locate and eliminate
program errors (called bugs) that can appear despite your
best efforts to keep them out.
4. Compile your program into a final application.
5. Quit Visual Basic.
6. Distribute the application to your users.
Starting Visual Basic
You start Visual Basic from the Windows Start menu. The
Visual Basic development environment itself usually appears
on a submenu called Microsoft Visual Basic 6.0, although yours
On most systems, Figure 1.1’s dialog box appears as soon as
you start Visual Basic. The dialog box lets you start the VB
Application Wizard, edit an existing VB project, or select from a
list of recent projects you’ve worked on, depending on the
dialog box tab you click.
As you can see at the bottom of the dialog box, you don’t have
to see the dialog box every time you start Visual Basic. If you
click the option labeled Don’t show this dialog box in the
future, Visual Basic will not display the opening dialog box
when you start Visual Basic.
Figure 1.1. The New Project dialog box often appears when
you start VB.
Note:If you decide not to show the New Project dialog box for
subsequent start-ups, you will still be able to access the dialog
box’s operations from VB’s File menu.
Once you close the dialog box, the regular Visual Basic screen
appears. As Figure 1.2 shows, VB’s opening screen can get busy!
Figure 1.2 shows the Visual Basic development environment,
the environment with which you will become intimately familiar
soon. From this development environment you will create
Windows programs.
Figure 1.2. VB’s screen looks confusing at first.
Although the screen can look confusing, you can fully customize the Visual Basic screen to suit your needs and preferences.
Over time, you will adjust the screen’s window sizes and hide
and display certain windows so that your Visual Basic screen’s
start-up state might differ tremendously from that of
Figure 1.2.
New Term: A dockable window is a window that you can
resize and move to the sides of the screen and connect to other
TIP:Most of VB’s windows are sizable and dockable, meaning
you can connect them together, move them, and hide them.
This lesson’s section titled “Mastering the Development
Environment” explains the parts of the development environment and how to maneuver within it.
Learning Objectives
How to stop Visual Basic
When to use the different Visual Basic windows
How the system windows work together for you
Stopping Visual Basic
You’ll exit from Visual Basic and return to Windows the same
way you exit most Windows applications: Select File|Exit, click
Visual Basic’s main window close button, press Alt+F4, or
double-click VB’s Control menu icon that appears in the upperleft corner of the screen.
If you have made changes to one or more files within the
currently open project (remember that a project is the collection
of files that comprise your application), Visual Basic gives you
one last chance to save your work before quitting to Windows.
Never power-off your computer without completely exiting
Visual Basic, or you might lose some or all of your work for the
current session.
Mastering the Development
Learning the ins and outs of the development environment
before you learn Visual Basic is somewhat like learning the parts
of an automobile before you learn to drive; you might have a
tendency to skip the terms and jump into the foray. If, however,
you take the time to learn some of the development
environment’s more fundamental principles, you will be better
able to learn Visual Basic. You then will be more comfortable
within VB’s environment and will have a better understanding
of the related words when subsequent lessons refer to the
windows and tools in the development environment.
The Visual Basic development environment with many of the
more important screen components labeled. As you can see
from the menu and toolbar, Visual Basic looks somewhat like
other Windows programs on the market. Many of Visual
Basic’s menu bar commands work just as they do in other
applications such as Microsoft Word. For example, you can
select Edit|Cut and Edit|Paste to cut and paste text from one
location to another. These same menu bar commands appear
on almost every other Windows program on the market today.
Note: only a portion of the development environment’s
windows and components. As you need additional tools, such
as the Menu Editor, this tutorial describes how you access those
Standards: The Menu Bar and Toolbar
Visual Basic’s menu bar and toolbars work just as you expect
them to. You can click or press a menu bar option’s hotkey (for
example, Alt+F displays the File menu) to see a pull-down list
of menu options that provides either commands, another level
of menus, or dialog boxes. Many of the menu options have
shortcut keys (often called accelerator keys) such as Ctrl+S for
the File|Save option. When you press an accelerator key, you
don’t first have to display the menu to access the option.
The toolbar provides one-button access to many common
menu commands. Instead of selecting Edit|Paste, for example,
you could click the Paste toolbar button. As with most of
today’s Windows applications, Visual Basic supports a wide
range of toolbars. Select View|Toolbars to see a list of available
toolbars. Each one that is currently showing will appear with a
checkmark by its name.
Tip:As you begin to work with Visual Basic, pay attention to
the form location and form size coordinates at the left of the
toolbar buttons. These measurements, in twips (a twip is
1,440th of an inch, the smallest screen measurement you can
adjust), determine where the Form window appears and its
size. Twip values usually appear in pairs. The first location value
describes the x-coordinate (the number of twips from the top
of the screen) and the second value describes the y-coordinate
(the number of twips from the left of the screen), with 0,0
indicating the upper-left corner of the screen. The first size value
describes the width of the form, and the second size value
describes the height of the form. Therefore, the size coordinate
pair 1000,3000 indicates that the Form window will be 1,000
twips wide and 3,000 twips tall when the program runs. As
you’ll learn in the next section, the Form window is the primary
window for the applications you write. The location and size
coordinates describe the form’s location and size when you run
the application.
The Form Window: Where it all happens
The Form window is your primary work area. Although the
Form window first appears small relative to the rest of your
screen, the Form window comprises the background of your
application. In other words, if you write a Windows-based
calculator with Visual Basic, the calculator’s buttons all reside on
the Form window and when someone runs the calculator, the
calculator that appears is really just the application’s Form
window with components placed there and tied together with
Note:You will not see program code on the Form window. The
Form window holds the program’s interactive objects, such as
command buttons, labels, text boxes, scrollbars, and other
controls. The code appears elsewhere in a special window called
the Code window. The Code window does not appear in Figure
1.3, but you can select View|Code to see the Code window. A
Code window is little more than a text editor with which you
write the programming statements that tie together the
Consider the sample program running in Figure 1.4’s window.
The window shows a simple dialog box with a few options,
text boxes, and command buttons.
The programmer who created Figure 1.4’s dialog box did so by
opening a Form window, adding some controls (the items on
the Form window that interact with the user-sometimes called
tools), and tying the components together with some Visual
Basic language code. That’s exactly what you will do when
writing simple and complex Visual Basic applications. You will
begin with a blank Form window and add controls to the Form
window such as options and command buttons. Perhaps your
application might even require multiple Form windows.
Note: Some applications, such as Word, allow for several Form
windows in a special mode called MDI (multiple-document
interface) in which you can open multiple data documents
within the same application. An application that requires only a
single data window is called an SDI (single-document interface)
application, such as the Windows Notepad application that lets
the user open only one data document at a time. SDI applications might support multiple forms; however, these forms do
not hold multiple data files but only provide extended support
for extra dialog boxes and secondary work screens.
Compare Figure 1.4 with Figure 1.5. As you can see, Figure 1.5
shows the same application in the VB development environment. Figure 1.5 shows the application in its design-time state
as opposed to its runtime state, which is shown in Figure 1.4. It
is during design time that you design, create, edit, and correct
the application. When you or another user runs the application,
the results of your work can be seen. Source program is code,
forms, menus, graphics, and help files that you create and edit
to form the project (also called source code).
The parts of the application that you create, such as the forms,
the code, and the graphics that you prepare for output, comprise the source program. When you or another user compiles
or runs the source program, VB translates the program into an
executable program. You cannot make changes directly to an
executable program. If you see bugs when you run the
program, you must change the source application (which might
contain multiple files in the project) and rerun or recompile the
The Toolbox Supplies Controls
The toolbox contains the controls that you place on the Form
window. All of Figure 1.5’s controls appear on the toolbox.
You will learn in the next lesson’s lesson how to place toolbox
controls on the Form window. The toolbox never runs out of
controls; if you place a command button on the Form window,
another awaits you on the toolbox, ready to be placed also.
Figure 1.6 names every tool that appears on the standard
Toolbox window. These are called the intrinsic controls because
all three editions of VB support these standard tools. You can
add additional controls to the toolbox as your needs grow.
Some extra tools come with all three editions of VB, but these
extra tools do not appear on the Toolbox window until you
add them through the Project|Components menu option. If
you use the Professional or Enterprise Editions, you will be
able to add extra controls that don’t appear in the Standard
Edition’s collection of intrinsic and extra controls.
The Form Layout Window Places Forms
The Form Layout window displays the initial position and
relative size of the current form shown in the Form window.
For example, look back at Figure 1.5 to see the Form Layout
window. The application being studied is a multiple-form
application. The form with the title Text Box Properties is just
one of several forms. The Form Layout window always shows
where the form appears in the current Form window. If you
want the form to appear at a different location from the current
position, you can move the form inside the Form Layout
window to move the form’s appearing position when the user
runs the application.
TIP: Notice that the form location indicators, to the right of
the toolbar buttons, change when you move the form in the
Form Layout window.
This book generally does not show the Form Layout window
in figures to give more room to the Form window and its
contents. You can display the Form Layout window from the
View menu, and you can hide the Form Layout window by
clicking its window close button.
The Project Explorer Window
The Project Explorer window, often called the Project window,
gives you a tree-structured view of all the files in the application.
Microsoft changed the formal name from Project window to
Project Explorer window between versions 4 and 5 to celebrate
the resemblance of the window to the typical Explorer-like treestructured file views so prevalent in Windows 95 and NT. You
can expand and collapse branches of the view to get more or
less detail.
The Project Explorer window displays forms, modules (files
that hold supporting code for the application), classes (advanced
modules), and more. When you want to work with a particular
part of the loaded application, double-click the component in
the Project window to bring that component into focus. In
other words, if the Project Explorer window displays three
forms and you need to edit one of the forms, locate and
double-click the form name in the Project window to activate
that form in the Form window. Figure 1.7 shows a Project
Explorer window that contains several kinds of files.
WARNING: If you add a help file to your application, the
Project window does not display the help file.
The Properties Window
New Term: Properties are detailed descriptive information
about a control.
A different list appears in the Properties window every time you
click over a different Form window tool. The Properties
window describes properties (descriptive and functional
information) about the form and its controls. Many properties
exist for almost every object in Visual Basic. The Properties
window lists all the properties of the Form window’s selected
Help Is at Your Fingertips
New Term: Books Online are electronic books about Visual
Basic for the Visual Basic programmer.
Visual Basic’s online help system is one of the most advanced
on the market. When you want help with a control, window,
tool, or command, press F1. Visual Basic analyzes what you are
doing and offers help. In addition, Visual Basic supports a
tremendous help resource called Books Online. When you select
Books Online from the Help menu, Visual Basic displays a treestructured view of books about Visual Basic that you can search
and read. The online help extends to the Internet as well. If you
have an Internet connection, you can browse the latest help
topics by selecting Help|Microsoft on the Web.
This lesson quickly introduced you to Visual Basic. Perhaps you
already can see that Visual Basic is more than it first appears.
Programmers use Visual Basic to create extremely advanced
Windows applications. Now that you understand VB’s purpose
and how to start and stop VB, you’re ready to jump right in.
The next lesson describes a sample application that comes with
Visual Basic so you can get a better picture of how Visual Basic’s
components work together.
Q Must I learn a new language to use Visual Basic?
A Visual Basic is more than just a programming language.
Nevertheless, learning VB’s language portion is integral to
writing advanced applications. Fortunately, the Visual Basic
programming language is one of the easiest programming
languages in existence. The language is simple but powerful
because Microsoft based Visual Basic’s language on BASIC, a
beginner’s language. VB’s simplicity does not translate to
inability, however. Visual Basic is one of the most powerful
Windows programming languages on the market and supports
advanced programming techniques.
Q How can I master the complicated-looking development
A The Developer Studio might look complicated, but only
because you are new to the development environment. The
development environment is little more than a collection of
windows. As you learn more about Visual Basic, you will learn
which windows you need and when you need them; you can
close the other windows. The Developer Studio development
environment is a development platform Microsoft has integrated into most of its language products, including Visual
C++ and Visual J++. Therefore, once you master the development environment, you will already understand the other
language’s development environment as well.
The quiz questions and exercises are provided for your further
understanding. See Appendix C, “Answers,” for answers.
1. What is the purpose of Visual Basic?
2. How have programming languages changed over the years?
3. What programming language is Visual Basic based on?
4. Which Visual Basic development environment window
forms the background for the applications you develop?
5. What are the three editions of Visual Basic and how do they
6. What is the difference between the Form window and the
Form Layout window?
7. How can you tell the width and height of the Form
8. True or false: All the tools you find on the Toolbox window
when you start Visual Basic are the intrinsic controls.
Learning Objecting
Introduction to Evnts
Control Events
How to respond to events
How to Run Application
You will analyze a sample program in depth to learn more
about how a Visual Basic application’s components work
together to form one executable program. Although this lesson
might raise a few more questions than it answers, that’s good!
You need this overall walkthrough before you get your hands
dirty with Visual Basic in Lesson 3, “Controls and Properties.”
Don’t worry, this lesson is not all theory and description! The
final part of this lesson walks you through the building of a
complete Visual Basic application. A little help from the VB
Application Wizard will go a long way.
The highlights of this lesson include
Event-Driven Programs
Lots can happen when a Windows program executes. For
example, consider Figure 2.1’s Microsoft Excel screen. What can
happen next? What exactly will the user at the keyboard do? The
user might click a toolbar button. The user might select a menu
option. The user might press F1 to get help. The user might
scroll the window. The user might enter additional numbers or
formulas. The user might edit existing worksheet cells. The user
might switch to another program. The user might....
Figure 2.1. A Windows program never knows what will happen
In the old days of programming, less than a decade ago, before
windowed environments became so popular, the program
dictated what the user could next do. The program might ask
the user a question, and the user could answer the question and
nothing else until the question was answered. The program
might display a menu of options. Although the user had the
choice of options, the user only had the choice of a menu
selection. If the user wanted to move to another part of the
program, he could not unless such a move was part of the
currently displayed menu.
The multitasking, multiuser windowed environments changed
everything. Today’s Windows program has no idea what might
happen next. The program must offer a plethora of choices that
range from menu options to various controls and data-entry
locations, and the program just has to wait and see what
New Term: An event is something that happens, usually but
not always due to the user at the keyboard, during a program’s
When the programs lost control, users gained. Users can now
perform any one of many tasks. The problem for the program-
mer is responding to users’ actions when so many actions are
possible. Fortunately, Microsoft designed Windows to be
elegant not only for the user but for the programmer as well.
When virtually anything happens in the Windows environment, Windows generates an event. An event might be a
keypress, an internal clock tick, a menu selection, a mouse click, a
mouse movement, a task switch, or one of many hundreds of
other possible events.
Your program does not have to wait around for the user to do
something specific. In text-based programming days, you
would write one big program that guided the user through the
execution of the code step-by-step. The program would take
the user to a menu, ask the user questions, and offer only a
limited set of choices. In many ways, a Visual Basic program is
nothing more than a collection of small routines. These
routines, called event procedures, handle individual events. If
and only if an event occurs for which you’ve written an event
procedure does that event procedure execute. You don’t have to
do anything special to execute the event procedure-just write the
code. In other words, your program responds to events by
supplying a matching event procedure and your program
ignores events if you’ve not written an event procedure.
Control Events
Every control you place on a form supports one or more
events. For example, if you place a text box in the center of the
Form window and run the program, you can click the text box,
enter text in the text box, double-click the text box, and ignore
the text box. The Text Box control happens to support events
that can recognize when you’ve done anything to the control.
If you’ve written an event procedure for that text box’s event,
your code’s instructions will execute automatically as soon as the
event occurs. Therefore, if you’ve written code to blank out the
text box as soon as the user clicks the text box and you’ve
written another event procedure for the double-click event that
fills the text box with X’s when the user double-clicks the text
box, the text box fills with blanks or X’s when you run the
program and click or double-click the text box.
NOTE: You’ll see plenty of examples in this and subsequent
lessons that demonstrate the nature of event procedures.
Analyzing a Sample Application
Perhaps the best way to begin learning about application
creation with Visual Basic is to analyze one of the sample
applications that comes with Visual Basic. You will gain some
practice working within the development environment and you
will master the various windows quickly.
To begin, perform these steps:
1. Start Visual Basic. If the New Project dialog box appears,
close the dialog box because you will open a project without
the dialog box’s help in the next step.
2. Select File | Open Project (a toolbar button does this, too)
to display a list of directory folders from which to choose.
Double-click the folder named samples to display its
contents. You will see various folders with sample projects in
the form named frmVCR is called vcr.frm on the disk. Rarely
will the actual filename match that of the internal name used in
the project. In a way, the three-letter abbreviated prefix works a
lot like the three-letter filename extension in that the prefix
describes the type of object.
3. Double-click the folder named PGuide to display additional
sample folders. Double-click the folder named Vcr to display
the only project file in the folder, named Vcr.vbp (the
extension might not appear if you’ve turned off the display
of filename extensions in Windows Explorer).
The naming rules for internal Visual Basic names differ from
those of files. Therefore, you will need to give each object you
create in the Project window both a filename and an internal VB
name. If you don’t supply a name, Visual Basic supplies one
for you, but Visual Basic is not good at assigning names to
objects. VB would be happy calling every command button on
your form Command1, Command2, and so on. When you
name command buttons, however, you’ll make up names that
better match their meaning, such as cmdOK and cmdExit.
Although only a single filename appears in the Open Project
dialog box, several files actually reside in the Vcr folder. Visual
Basic knows, however, that when you select File | Open Project,
you want to open a project and not another kind of file, so
Visual Basic displays only project files in the dialog box. All
project files end with the .VBP filename extension to distinguish them from form files that end with the .FRM extension
and module files that end with .BAS (other Visual Basic file
types exist, but we won’t cover them here).
The advantage that projects present to the Visual Basic programmer is that a project is a bookkeeping record of the entire
collection of files that comprise an application. When you write
even a simple Visual Basic application, Visual Basic creates a
project for that application so that, as the application’s functionality grows, the project can track all the files related to that
project. No matter how many files go with a project, when you
open the project, Visual Basic puts the project’s files at your
fingertips in the Project window.
Double-click the Vcr.vbp project file now. Double-click the form
named frmVCR in the Project Explorer window if you don’t
see VCR in the Form window. Your development environment
changes dramatically to hold the project, as shown in Figure 2.2.
As you might guess from the name of the project and from the
window in front of you, this application simulates a television
playing a videotape. Click any plus signs you see in the Project
window to expand the list to look like Figure 2.3. You now
know that this application is a collection of five files: two
forms, a module file, and two class files. Actually, a sixth file
goes with the project: the Vcr.vbp project file itself, which
Visual Basic keeps track of and updates as needed.
The Project window describes two important aspects of a VB
project: the external disk drive filenames for each project file and
the internal names used inside the project. For example, the
current form open in the Form window is named frmVCR.
You know this because VB’s title bar names the file currently
showing at the top of your screen and also shows that the file is
a form and not another kind of file.
To every area of your project, the form is called frmVCR. This
form got its name because the program writer named the form
frmVCR. As you’ll see throughout this tutorial, programmers
often precede items they name with a three-letter abbreviation
for the object being named. Thereafter, when you look through
a list of object names, you’ll know just from the names what
the names represent.
The form is not stored on the disk drive under the name
frmVCR, however. As the Project window’s parentheses show,
Naming Objects
As you create applications and add to them objects such as
forms and modules, you will have to come up with lots of
names so that both you and Visual Basic can distinguish one
object from another. Unlike filenames, a name of a Visual Basic
object must begin with an alphabetic character and can contain
letters and numbers, but it cannot contain periods or certain
other special characters. You can mix uppercase and lowercase as
much as you wish. The illegal period is the primary reason why
internal object names differ from filenames.
Generally, as stated previously, programmers prefix a name with
letters representing the kind of object they are naming. The
prefix is often stated in lowercase letters and the rest of the
name often appears as a combination of uppercase and
lowercase letters, with the uppercase letters helping to separate
parts of the name. clsTape is the name of one of the class files
(this book does not dive too deeply into classes, although you’ll
learn some about them as you go along), and cls indicates that
the file is a class file and Tape is the rest of the name to help
describe the contents of that file. (Notice that the programmer
did not precede the VCRModule file with mdl or mod and that
doing so would better describe the file’s module type.)
Display frmVCR form once again. Look at the Form Layout
window to determine where the form will appear on your
screen when you run the application. The next section explains
how to run the application.
Running Applications
You learned in previous lesson, “Visual Basic at Work,” that
you can execute a Visual Basic application by running the
application or by first compiling the application and then
running the executable compiled program. For the majority of
your VB training, you’ll run applications from within the Visual
Basic development environment without taking the time to
compile the application first. Usually, compilation is the last step
a programmer makes before distributing the application to
other users.
Generally, and for all of this tutorial, you’ll run your applications from within the Visual Basic development environment.
When you run within the development environment, you gain
all kinds of advantages that your users will not need. You can
stop the program in midstream and analyze values (using the
debugging tools available in the development environment),
you can start and stop your program at any point, you gain
access to the source code faster each time you stop the program,
and the program’s startup is faster than having to wait on the
TIP: When you are ready to distribute your application, select
File | Make to start the compilation process.
Although several ways exist to run the program, the easiest is to
press F5, the accelerator key for the Run | Start menu option.
(A Start toolbar button also gives you quick access to the
application’s startup.)
NOTE: Right before starting the application, take a quick look
at the Form Layout window. Notice where the primary frmVCR
appears relative to the rest of the screen. When you start the
application, the Form Layout window will prove to be correct;
the Form window appears right where the Form Layout
window showed.
Press F5 now to see the running application. The application
contains VCR-like buttons at the bottom of the form. Click the
Play button (>) to watch Figure 2.5’s butterfly fly across the
television screen. When you change channels, the television
screen color changes, but the flying butterfly is the only program
you can see. Click Set to see the second Form window and click
Eject to close the program.
Now that you’ve seen the Form Layout window in action,
consider closing the window. You’ll rarely use it and it gets in
the way most of the time. You can control the exact twip
location where a form first appears through code, and the Form
Layout window is nice just for testing purposes most of the
When you close the Form Layout window, you’ll have a better
view of the form. Notice all the buttons, windows, text, lights,
stopwatch symbols, and butterfly graphics you see on the form.
All these objects are controls the programmer got from the
WARNING: Don’t confuse the Toolbox window with the
toolbar. The toolbar is the row of buttons that mimics certain
menu options and appears directly beneath the menu bar. The
Toolbox window holds your tools, a collection of controls that
you place on forms.
Code and Events
This lesson began by describing code and event procedures in
detail, and yet not a word has been mentioned about that in
several pages. The code is there, as you can see from the Project
Explorer window. Actually (ignoring the class files for now),
this application contains three sets of code!
The Project window’s Modules entry also is a file with code in it.
A module file that lies outside a form module is often called a
standard module. You’ll place event procedures for forms in the
forms’ form modules, and you’ll place common routines that
work on all the forms in a standard module file that lies outside
the form module but still in the project.
TIP: As you write more code, you will write routines that you
want to use again, such as special calculations that are unique to
your business. By storing these general-purpose routines inside
modules instead of embedding them in form modules that go
with specific applications, you can copy and load the standard
module into multiple applications so that you don’t have to
type the general-purpose code more than once. Therefore, once
you’ve written a useful procedure that calculates or processes
data outside the form’s boundaries, you can reuse that code and
insert the code into other projects as long as you keep the
routines in a standard module file.
New Term: You enter, edit, and view the language of VB in
the Code window.
Visual Basic always presents you with code in the window. A
Code window acts a lot like a simple text editor or word
processor. You can insert, delete, copy, cut, and paste text.
Despite the graphical nature of applications and the controls,
the code you write to tie things together is still in text.
Take a brief look at the application’s single module’s Code
window by double-clicking the Project window’s VCRModule
entry. Visual Basic opens the module’s Code window, as shown
in Figure 2.7.
Code appears in the Code window in various colors to indicate
the purpose of the code. As you learn the Visual Basic language,
you will better understand why some code is green and some
black. Scroll down through the Code window. Don’t worry
about understanding much or anything about the Code
window at this time. As you can see, much of the Code
window contains English words, but the structure might seem
completely odd if you’ve never programmed before. By the
time you finish this 24-lesson tutorial, you will understand the
entire program and be able to speak the Code window’s
language fluently!
Close the module’s Code window for now. To close the
window, you can click the window’s (not VB’s!) close button or
double-click another object in the Project window such as the
primary form named frmVCR. However you close the window,
make sure that you see the VCR form before you start the next
Controls cannot have the same name if you place them on the
same form, but two forms might contain controls with the
same name. A control name goes with its parent form. For
example, an application might contain an About dialog box and
a form that displays account information. Both forms can have
a command button named cmdExit that closes the form’s
window. Each form contains its own code, called the form
module, that manages and responds to the controls on that
form. You won’t always put code in a form’s form module, but
you very frequently will.
Learning Objectives
Event Procedures
Properties and Event Procedures
Generating an Application from Scratch
Event Procedures
Visual Basic makes it easy to locate event procedure code for
controls on forms. Double-click any control to see one of its
event procedures. For example, if you double-click the command button labeled Up, Visual Basic opens the Code window
and places the text cursor in the set of lines that Listing 2.1
Listing 2.1. The Up command buttons Click event procedure
Private Sub cmdUp_Click()
‘ if in range, set the channel number
If vntChannel < 13 Then
vntChannel = vntChannel + 1
vntChannel = 2
End If
‘ assign the channel variable to the display
lblChannel.Caption = vntChannel
End Sub
New Term:Wrapper lines are the first and last lines of a
Don’t sweat the details, but get familiar with the overall event
procedure. Most event procedures begin with the statement
Private Sub and end with End Sub. The Private-End block (a
block is a section of code that goes together as a single unit)
illustrates the first and last lines of the event procedure. The
lines between these wrapper lines comprise the body of the
event procedure.
All controls have unique names, as you saw earlier. All event
procedures also have unique names. An event procedure name
always takes this form:
controlName_eventName ()
WARNING: The parentheses are not actually part of the name.
Some procedures require values inside the parentheses while
others do not. Even if an event procedure requires nothing
inside the parentheses, the parentheses are still required.
The event procedure always consists of the control name, an
underscore, and the procedure’s event name. Therefore, if you
want to respond to both the click and double-click events that
might be applied to the command button named cmdUp, you
would have to write an event procedure named cmdUp_Click()
and one named cmdUp_DblClick().
You don’t have to memorize that the double-click event is
named DblClick and that a keypress event is named KeyDown.
The top of every Code window contains a drop-down list box
that contains every event possible for the control listed in the
right-hand drop-down list box. The left-hand list box holds
the name of every control on the form that this form module
goes with. Again, do not get too bogged down in details
because when it is time to use these drop-down list boxes to
select events, this lesson describes the process in detail.
The naming convention for the event procedure is not up to
you, but up to Visual Basic. In other words, the Click event
procedure for a command button named cmdTest will always
have to be cmdTest_Click(). The two-part name makes the
event procedure extremely specific; from the name both you and
Visual Basic know that the code executes only if the user clicks
the command button named cmdTest.
Properties and Event Procedures
This might be a good time to review properties. When the
programmer (you!) places controls on a form, the programmer
generally sets many of the control’s property values at that time
in the Properties window. A programmer might then write the
event procedure code for the control or the programmer might
place additional controls on the form and write event procedures later.
Many of the properties in the Properties window show up
immediately, during design time, as you assign the properties.
In other words, if you place a command button on a form and
immediately click the Properties window’s Caption property and
type Click Here, the command button instantly reads Click Here
in the Form window.
The event procedure code, however, does not do anything until
runtime. The instructions you learn to place in the event
procedures will not execute until the application’s user runs the
program and triggers events at runtime. The Properties window
often reacts at design time, whereas the Code window often
reacts at runtime.
Generating an Application from Scratch
Enough already! How about a little fun? You can create your
very first Visual Basic application without knowing any more
than you know now about Visual Basic. The secret is Visual
Basic’s VB Application Wizard, a wizard that generates an
application for you based on your responses to a series of
dialog boxes.
New Term: A skeleton program is a program shell that you
must fill in with specific code.
WARNING: The application that the VB Application Wizard
generates is known as a shell or skeleton. The application will
not do much. For example, how can the VB Application
Wizard create a real estate analysis application for you and know
all the details and processing requirements and calculations that
you might require? The VB Application Wizard’s purpose is to
build only a shell by following your guidelines. The shell is just
a program structure that executes but contains no specific
functionality. The shell contains a menu, a toolbar, and several
other features, but these features are more like placeholders for
you until you get around to editing the generated application to
make the application perform a specific task that you need done.
Despite the ease with which you can generate an application
with the VB Application Wizard, this book does not revisit the
VB Application Wizard after this section. You need to get well
grounded in Visual Basic before you will really understand how
to add to the shell and change the shell to suit your needs.
Therefore, the VB Application Wizard arguably benefits the
experienced Visual Basic programmer more than the beginning
programmer because the experienced programmer will be more
able to decipher the generated shell and add specifics to make
the program operate as needed.
Perform these steps to generate your first Visual Basic application with the VB Application Wizard:
1. Select File | New Project. Click No at the dialog box that asks
if you want to save the Vcr project because you don’t want
to overwrite the sample application. (You made slight
changes to the project if you moved the Form Layout
window’s form around or closed windows that were open,
but you should not save those changes to the sample
2. When the New Project dialog box appears, double-click VB
Application Wizard to start the wizard.
3. Read through the wizard’s dialog boxes and click Next when
you’re ready to move to the next dialog box. Keep all the
default values along the way. As you’ll see on the Menus
dialog box (shown in Figure 2.8), the wizard gives you a
choice of menu items you want to see on the generated
application’s menu bar. Although menus are relatively simple
to place in a Visual Basic application, the wizard makes
placing menus much simpler because you only need to check
the boxes next to the items you want on the final
application’s menu bar.
4. As you click through the wizard, look for the dialog box that
describes the application’s Internet connectivity. The
generated application, despite being a shell, can access the
Web directly. You can send your application’s users to a Web
page or let them view Web pages from inside your own
application! The real magic is that the wizard handles all the
details for you if you want the options! For now, don’t select
Internet access but keep moving through the dialog boxes by
clicking Next.
5. The wizard gives you a chance to interface with a database,
such as Microsoft Access, before taking you to the final
dialog box, where you click Finish to watch Visual Basic’s
wizard perform its wizardry. Right before your eyes, the
wizard will put the application together, add the forms, and
build the menus.
6. Click the closing dialog box and close the final instructions.
The wizard leaves your development environment fairly
clean, but you know that you can double-click any object in
the Project window to see forms and code modules. For
now, simply run the program to see Figure 2.9’s screen.
The generated program looks somewhat like a word processor
because of the large editing area in the center of the screen. Try
the menus and click the toolbar buttons. Things look good.
You will find that the application does not respond to your
keystrokes as you might expect, however. If you select and
attempt to cut, copy, or paste (despite the toolbar and menu
items that represent those tasks), either nothing happens or a
small dialog box appears, telling you what you requested (such
as the paste command) but doing nothing about the request.
You must remember that it’s not the wizard’s job to generate a
fully working application that performs specific tasks. The
wizard’s job is to construct a general application to which you
can later add the specifics. As you learn more about Visual Basic,
you will better appreciate how much time and effort the VB
Application Wizard saves you because the simple task of
adding a standard menu and toolbar buttons can take an
afternoon. The generated application is a great starting point for
your own applications once you and Visual Basic become better
You’ve just created your first application! Actually, you got a
little help from your friend the VB Application Wizard, but
that’s okay. You are now beginning to understand how a Visual
Basic application’s components fit together. The events that the
user triggers are often related directly to your application’s forms
or controls, and you now know where to place the code that
handles the important events.
The next lesson takes a small step backward and lets you begin
to create an application from scratch without the help of the
wizard. You will better learn how the toolbox and Properties
window interact and support each other’s activities.
Q How do I know which events to respond to when so
many events can happen at any time?
A Your application’s requirements determine the events you
respond to in the application, nothing else. For example, if
your application has no need to respond to a mouse click over a
label you’ve placed on the form, don’t write an event procedure
for that label’s Click event. If the user clicks over the label,
Windows will send a message signaling the event to your
program, but your program simply lets the event pass through
and never responds to the event.
Q Why should I not compile my application before I run
the application if compiling the application makes it more
A When you compile an application, Visual Basic translates your
source code project into an executable program. The executable
program often takes less disk space than all the source files, and
the executable program is easier to distribute. Nevertheless,
when you develop and test an application, you don’t want to
compile the application every time you run it to test the
application and see the results. As a matter of fact, don’t
compile your application until you have completely finished the
application and are about to distribute it to others. The
compiled application is safe from modifications because a
compiled program is virtually impossible to change without
ruining the application’s executable file. In addition, the
compiled file will be faster than the project that you run from
inside the development environment. Nevertheless, during
development, you don’t care about speed, but you do care
about bugs. During debugging test runs, you want your project
to execute as soon as you request without taking the extra time
necessary to compile each time.
Q What is the difference between a form module and a
standard module?
A A form module always goes with its form. The form holds
controls, remember, and each of those controls can trigger and
respond to events. The event procedure code that you write for
the form’s controls must reside in that form’s form module.
General-purpose routines, such as common calculations that
several applications must share, should go in a standard
module with the .BAS filename extension. By the way, not only
can other applications utilize standard module files, but you can
add the same form and form module to multiple applications
as well. The application’s Project window will take care of the
bookkeeping details.
The quiz questions and exercises are provided for your further
understanding. See Appendix C, “Answers,” for answers.
1. How do windowed programs differ from programs running
in text-based environments?
2. What are events?
3. Why are project component filenames not usually the same
as their internal VB names?
4. What is usually the last step a VB programmer takes before
distributing an application to users?
5. How does Visual Basic know which procedure to execute for
a particular control’s event?
6. True or false: All controls support one and only one event
7. Which usually respond at design time: control property
changes or event procedures?
1. Scroll through the Vcr.vbp project’s form modules again,
looking at the various event procedures coded there. Surely
you’ll be able to spot exactly which events are handled and
which are not. An event procedure whose first name half is
Form is an event procedure for the form itself. For example,
you can respond to the user’s mouse click over the form
differently from a mouse click over a command button. Look
for the events associated with the various command buttons
on the form. Most often, a command button’s event
procedure is a ...Click() or ...DblClick() event procedure
because most users either click or double-click command
buttons and the click and double-click events are the ones
you often need to respond to.
2. Run the VB Application Wizard once again and, this time,
test other features by including more objects (such as the
Internet and database access if your disk drive contains a
database file somewhere that you can locate when the wizard
asks for the location) and selecting different options. Run the
generated shell to see how differently the wizard’s generated
shell applications can act.
Learning Objectives
What steps are required for application creation
How to place and size controls
Why various properties require different setting methods
Controls and Properties
Nobody can master Visual Basic until he masters controls and
properties. The form is the placeholder for the controls, and the
controls are the really important parts of any application. Many
of the properties require different kinds of values, and you will
learn in this lesson’s lesson how to set those values.
your toolbox and other windows on the screen, you’ll have to
use the scrollbars to access various parts of the form. Of course,
if your application is full screen, you’ll need to work with the
scrollbars to add controls to the full form.
NOTE: This book’s Form windows typically remain a size at
which you can see all the form as well as the surrounding
windows. Therefore, most of the applications in this book
contain fairly small Form windows. The book’s Form windows
will be larger than the default size that appears when you first
start Visual Basic, but the Form windows will be far smaller
than full screen.
Before you finish this lesson, you also will have created your
very first application from scratch without the aid of the VB
Application Wizard. You will have created a new project, sized
the form, added controls, set control properties, and even
written an event procedure using the Visual Basic programming
language! As you’ll soon see, Visual Basic makes all those tasks
Controls Provide the Interface
The highlights of this Lesson include
Placing Controls
Once you increase the Form window to a reasonable size that
your application requires, your job is to place controls on the
form. Use either of these two methods for placing controls on
the form:
1. Double-click any control on the Toolbox window to place
that control on the Form window
If a control appears in the center of the form already, the
new control will overwrite the existing control. You can drag
the new control to a different location, however. The eight
sizing handles (the small boxes that appear around a selected
control) indicate that the control is selected. If several
controls appear on the Form window, the selected controls
will display their sizing handles. (Typically, only one control
will be selected at any one time but you can select multiple
controls by holding the Ctrl key and clicking several controls.)
2. If you click a toolbox control once, the toolbox highlights
the control. If you then move the mouse cursor to the Form
window, the mouse cursor turns into a crosshair indicating
that you can place the selected control anywhere on the form.
Whereas a control appears in the center of the Form window
automatically as soon as you double-click the control, a
selected control appears only when you click and drag your
mouse crosshair on the Form window. The final control
appears when you release the mouse.
The advantage of using this approach to placing controls
over the first approach is that you don’t have to move and
resize the control after you’ve placed it. Figure 3.2 shows
Figure 3.1’s command button placed in the center of the
form with a double-click as well as a new command button
placed on the form by dragging the control as described here.
Which naming prefixes work best
Why your application’s tooltips give users added help
Creating new applications
When you create an application from scratch, instead of using
the VB Application Wizard to generate the program shell, you
control every aspect of the application’s design and you place all
the program’s controls on the form yourself. When you place
those controls, you must name the controls, position the
controls, set control properties, adjust the control sizes, and
hook up all the event procedure code that goes with each
All this may sound daunting, but Visual Basic makes things as
simple as possible. Although the task is not quite as simple as
running the wizard, you have the power to create the exact
application you need. Newcomers need to learn how to create
applications without the wizard so they can fully master all the
ins and outs of Visual Basic.
To create a new application from scratch, start Visual Basic and
double-click the icon labeled Standard EXE. The blank Form
window appears in the work area’s upper-left corner next to the
toolbox, ready for you to begin creating the application by
placing the controls.
TIP: The default Form window size is fairly small, especially
when you realize that the Form window holds the application’s
background. Most applications appear either full-screen or in an
initial window much larger than the Form window size that
appears. Therefore, one of the first tasks you will usually
perform is to increase the Form window’s size.
If you double-click the Form window’s title, Visual Basic
expands the Form window to a full- screen size. However, with
The controls you select for your application’s form are important because the controls (also called tools) provide the
application interface for your users. Users interact with your
application by clicking the controls and entering text in the
controls. Placing and sizing controls are perhaps the two most
important tasks you can master at this point.
You can place the control exactly where you want it and at the
size you want it when you drag the control onto the form.
Sizing and Moving Controls
You can change the size of only a selected control. The eight
sizing handles are the key to resizing the control. You can drag
any of the eight sizing handles in any direction to increase or
decrease the control’s size. Of course, if you placed a control on
the form by dragging the control, you won’t need to resize the
control as often as you will if you double-clicked the toolbox
tool to place the control.
You can move a selected control to any area of the Form
window by dragging the control with your mouse. Once you
click to select a control, click the control and hold down the
mouse button to drag the control to another part of the Form
Sometimes you may want to drag several controls to a new
location as a group. For example, perhaps you’ve placed a set of
command buttons at the bottom of a form and after adjusting
the Form window’s size, you determine that you need to move
the buttons down some. Although you can move the command buttons one at a time, you can more quickly select all the
command buttons and move them as a group.
As stated earlier, you can select more than one control by
holding the Ctrl key as you click a control. (Much of the
Windows interface, such as Explorer and the Windows
Desktop, lets you select multiple files and icons the same way as
Visual Basic lets you select multiple controls.)
In addition, you can lasso the controls by dragging a selection
rectangle around the controls you want to select as a group.
When you release your mouse, the controls within the selected
region will be selected
TIP: Remember how to select multiple controls if you find
yourself needing to change other properties beside the location
of controls. If you select multiple controls before changing a
control property, all controls in the selected range will take on
that new property value. You can only change the common
properties that appear in all of the selected controls.
Setting Properties
As you add controls to the Form window, the Properties
window updates to show the properties for the currently
selected control. The selected control is usually the control you
last placed on the form. Visual Basic lets you see a control’s
properties in the Properties window by clicking to select the
control or by selecting the control from the Properties window’s
drop-down list box.
NOTE: Visual Basic programmers often use the generic term
object to refer to controls, forms, menus, and various other
items on the screen and in the code.
Scroll the Properties window to see the various properties for
the selected controls. Each kind of control supports the same
set of properties. Therefore, every command button you place
on the form supports the same properties (and events as well)
as every other command button, but option buttons and text
boxes support different sets of properties than command
The Left, Top, Height, and Width properties are about the only
properties you can set without accessing the Properties window.
As you size and move a control into place, Visual Basic updates
the Left, Top, Height, and Width properties according to the
control’s placement on the Form window and the control’s size.
As with the form location and size measurements, these
properties appear in twips (unless you specify a different value
in the ScaleMode property). Left indicates how far from the
form’s left edge the control appears, Top indicates how far from
the top of the form the control appears, and the Height and
Width properties indicate the control’s size.
NOTE: Even the form has properties. Click your Form
window and look at the Properties window. The form will be
the selected object at the top of the Properties window (Form1
is the default name for an application’s initial form).
After you place and size a control, the first property you should
modify is the Name property. Although Visual Basic assigns
default names to controls when you place the controls on the
Form window, the default names don’t indicate the control’s
true purpose in your application. In addition, the default names
don’t contain the three-letter prefix that describes the control
you learned about in Lesson 2, “Analyzing Visual Basic
For your reference, Table 3.1 lists common prefixes used for
control names. When you name your Form window’s controls,
you’ll appreciate later that you took the time to type the threeletter abbreviations at the beginning of the names because you
will be less likely to assign a text box a property that belongs to
a command button control inside an event procedure. (Such an
assignment will cause a runtime error.)
NOTE: The Name property is so important that Visual Basic
lists the Name property first (as (Name) inside parentheses) in
the Properties window instead of alphabetically in the Properties window, where the other properties reside.
Table 3.1. Use these prefix abbreviations before control
need to place the following Visual Basic statement inside one
of the application’s event procedures to do this:
lblClick.Caption = “Clicked!”
Save the project and form module so you can modify the
application later if you want to do so.
Prefix Control
Combo box
Check box
Command button
Directory list box
Drive list box
File list box
Horizontal scrollbar
List box
OLE client
Option button
Picture box
Text box
Vertical scrollbar
New Term: A tooltip is a pop-up description box that appears
when the user rests the mouse pointer over a control.
Some property values you set by typing the values directly in the
Properties window. For example, to enter a value for a control’s
ToolTipText property, click once on the Properties window’s
ToolTipText property and type the tooltip text.
1. Create another application from scratch. Add two command
buttons and one label between them. Make the label’s
Caption property blank when you place the label on the
form. When the user clicks the first command button, a
caption should appear on the label that reads Clicked!. You’ll
Learning Objectives
How To give user help
How to assign a named literal to this property.
How to play with properties.
Giving your users Help
The tooltip is a great feature that helps your users and is as easy
to implement as typing text into the control’s ToolTipText
property. Most applications since the introduction of Windows
95 include tooltips, and there’s no reason why your applications
should not include them as well.
A tooltip that appears in Visual Basic when you rest the mouse
pointer over the Form Layout window toolbar button. The
best time to add tooltip text is when you adjust a new control’s
properties because you are more likely to remember the primary
purpose for the control. Often, when programmers plan to add
such items later once they “complete” the application, the items
to be added, especially helpful items such as tooltips, are not
If you want to change a property value, such as the Name
property, you can click the Name property and enter a new name.
As you type, the new name replaces the original name. If
instead of clicking you double-click the property, Visual Basic
highlights the property value and lets you edit the existing value
by pressing your cursor keys and using Insert and Delete to edit
the current property value.
TIP: As you select a property, read the text that appears at the
bottom of the Properties window. The text describes the
property and serves as a reminder about what some of the
more obscure properties do.
Some properties require a selection from a drop-down list box.
For example, In a command command button’s Visible
property’s drop-down list box. The Visible property can either
be True or False. No other values work for the property, so
Visual Basic lets you select from one of those two values when
you click the property value to display the down arrow and open
the drop-down list box.
If an ellipsis (...) is displayed when you click the property value,
such as the Font property when you click the current Font
property’s value, a dialog box opens when you click the ellipsis.
A Font property is more than just a style name or size. The
control’s Font property can take on all kinds of values and the
Font dialog box that appears from the click of the ellipsis lets
you specify all available Font property parts. When you close the
dialog box, the compound property is set to the dialog box’s
specific values.
Some programmers prefer the Categorized view of the
Properties window. By default, the Properties window displays
its properties alphabetically (with a possible exception at the top
of the Properties window, such as the Name property). When
you click the Categorized tab above the property values, the
Properties window changes to show the properties in an
Explorer tree view .
If you needed to change all of a control’s appearance values,
such as Color and Caption, you could expand the Categorized
view’s Appearance entry to display all the appearance values
together. You then can more quickly change the appearance than
if you had to search through the alphabetical listing of properties.
As you can see, placing a control requires much more involvement with property values than simply moving and sizing the
control. You rarely if ever have to change all of a control’s
properties because many of the default values work fine for
most applications. Nevertheless, many property values work to
make the control unique to your specific application.
Named Literals
A named literal, also called a named constant, is a special named
value that represents a fixed value. Visual Basic comes with
several named literals and you’ll use many of them in your
programs to assign values to controls at runtime.
Consider the drop-down list box that appears when you click
on a command button’s MousePointer property .The
MousePointer property requires a value from 0 to 15 (or 99 for a
custom value). When you set property values at design time,
you simply select from the list, and the descriptions to the right
of the numeric values explain what each value is for. When
programming, you will be able to assign property values to
properties when the user runs the program. Although you can
assign 2 to the property value to change the mouse cursor to a
crosshair during one part of the running application, your code
will be better if you assign the named literal vbCrosshair.
Although vbCrosshair is longer to type, you will know what
you assigned when you later look at the project.
We’re getting slightly ahead of ourselves discussing runtime
property values that change inside the code such as event
procedures. Nevertheless, keep named literals in mind as you
assign values to the Properties window at design time. The
named literals often closely match their Properties window
counterparts. When you’re ready to use named literals in
subsequent lessons, this book describes the ones available for
the controls being discussed.
Take a Break!
In this section, you are going to create a project from scratch
without the help of the VB Application Wizard. You’ll create a
new project, assign controls, and write event procedure code to
hook everything together. The final application will be simple,
but you’ll have little trouble understanding the application now
that you’ve become more familiar with properties and event
To create your first application, follow these steps:
1. Create a new project by selecting File | New Project and
double-clicking the Standard EXE icon. Don’t save any
changes from earlier in this lesson if you were following
along during the discussion of command buttons and
control placement.
2. Change the form’s Name property to frmFirst and change its
Caption property to My First Application. The form’s
Caption property text appears in the title bar when you run
the application.
3. Expand the Form window to these property values: Height
7380 and Width 7095. You can either drag the Form
window’s sizing handles until the Form window’s size
coordinates to the right of the toolbar read 7095x7380 or
you can set these two property values yourself by changing
the values in the Properties window. If you drag the Form
window to obtain this size, you can approximate the
coordinates described here; you don’t have to size your Form
window exactly to 7,095 by 7,380 twips.
4. Click the Label control once. As you learned in Lesson 1,
“Visual Basic at Work,” the Label control is the tool with the
capital letter A on the toolbox. When you click the Label
control, Visual Basic shows the control depressed as if it
were a command button.
5. Move the mouse pointer onto the Form window and drag a
Label control toward the top of the Form window in the
approximate location
6. Change the label’s Name property to lblFirst. Change the
label’s Caption property to VB is fun.
7. Click the label’s Font property value to display the ellipsis.
Click the ellipsis to display the Font dialog box for the label.
Set the font size to 24 points (a point is 1/72 inch and 24
points is about twice the height of a word processor’s
character on the screen) and set the Bold property.
As Figure 3.10 shows, the label’s text is now large enough to
read, but the text is not well centered within the label.
Change the label’s Alignment property to 2-Center, and the
text centers just fine.
8. Change the label’s BorderStyle property to 1-FixedSingle. This
property adds a single-line 3D border around the label.
You’ll see that the label’s Height property is too large, so click
the label to display its sizing handles and drag the top edge
downward to center the text within the label.
9. Add a command button, but to do so, double-click the
command button tool on the Toolbox window. The
command button appears in the middle of the form and
you can leave it where it is.
10.Change the command button’s Name property to cmdExit.
Change the command button’s Caption property to E&xit.
Watch the command button as you type the Caption
property text. The command button’s caption becomes the
text you type with one exception: The x is underlined. When
you precede a Caption property’s letter with an ampersand
(&), Visual Basic uses that letter for the control’s hotkey.
Users of your application will be able to select the command
button not only by clicking with the mouse, but also by
pressing Alt+X on the keyboard.
11. The command button will be used to exit the program.
When the user clicks the command button, your application
should end. What happens anytime a user clicks a command
button? A Click event occurs. Therefore, to respond to this
event, you must write an event procedure for the command
button. Visual Basic helps. Double-click the form’s
command button and Visual Basic instantly opens the Code
window and displays the following wrapper lines for the
command button’s Click event procedure:
Private Sub cmdExit_Click()
End Sub
You only need to fill in the body. The name of the procedure,
cmdExit_Click(), describes both the control and the event being
processed by the code. Type End for the one-word body of the
event procedure and close the Code window. End is now the
very first Visual Basic programming language statement you’ve
learned! End tells Visual Basic to terminate the running
application. Therefore, the application will terminate when the
user clicks the command button.
TIP: Indent the body of the code from the surrounding
wrapper lines as follows so you’ll be able to distinguish
procedures from one another when you read through a list of
Private Sub cmdExit_Click()
End Sub
Press F5 to run the program and watch your creation appear. As
shown in Figure 3.11, the form appears with the label and
command button in place.
Terminate the application by clicking the Exit command button.
Visual Basic regains control. (If you had compiled the application, you could run the compiled .EXE file from the Windows
Run command or from an icon if you assign the .EXE file to
an icon on the Desktop or to an option on the Start menu.)
Save your first application. When you save the project, Visual
Basic saves all the files within the project. Select File | Save
Project. Visual Basic asks for the form’s name with a Save File
As dialog box (remember that each element of the project is a
separate file). You can select a different drive or pathname if you
wish. Save the form module file under the name Lesson 3
Form (Visual Basic automatically adds the .FRM filename
extension). Visual Basic now requests the name of the project
with a Save Project As dialog box. Type Lesson 3 Proj and click
Save to save the project file (Visual Basic automatically adds the
.VBP filename extension). If you were to edit the project,
Visual Basic would not need to request the filenames subsequently now that you’ve assigned them.
Take a rest before starting Lesson 4, “Examining Labels,
Buttons, and Text Boxes.” Exit Visual Basic and give your
computer’s circuits a break as well. You are well on your way to
becoming a Visual Basic guru, so feel good about the knowledge you’ve already gained in three short lesson.
This lesson you learned how to place controls onto a form and
how to size and move the controls. Once you place controls,
you must set the control property values so that the controls
take on the values your application requires. (Don’t you wish
you could set your real estate property values just as easily?)
The next lesson gets specific and describes these three common
controls in detail: command buttons, labels, and text boxes.
Q When do I double-click a toolbox control to place the
control on the Form window and when do I drag the
control onto the Form window?
A When you double-click a toolbox control, that control
appears on the Form window immediately. The double-click
requires less work from you to place the control on the form.
Once the control appears, however, your rest period ends
because you have to move and size the control properly. By first
selecting a control and dragging the control onto the form, you
select, size, and move the control in one step.
Q How do I know if a property value requires a value, a
selection from a drop-down list box, or a dialog box
A Just click the property. If nothing happens, type the new
property value. If a drop-down list box arrow appears, click the
arrow to see the selections in the list. If an ellipsis appear, click
the ellipsis to display the property’s dialog box.
Q Can I create an initial application with the VB Application Wizard and then add extra controls to the form?
A Certainly! That’s the true reason for using the wizard. The
wizard creates the shell, and then you add to and modify the
shell to generate a final application that meets your specific
needs. The only potential problem right now is that the wizard
does generate a fairly comprehensive shell, especially if you add
Internet and database access to the shell. Until you master more
of the Visual Basic environment and language, you might find
that locating the correct spots to change is more difficult than
creating the application from scratch.
The quiz questions and exercises are provided for your further
understanding. See Appendix C, “Answers,” for answers.
1. What is the fastest way to place a control on the form?
2. What are a control’s sizing handles for?
3. How can you select multiple controls?
4. True or false: Some properties change automatically as you
move and resize controls.
5. Which form property sets the title that appears in the form’s
title bar?
6. What is the difference between an object and a control?
7. When is the best time to add a tooltip to a control?
8. Why do some controls display an ellipsis when you click
certain property values?
1. Load the project you created in the previous exercise and add
tooltips to the two labels and to the command button. Run
the application and test the tooltips to see if they work.
Learning Objectives
How to set up focus order
When the Cancel property triggers events
How to set a command button’s Default property
Examining Labels, Buttons, and Text
It’s time to get serious about controls! This lesson dives deeply
into the three most common controls and explains how you
can use them and manage them in your applications. By the
time you complete this lesson, you will have mastered labels,
command buttons, and text boxes. In addition, you will learn
more about how to properly set up a form.
You’ll place labels on forms to display information. Command
buttons give the user pushbutton control within applications.
Text boxes get information from the user and process that
information inside the program.
Which common properties are important
How to adjust label sizes for long text values
Control Focus
New Term: The currently active control at runtime has the
Before looking at this lesson’s three controls, you need to
master the concept of focus. Focus is a runtime concept. At
runtime, only one window, form (which appears as a window),
or control can have the focus. The window or form currently in
focus is the form whose title bar is highlighted (typically colored
blue). The control with the current focus has an outlined border
or caption.
WARNING: Don’t confuse focus with a selected control. At
design time you select controls by clicking them to display their
sizing handles. At runtime, one control always has the focus,
and users can change the focus by pressing Tab or Shift+Tab.
Focus is important because the focus determines what the next
keystroke or Enter keypress will activate. For example, consider
the screen shown in Figure 4.1. The figure shows a VB session
with several windows, including two windows from the
executing program. The center window is the window with the
focus, and you know so because of the highlighted title bar.
Therefore, the center window is the window that receives
keystrokes if and when the user presses a key.
Only one control on the active window can have the focus. The
check box labeled AutoSize has the current focus. Notice the
outline around the control. In other words, despite the other
windows on the screen at the time, if the user presses Enter
under Figure 4.1’s circumstances, the check box receives that
Enter keystroke. If you understand the way check boxes work,
you know that a check box is either checked or unchecked,
meaning that the control determines one of two states. If the
user presses Enter, the AutoSize check box will turn to
NOTE: Of course the user can click the AutoSize check box to
uncheck the control. In addition, the user can click any control in
any window on the screen and that control would receive the
click. Focus refers to a window’s and control’s capability to
receive keystrokes.
Different controls display the focus in different ways. Only one
of Figure 4.2’s seven command buttons can have the focus at
any one time. Can you spot the command button that has the
focus? The extra dotted outline around the Images command
button lets you know that the Images command button has
the focus and that command button will receive an Enter
keypress if the user presses Enter.
The Mouse and Hotkeys Need no Focus
As stated earlier, a mouse click does not have to worry about
focus. Wherever the user clicks, the mouse gets the mouse click
no matter which window and control had the focus before the
click. In addition, within the active window, the user can select
any control by pressing that control’s hotkey. For example, with
Figure 4.2 showing, the user could press Alt+X to select the
command button labeled Text Box even though the command
button labeled Images has the focus.
An Enter keypress has no inherent location. Without focus,
Windows would have no way to determine where or what the
Enter keypress is to activate. With a hotkey, Windows keeps the
hotkey possibility within the window with the focus. In other
words, if two windows appear on your screen and both contain
controls with Alt+S keystrokes, only the active window with the
current focus would receive and respond to Alt+S.
The mouse is inherently directional as well as functional. When
you click the mouse button over any window’s control on the
screen, Windows knows for certain that you wanted to click over
that control. No ambiguity can exist as could happen with the
Enter key. Therefore, focus does not apply to the mouse.
Related Properties
A command button’s Cancel property relates somewhat to
focus. Whereas the focus determines which control gets the
Enter keypress, a command button’s Cancel property determines which command button gets a simulated Click event
when the user presses the Esc key.
TIP: Often, a command button used to exit an application or
close a dialog box has its Cancel property set to True. Therefore,
you can close such applications or dialog boxes by clicking the
command button or by pressing Esc.
A command button’s Default property also relates somewhat
to focus. When a form first appears, the command button with
the Default property of True receives the Click event when the
user presses Enter. Another control might have the focus at
that time, but if a command button has a Default property
value of True, that button receives a Click event if the user
presses Enter unless the user moves the focus to another
command button before pressing Enter. Only one command
button can have a Default value of True at any one time. As
soon as you assign a command button’s Default value True,
either at design time or at runtime, any other command button
on the form with a True Default value immediately changes to
False. Therefore, Visual Basic protects a form’s integrity by
ensuring that only one command button can have a True
Default value at any one time.
Tab order
The user can move the focus from control to control by
pressing Tab (or Shift+Tab to move the focus backward). If
you place eight controls on an application’s form, what focus
order will result? In other words, as the user presses Tab, will
the controls get the focus from a left-to-right or from a top-tobottom order?
VB sets the default focus order in the order you place controls
on the form. Therefore, if you place the top control first and
the bottom control second, and then insert a third control in
the middle of the form, the focus order will not move down
the form in the order the user probably expects.
You do not always place controls on a form in the same order
in which you want to set the focus. Therefore, controls that can
receive the focus support a property called the TabIndex
property. The first control in the focus order has a TabIndex
property of 0, the second control in the focus order has a
TabIndex of 1, and so on. If you place controls on the form
and then later want to modify the focus order, you need to
change the controls’ TabIndex property values.
TIP: Not all controls can actually accept the focus. For example,
a label cannot receive keystrokes, so a label never gets the focus.
The Label control does include the TabIndex property, however.
By setting the label’s TabIndex value to one more than a text
box next to the label, you can add a hotkey to the label’s
Caption property, and the user then has a way to hotkey to the
text box. Text boxes do not support hotkey keystrokes by
Command Buttons
Command buttons appear in almost every window of every
Windows application. Command buttons determine when the
user wants to do something, such as exit the application or
begin printing. In almost every case, you will perform these
tasks to add a command button to an application:
1. Locate and size the command button on the form.
2. Change the command button’s Name and Caption
properties. (The Caption property holds the text that appears
on the command button.)
3. Add code to the command button’s Click event procedure.
Although the command button control supports 36
properties, you’ll only set the Name and Caption properties
in most cases. In addition, although command button
controls support 15 events, you’ll only write code for the
Click event in most cases. After all, a command button
resides on most forms just so the user can click the button
to trigger some event that the user is ready to start.
NOTE: By the way, you can set some properties only at design
time (such as a control’s Name property), you can set some
properties both at design time and at runtime inside event
procedures and other module code (such as a caption), and you
can set some properties only at runtime from within the
program (such as a list box’s entries). All of a control’s properties that appear in the Properties window are settable at design
time, and some of those you can set at runtime as well. As you
learn more about Visual Basic, you will become familiar with
the properties you can set only at runtime.
Although you’ll set the command button’s Name and Caption
properties most of the time, setting the Caption property often
requires that you change the font to increase or decrease the text
size and style on the caption. Of course, you might want to
center the caption text or, perhaps, left-justify or right-justify the
text, so you also might need to change the Alignment property.
In reality, you’ll also set the Left, Height, Top, and Width
properties when you size and locate the command button
because, as you learned in Lesson 3, “Controls and Properties,”
these properties update automatically when you place and size
As you can see, although you only seem to set a couple
properties for most controls, the other properties really do play
important roles, and you’ll almost always end up setting several
properties to finalize your application. Table 4.1 lists some of
the most common command button properties that you’ll set.
New Term: An icon is a small graphical image, stored in a file
with the .ICO filename extension, that often appears on toolbar
Today you have learned the concept of focus. You must know
about focus before working more with Visual Basic controls
because focus determines the order of controls and which
controls are active at any one time.
Most of this lesson describes the three fundamental controls
that appear on almost every application’s Form window:
command buttons, labels, and text boxes. Many of the control
properties overlap between these and other controls so you can
easily master the properties that are important.
The next lesson dives head first into the Visual Basic programming language so you can begin to build applications internally
now that you’ve learned how to design application windows
using the fundamental controls.
Q How do I know which control has the focus?
A Generally, you’ll quickly learn to recognize focus once you’ve
worked with focus a short time. The focus appears different
depending on the collection of controls that appear on the
form. Most of the time, the focus appears as a dotted outline
around a caption or an option. You’ll know which window has
the focus because the focus window’s title bar will be colored
and the others’ will be grayed out. If you really cannot deter-
Specifies the command button's background color. Click the BackColor's
palette down arrow to see a list of colors and click Categorized to see a list of
common Windows control colors. Before the command button displays the
background color, you must change the Style property from 0-Standard to 1Graphical.
Determines whether the command button gets a Click event if the user
presses Esc.
Holds the text that appears on the command button.
Determines if the command button responds to an Enter keypress even if
another control has the focus.
Determines whether the command button is active. Often, you'll change the
Enabled property at runtime with code when a command button is no longer
needed and you want to gray out the command button.
Produces a Font dialog box in which you can set the caption's font name,
style, and size.
Holds the height of the command button in twips.
Holds the number of twips from the command button's left edge to the
Form window's left edge.
MousePointer Determines the shape of the mouse cursor when the user moves the mouse
over the command button.
Holds the name of an icon graphic image that appears on the command
button as long as the Style property is set to 1-Graphical.
Determines whether the command button appears as a standard Windows
command button (if set to 0-Standard) or a command button with a color
and possible picture (if set to 1-Graphical).
Specifies the order of the command button in the focus order.
Determines whether the command button can receive the focus.
ToolTipText Holds the text that appears as a tooltip at runtime.
Holds the number of twips from the command button's top edge to the
Form window's top edge.
Determines whether the command button appears or is hidden from the user.
(Invisible controls cannot receive the focus until the running code changes
the Visible property to True.)
Holds the width of the command button in twips.
mine which control has the focus, press the Tab key a few times.
You will see the focus jump from control to control.
Q How can I learn all the properties?
A People who have written Visual Basic programs for years
don’t know every property for every control. The Properties
window is always at most one menu away, and it always
displays a control’s properties. Therefore, don’t worry about
learning all the properties. Generally, if you need to adjust the
location, size, look, or behavior of a control, a property
probably exists to handle that operation.
The quiz questions and exercises are provided for your further
understanding. See Appendix C, “Answers,” for answers.
1. True or false: A selected control (the control with its sizing
handles showing) is the control with the focus.
2. True or false: When the user clicks the mouse over a control
in a window that does not have the focus, the clicked control
still gets the focus.
3. Which control works best for titles: labels or text boxes?
4. What can you do to close a Form window when the user
presses Esc?
5. Which property disables a text box from triggering events
when the user types or clicks the text box?
6. Why do you think labels fail to support a GetFocus event?
7. What happens if you set a label’s AutoSize property to True
before setting the WordWrap property to True if the label
holds a long caption value?
8. Why should you avoid adding too many autosizing labels to
the form at one time?
1. Write a Visual Basic application that displays an appropriate
form title and asks the user for his first and last names in
two separate text boxes. Add a command button that
terminates the program when the user clicks the command
button, presses the command button’s hotkey, or presses
2. Create an application with five command buttons. Reverse
the focus order so that when you run the application and
press the Tab key several times, the focus order flows upward
through the command buttons.
3. Write an application that displays three labels with the same
long label Caption property in each. Don’t display the entire
caption in the first label. Display the caption horizontally in
the second label. Display the caption vertically down the
window in the third label. You may have to expand the
Form window to its full size (perhaps by setting the Form
window’s Window State property to 2-Maximized).
Learning Objectives
What data types VB supports
How to declare variables
How to assign data to variables
It’s time to hone your multilingual skills and learn a new
language! This lesson’s lesson explores the Visual Basic
programming language. You’ll learn how code goes together to
form the application, and you’ll learn how VB works with data.
Your applications must be capable of processing many types of
data values, and you’ll master those data types
Coding Basics
As you write more powerful programs, you’ll need to insert
more and more of Visual Basic’s programming language into
your applications. The language, although one of the easiest to
master, can be tricky in places. Nevertheless, if you start with the
fundamentals, you’ll have no trouble mastering the hard parts.
Remember that a VB program consists of the following:
One or more forms
Controls on the forms
Code written in the Visual Basic programming language
Although you can create great-looking applications just by
dragging controls onto forms and setting properties, the
applications don’t really become useful until you add code to tie
the controls together and to perform calculations and data
manipulation when needed. No control exists to calculate
inventory accounting values; you must add the code to do
things like that. The program code that you write is just a
detailed set of instructions that tells Visual Basic how to
manipulate data, perform input and output (known as I/O),
and respond to the user.
New Term: I/O stands for input and output and refers to the
practice of receiving data from a control, the user, or a data
source such as the disk drive and sending data from your
computer to the outside world, such as the screen or printer.
Before looking at specifics, you should take a moment to
consider the location of the code in a VB application. You now
know that much of the code in an application is comprised of
small event procedures that respond to events. The form’s
controls often trigger the events when the user interacts with a
control. Event procedures are not the only code that appears in
an application, however. Code can appear in several places. This
24-lesson tutorial concerns itself with code that appears in form
modules and in standard modules.
New Term: A form module is a module file that holds one or
more forms and the code that goes with each form.
New Term: A standard module is a file that holds code not
related to a form.
A form module is code connected to a specific form. The form’s
event procedures appear in the form’s form module as does
other code that is not directly connected to events such as
calculations and data sorting routines. Every application has at
least one form, so every application contains at least one form
module. When you add a new form to an application, Visual
Basic adds a new form module to go with the form.
NOTE: Some applications, such as those that perform system
utility functions and background processing tasks, never display
their form. The form’s Visible property is set to False.
Figure 5.1 helps illustrate the module concepts this section
describes. All of the application’s modules reside in separate
disk files even though Visual Basic groups them together in a
single project. You can consider all the project’s files as one
entity during your application’s creation and execution, but the
files do reside separately on the disk. The Project Explorer
window keeps things together in an orderly manner.
Figure 5.1. One or more modules can appear in an application.
A program that supports multiple forms (and therefore,
multiple form modules) is either an MDI (for multipledocument interface) application or an SDI (for single-document
interface). An MDI application, such as Word, can open several
windows at once that contain different data documents. An
SDI application, although it can contain multiple forms such as
dialog boxes, only supports one data document (the Windows
Notepad application is an SDI application because when you
open a new document, the current one leaves the work area).
No matter which kind of application you create, your application can contain multiple Form windows and, hence, can
contain multiple form modules.
In addition to form modules, an application might contain one
or more standard modules. Standard modules contain code and
have no forms or controls associated with them. Although the
code inside a standard module might manipulate a form or its
controls, the code that you put in a standard module usually
contains general-purpose code that you can use in several
applications. For example, you might write some Visual Basic
code that calculates wages using some special formulas that your
company requires. If you need to use those calculations in
several applications, store the calculations in a standard module
and then add a copy of that standard module to each application instead of typing the code multiple times in multiple
TIP: You will understand the differences in modules much
more clearly as you progress through these 24 lesson. For now,
concentrate on getting the “big picture.”
Fortunately, you don’t have to do much to manage projects that
require multiple files. The Project Explorer window keeps track
of things. As you add files to or remove files from the application (by selecting from the menu that appears when you
right-click over the Project Explorer window), the Project
Explorer window keeps track of the bookkeeping. When you
want to modify or add to one of the items in the Project
Explorer window, double-click the object’s icon in the Project
Explorer window, and the form or code opens in the work area
NOTE: Visual Basic also supports class modules, but this
book does not discuss class modules in detail.
Data Basics
Now that you’ve got a better idea of how code goes together to
support a Visual Basic application, you’re ready to begin the
specifics. This section teaches you all about the types of data
that Visual Basic can manipulate.
Before you can perform data processing, you must understand
data. When you are able to represent data properly, you can learn
some commands to manipulate and process that data. Data is
the cornerstone for learning the rest of the Visual Basic
programming language. Although writing code that manipulates data might not seem to be as much fun as working with
controls, you’ll soon see the tie-in between controls and the
code you write. Once you learn to represent and process data,
Description and Range
you can then work with controls in ways that you could not
without the language’s help.
Data Types
Data falls into three broad categories: numeric, string, and
special. If you want to work with a number, you’ll need to use a
number that fits within one of VB’s data type categories. If you
want to work with text data, you’ll need to use a string. Other
data might fall into one of several special data type categories
such as an item that represents a check box-like value of True or
A string is a series of zero or more characters that you treat as a
single entity. VB supports both fixed-length and variable-length
NOTE: Controls almost always supply the Variant data type to
your programs. Therefore, when your program receives a value
from a control, the data type is Variant. You can, through a
conversion routine or by implicit typing (when VB converts the
data type for you as you store one data type in a location that is
designed to hold a different data type), convert the control’s
data type to another data type. The Variant data type lets you
store data in a variable when you
don’t know the specific data type of
the variable.
A data type that takes on one of two values only: True or False. True and False are
Visual Basic reserved words, meaning that you cannot use them for names of items
you create.
Positive numeric values without decimals that range from 0 to 255.
Currency Data that holds dollar amounts from -$922,337,203,685,477.5808 to
$922,337,203,685,477.5807. The four decimal places ensure that proper rounding
can occur. VB respects your Windows International settings and adjusts currency
amounts according to your country's requirements. Never include the dollar sign
when entering Currency values.
Holds date and time values. The date can range from January 1, 100, to December
31, 9999. (In the years following 9999, people will have to use something other
than Visual Basic!)
Decimal A new data type not yet supported in Visual Basic except in a few advanced
situations. The Decimal data type represents numbers with 28 decimal places of
Double Numeric values that range from -1.79769313486232E+308 to
1.79769313486232E+308. The Double data type is often called double-precision.
Numeric values with no decimal point or fraction that range from -32,768 to
Integer values with a range beyond that of Integer data values. Long data values range
from -2,147,483,648 to 2,147,483,647. Long data values consume more memory
storage than integer values, and they are less efficient. The Long data type is often
called long integer.
A special data type that holds and references objects such as controls and forms.
Numeric values that range from -3.402823E+38 to 3.402823E+38. The Single data
type is often called single-precision.
Data that consists of 0 to 65,400 characters of alphanumeric data. Alphanumeric
means that the data can be both alphabetic and numeric. String data values may also
contain special characters such as ^, %, and @. Both fixed-length strings and
variable-length strings exist.
Data of any data type and used for control and other values for which the data type
is unknown.
Implicit typing is the process that
VB performs when converting one
data type to another.
Table 5.1 lists the data types that
Visual Basic supports. As you work
with Visual Basic, you’ll become
familiar with all the data types (with
the possible exception of Decimal,
which is not supported throughout
the Visual Basic language yet).
Table 5.1. The Visual Basic data
Scientific Notation
New Term: An exponent is a
power of 10 by which you want to
multiply another value.
Table 5.1 contains Es and Ds in
some numeric values. E stands for
exponent, and D stands for doubleprecision exponent. The
double-precision provides more
accuracy than the regular exponent
(often called a single-precision
exponent). Both data types
demonstrate a shorthand number
notation called scientific notation.
Scientific notation contains either
uppercase or lowercase Es and Ds
because the notation’s letter case is
New Term: Scientific notation is a shorthand notation for
specifying extremely large or extremely small numbers.
Use scientific notation to represent extremely large and extremely small decimal numbers without typing a lot of zeros or
other digits. You can convert a scientific notation value to its real
value by following these steps:
1. Raise 10 to the number after the D or E. Therefore, the
number 5.912E+6 requires that you raise 10 to the 6th
power to get 1,000,000.
2. Multiply the number at the left of the D or E by the value
you got in step 1. Therefore, the number 5.912E+6 requires
that you multiply 5.912 by the 1,000,000 you got in the first
step to get a final meaningful result of 5,912,000.
Typing 5.912E+6 is not a lot easier than typing 5912000; but
when the number grows to the trillions and beyond,
scientific notation is easier. By the way, you cannot insert
commas when you enter Visual Basic numbers unless your
International settings uses the comma for the decimal
TIP: Visual Basic often displays value in the scientific notation
format to save room on the screen or in a control. Therefore,
you need to understand scientific notation, even if you never
plan to use scientific notation, so you’ll recognize its meaning
when you see it.
Specifying Values A literal is a value that does not change. You
will sprinkle literals throughout your program. For example, if
you need to annualize a monthly calculation, you’ll surely
multiply a value by 12 somewhere in the calculation because 12
months appear in each year. 12 is a literal and represents either a
Byte, an Integer, or a Long data type, depending on its context.
If you multiplied the monthly value by 12.0, the 12.0 is also a
literal, but 12.0 must be a Single or Double data type due to the
When typing numeric literal values, you don’t have to concern
yourself with the data type because Visual Basic takes care of
things for you and attaches the best data type for the calculation.
If, however, you specify data of other data types, you must
consider the way you type the data.
All String literal data contains surrounding quotation marks.
The String literals do not include the quotation marks. The
following are literals that take the String data type:
“123 E. Sycamore St.”
“Happy birthday!”
NOTE: The last string is called an empty string or a null string
because the quotation marks are together without even a space
between them.
You must embed date and time literals (Visual Basic uses the
Date data type to hold these values) inside pound signs (#).
Depending on your International settings, you can specify the
date or time in just about any valid date or time format, as in
the following:
#2:56 PM#
#December 5,
A Boolean literal is always True or False, so any time you must
store or retrieve a True or False value, Visual Basic uses the
Boolean data type to hold the value. Option and Check Box
controls return their values in the Boolean data type. Many
programmers use the Boolean data type to store two-value data
such as yes/no or on/off values.
NOTE: You’ll learn more about Variant and Object when you
tie code to controls and forms later in this book.
Although Visual Basic normally takes care of data types when
you type number values, you might need to ensure that Visual
Basic interprets a numeric literal as one of the specific numeric
data types. For example, you might type the literal 86 and need
Visual Basic to store or display the value as a Long data type
even though 86 fits within a Byte or Integer data type.
You can use the data type suffix characters from Table 5.2 to
override the default data type. The suffix characters let you
specify the data type for numeric literals when you need to.
Occasionally, Visual Basic will also use the data type suffix
characters when displaying numeric information. Therefore, if
you type 86#, Visual Basic treats the number 86 as a doubleprecision value.
Table 5.2. Numeric data type suffix characters.
Suffix Cha ra cter Data Type Example
[email protected]
Variables Hold Data
All your data cannot be literals. The information your program’s
users enter in controls such as text boxes is not literal data
because the user can change information. In addition, your
program has to have a place to hold information temporarily
for calculations and for in-memory storage before sending
information to a disk file or to the printer. To hold data that
might change due to calculations or state changes within the
application, you must declare variables. A variable is a named
location that holds data.
Variables, unlike literals, can change. In other words, you can
store a number in a variable early in the program and then
change that number later in the program. The variable acts like a
box that holds a value. The data you store in variables does not
have to change, but often the program does change the contents
of variables.
A program can have as many variables as you need it to have.
Before you can use a variable, you must request that Visual Basic
create the variable by declaring the variable before using it. To
declare a variable, you tell Visual Basic the name and data type
of the variable.
NOTE: A variable can hold only one data type.
Once you declare variables, the variables always retain their
original declared data type. Therefore, a single-precision variable
can hold only single-precision values. When you store an integer
in a single-precision variable, Visual Basic converts the integer to
a single-precision number before the number gets to the
variable. Such data type conversions are common and they
typically do not cause many problems.
You use the Dim statement to declare variables (Dim stands for
dimension). The Dim statement defines variables. Dim tells
Visual Basic that somewhere else in the program the program
will need to use a variable. Dim describes the data type and also
assigns a name to the variable.
Lesson 2, “Analyzing Visual Basic Programs,” describes the
naming rules for controls, and you use the same naming rules
for variables. Follow the naming rules when you make up
names for variables. Whenever you learn a new statement, you
need to learn the format for that statement. Here is the format
of the Dim statement:
Dim VarName as datatype
VarName is a name that you supply. When Visual Basic executes
the Dim statement at runtime, it creates a variable in memory
and assigns it the name you give in the VarName location of
the statement. DataType is one of the data types that you
learned about in Table 5.1.
WARNING: Never declare two variables with the same name
in the same location. That is, you cannot declare two variables
with the name intNumber in the same event procedure.
Write code that declares these variables: your first name, your
last name, your age, your tax rate, and whether you are married.
Learning Objectives
How To Use Dim Statement
Table 5.3. Using variable name prefixes to maintain
accurate data types.
Why data type mixups can occur
When to use operators
Data Type Example
How To Put Putting Data in Variables
The Dim Statements Location
The location of the Dim determines how you use the variable.
If you include a special statement called the Option Explicit
statement at the very top of a form module or at the top of a
standard module (in a section called the general section that
appears before all event procedures), you must declare all
variables before you use them. Without Option Explicit, you
can begin using a variable name without declaring the variable,
but Visual Basic always assumes that the variable is a Variant
data type. If Dim appears in an event procedure, the variable is
visible (usable) only from within that event procedure and
known as a local variable. If you use Dim in a module’s general
section, all variables in that module can access the variable (the
variable is said to be global to the module). If you replace Dim
with Public in a general section (the Public statement uses the
same format as Dim), the variable is global to the entire module
as well as every other module within the project. Standard
module variables are almost always globally defined with Public
so that other modules within a project you add the standard
module to can access the variables. Generally, local variables are
better than global with a few exceptions (this book points out
these exceptions at the appropriate times).
New Term: Global variables are variables that are available to
the entire module or to the entire application.
New Term: Local variables are variables that are available only
to the procedure in which you define the variables.
The following statement defines a variable named
Dim curProductTotal As Currency
From the Dim statement, you know that the variable holds the
Currency data type and that the variable’s name is
curProductTotal. Programmers often prefix variable names with
a three-letter abbreviation that indicates the variable’s data type,
but such a prefix is not required. Table 5.3 lists these common
variable prefix values. Please remember that you put these
prefixes at the beginning of variable names just to remind
yourself of the variable’s data type. The prefix itself has no
meaning to Visual Basic and is just part of the name.
vnt or var Variant
The following statements define Integer, Single, and Double
Dim intLength As Integer
Dim sngPrice As Single
Dim dblStructure As Double
If you want to write a program that stores the user’s text box
entry for the first name, you would define a string like this:
Dim strFirstName As String
You can get fancy when you define strings. This strFirstName
string can hold any string from 0 to 65,500 characters long. You
will learn in the next section how to store data in a string. The
strFirstName string can hold data of virtually any size. You
could store a small string in strFirstName—such as “Joe”—and
then a longer string in strFirstName—such as “Mercedes”.
strFirstName is a variable-length string.
Sometimes you want to limit the amount of text that a string
holds. For example, you might need to define a String variable
to hold a name that you read from the disk file. Later, you will
display the contents of the string in a label on the form. The
form’s label has a fixed length, however—assuming that the
AutoSize property is set to True. Therefore, you want to keep
the String variable to a reasonable length. The following Dim
statement demonstrates how you can add the * StringLength
option when you want to define fixed-length strings:
Dim strTitle As String * 20
strTitle is the name of a String variable that can hold a string
from 0 to 20 characters long. If the program attempts to store a
string value that is longer than 20 characters in strTitle, Visual
Basic truncates the string and stores only the first 20 characters.
Here’s a shortcut: You can omit the As Variant descriptor when
you define Variant variables. This Dim statement:
Dim varValue As Variant
does exactly the same thing as this:
Dim varValue
A good rule of thumb is to make your code as explicit as
possible, so use As Variant to clarify your code intentions. If
you begin calling a variable one name, you must stay with that
name for the entire program. curSale is not the same variable
name as curSales. Use Option Explicit to guard against such
common variable-naming errors. Visual Basic supports a
shortcut when you need to define several variables. Instead of
listing each variable definition on separate lines like this:
conversion for you when the conversion is trivial. For example,
it is possible to perform the following assignment even if you
have defined dblMeasure to be a double-precision variable:
dblMeasure = 921.23
At first glance, it appears that 921.23 is a single-precision
number because of its size. 921.23 is actually a Variant data
value. Visual Basic assumes that all data literals are Variant
unless you explicitly add a suffix character to the literal to make
the constant a different data type. Visual Basic can easily and
safely convert the Variant value to double-precision. That’s just
what Visual Basic does here, so the assignment works fine.
New Term: Constant is another name for literal.
In addition to constants, you can assign other variables to
variables. Consider the following code:
Dim sngSales As Single, sngNewSales As Single
Dim A As Integer
sngSales = 3945.42
Dim B As Double
sngNewSales = sngSales
Dim C As Integer
When the third statement finishes, both sngSales and
sngNewSales have the value 3945.42.
Dim D As String
Dim A As Integer, C As Integer
Feel free to assign variables to controls and controls to variables.
Suppose, for example, that the user types the value 18.34 in a
text box’s Text property. If the text box’s Name property is
txtFactor, the following statement stores the value of the text
box in a variable named sngFactorVal:
Dim B As Double
sngFactorVal = txtFactor.Text
Dim D As String, E As String
Suppose that you defined strTitle to be a String variable with a
fixed length of 10, but a user types Mondays Always Feel Blue
in a text box’s Text property that you want to assign to strTitle.
Visual Basic stores only the first 10 characters of the control to
strTitle and truncates the rest of the title. Therefore, strTitle
holds only the string “Mondays Al”.
Dim E As String
you can combine variables of the same data type on one line.
Here’s an example:
Putting Data in Variables
So far you have learned how to define variables but not how to
store data in them. Use the assignment statement when you
want to put data values into variables. Variables hold data of
specific data types and many lines inside a Visual Basic program
consist of assignment statements that assign data to variables.
Here is the format of the assignment statement:
VarName = Expression
New Term: An assignment statement is a program statement
that puts data into a control, a variable, or another object.
VarName is a variable name that you have defined using the
Dim statement. Expression can be a literal, another variable, or
a mathematical expression.
Suppose that you need to store a minimum age value of 18 in
an Integer variable named intMinAge. The following assignment statement does that:
intMinAge = 18
To store a temperature in a single-precision variable named
sngTodayTemp, you could do this:
sngTodayTemp = 42.1
The data type of Expression must match the data type of the
variable to which you are assigning it. In other words, the
following statement is invalid. It would produce an error in
Visual Basic programs if you tried to use it:
sngTodayTemp = “Forty-Two point One”
sngTodayTemp is a single-precision variable, so you cannot
assign a string to it. However, Visual Basic often makes a quick
You can instantly make data appear on a form by assigning the
Text property of text boxes or the Caption property of labels
and command buttons. No variables are required to do this.
Suppose you put a command button named cmdPress on a
form. The event procedure shown in Listing 5.1 changes the
command button’s Caption property and immediately places a
new caption on the form (this occurs at runtime when this
event procedure executes).
E.g An event procedure that assigns a new command button
Private Sub cmdPress_Click ()
cmdPress.Caption = “Brush your teeth daily!”
End Sub
No matter what the command button’s Caption property is set
to at the start of the event procedure, when the user clicks the
command button, this event procedure executes and the
command button’s caption changes to Brush your teeth!.
Some properties accept only a limited range of values. Assign
only the number when a control’s property can accept a limited
range of values. For example, the possible values that you can
select for a label’s BorderStyle property in the Properties
window are 0-None and 1-Fixed Single. To assign border style
directly without using a named constant, assign just 0 or 1.
Don’t spell out the entire property. For example, you can assign
a fixed single-line border around a label like this:
lblSinger.BorderStyle = 1
Visual Basic includes a number of named literals internally that
you can use for assigning such controls when the controls
require a limited number of values. You can search the
property’s online help to see a list of named literals that you can
assign. For example, not only can you assign 0 and 1 to a label’s
border, but you can also assign one of the named literals,
vbBSNone and vbFixedSingle. Most named literals begin with
the Visual Basic prefix.
Expressions and Math Operators
You should learn Visual Basic’s math operators so you can
calculate and assign expression results to variables when you
code assignment statements that contain expressions. An
operator is a symbol or word that does math and data manipulation.
Table 5.4 describes Visual Basic’s primary math operators. Other
operators exist, but the ones in Table 5.4 suffice for most of the
programs that you write. Look over the operators. You are
already familiar with most of them because they look and act
just like their real-world counterparts.
Table 5.4. The primary math operators.
Opera tor Exa mple
Adds two values
Price - 4.00
Subtracts one value from another value
Total * Fact
Multiplies two values
Tax / Adjust
Divides one value by another value
Adjust ^ 3
Raises a value to a power
Name1 & Name2 Concatenates two strings
Net + Disc
(or +)
Suppose that you wanted to store the difference between the
annual sales (stored in a variable named curAnnualSales) and
cost of sales (stored in a variable named curCostOfSales) in a
variable named curNetSales. Assuming that all three variables
have been defined and initialized, the following assignment
statement computes the correct value for curNetSales:
curNetSales = curAnnualSales - curCostOfSales
This assignment tells Visual Basic to compute the value of the
expression and to store the result in the variable named
curNetSales. Of course, you can store the results of this
expression in a control’s Caption or Text properties, too.
If you want to raise a value by a power-which means to
multiply the value by itself a certain number of times-you can
do so. The following code assigns 10000 to lngValue because 10
raised to the fourth power (10 times 10 times 10 times 10) is
lngYears = 4
variable at the left of the equal sign. The following assignment
statement, for example, is rather lengthy, but Visual Basic
computes the result and stores the value in the variable named
sngAns = 8 * sngFactor - sngPi + 12 * sngMonthlyAmts
Combining expressions often produces unintended results
because Visual Basic computes mathematical results in a
predetermined order. Visual Basic always calculates exponentiation first if one or more ^ operators appear in the expression.
Visual Basic then computes all multiplication and divisionworking from left to right-before any addition and subtraction.
Visual Basic assigns 13 to intResult in the following assignment:
intResult = 3 + 5 * 2
At first, you might think that Visual Basic would assign 16 to
intResult because 3 + 5 is 8 and 8 * 2 is 16. However, the rules
state that Visual Basic always computes multiplication-and
division if division exists in the expression-before addition.
Therefore, Visual Basic first computes the value of 5 * 2, or 10,
and next adds 3 to 10 to get 13. Only then does it assign the 13
to Result.
If both multiplication and division appear in the same
expression, Visual Basic calculates the intermediate results from
left to right. For example, Visual Basic assigns 20 to the
following expression:
intResult = 8 / 2 + 4 + 3 * 4
Visual Basic computes the division first because the division
appears to the left of the multiplication. If the multiplication
appeared to the left of the division, Visual Basic would have
multiplied first. After Visual Basic calculates the intermediate
answers for the division and the multiplication, it performs the
addition and stores the final answer of 20 in intResult.
NOTE: The order of computation has many names. Programmers usually use one of these terms: order of operators,
operator precedence, or math hierarchy.
It is possible to override the operator precedence by using
parentheses. Visual Basic always computes the values inside any
pair of parentheses before anything else in the expression, even
if it means ignoring operator precedence. The following
assignment statement stores 16 in intResult because the
parentheses force Visual Basic to compute the addition before
the multiplication:
intResult = (3 + 5) * 2
TIP: Appendix A, “Operator Precedence,” contains the
complete Visual Basic operator precedence table. The table
contains several operators that you have yet to learn about, so
you might not understand the full table at this time.
The following expression stores the fifth root of 125 in the
variable named sngRoot5:
sngRoot5 = 125 ^ (1/5)
lngValue = 10 ^ intYears
As you can see from this expression, Visual Basic supports
fractional exponents.
No matter how complex the expression is, Visual Basic
computes the entire result before it stores that result in the
New Term: To concatenate means to merge two strings
One of Visual Basic’s primary operators has nothing to do with
math. The concatenation operator joins one string to the end
of another. Suppose that the user entered his first name in a
Label control named lblFirst and his last name in a Label
control named lblLast. The following concatenation expression
stores the full name in the String variable named strFullName:
rule! Byte is generally reserved for special system-level coding.
Generally, the smallest integer programmers use is the Integer
data type even though an Integer is slightly less efficient than a
Byte data type because the computer has to transfer more
information at one time when working with integers.
strFullName = lblFirst & lblLast
The quiz questions and exercises are provided for your further
understanding. See Appendix C, “Answers,” for answers.
There is a problem here, though, that might not be readily
apparent-there is no space between the two names. The &
operator does not automatically insert a space because you don’t
always want spaces inserted when you concatenate two strings.
Therefore, you might have to concatenate a third string between
the other two, as in
strFullName = lblFirst & “ “ & lblLast
Visual Basic actually supports a synonym operator, the plus sign
(+), for concatenation. In other words, the following assignment statement is identical to the previous one (although the
ampersand [&] keeps ambiguity down because of the plus
sign’s double usage with numbers and strings):
strFullName = lblFirst + “ “ + lblLast
Use the ampersand for string concatenation even though the
plus sign works also. The ampersand is less ambiguous and
makes for better programs.
1. What is a data type?
2. What is the difference between a String and a Boolean data
3. What are two controls that behave as if they conform to the
Boolean data type?
4. What is the difference between a literal and a variable?
5. Which of the following are invalid variable names?
NOTE: Remember that you’ll use the Code window to enter
code such as that which you see in this lesson. The Code
window appears when you select View|Code or when you
double-click a control to open its event procedure as you saw in
Lesson 3, “Controls and Properties.”
6. Which operator performs two operations?
a. ans = 1 + 2 + 3 + 4 / 2
In this lesson you have learned how to recognize and use Visual
Basic data. Visual Basic supports 14 data types, and you must
know how to specify literals and declare variables that take on
those data types. Once you know the data types and variables,
you can perform calculations that assign the results of expressions to variables and controls.
The next lesson adds to your programming power by explaining a quick and simple way to display information and receive
user input.
Q I don’t like math, so will I not like VB programming?
A Visual Basic does all the math for you! That’s why you
learned the operators. People who do not like math use
calculators and people who do not like math can write VB
Q If I want to represent a person’s age value, which
integer-based data type do I use?
A The quick answer is that you should use the smallest data
type that will hold every value you’d want to assign. A person’s
age rarely gets over 100 and does not ever go past 255. Therefore, you could use a Byte data type for a person’s age. The Byte
data type is small and is much more efficient than a Long. You
should now have the idea that you need to ensure that your
variables can hold all the data required but that you should not
use one that’s too large and that will use unnecessary space.
Having said that, the Byte data type is really an exception to that
7. What is the difference between a fixed-length string and a
variable-length string?
8. What value would Visual Basic store in the following ans
b. ans = 1 + 2 + 3 + (4 / 2)
c. ans = 2 ^ 5
d. ans = 25 - 8 / 2 ^ 2 + 1
1. Write an application that accepts your age in a text box and
then displays, when you click a command button, your age in
dog years (your age divided by 7). Don’t worry about
rounding that might take place.
Learning Objectives
How message boxes differ from text boxes
Why functions benefit programmers
When to test message box return values
Why to add remarks
How to receive input box answers
In this and subsequent lessons, your application will need to
display messages and ask questions of the user. The application
needs to receive the user’s response from the questions.
Although the Label and Text Box controls work well for giving
and receiving user information, such controls don’t lend
themselves to messages and questions that the program
displays during execution such as error messages and warning
For example, suppose you want to know if the user has
prepared the printer for printing. To prepare a printer, the user
has to turn on the printer, make sure paper is there, and ensure
that the online light is on. Your program should not attempt
to print a report until the user has performed these actions or
an error will occur. Therefore, when the user initiates a report for
printing, your application can gather the data and then ask the
user if the printer is ready. If the user responds affirmatively,
you can start the report’s output. The form’s controls simply do
not provide such interaction. In this lesson’s lesson you will
learn how to display message boxes and input boxes that
provide runtime I/O.
A Function Preview
The programming language you’ve learned so far-the variable
declarations, assignments, and operator usage-has focused on
programming statements. This lesson begins to discuss a new
kind of programming language concept called a function.
Visual Basic comes supplied with several built-in functions
(often called intrinsic functions) that do work for you. Many
functions perform common mathematical tasks such as
computing a square root. Other functions manipulate sting data
such as converting text inside a string to uppercase or lowercase
letters. Other functions, such as the functions taught in this
lesson, perform input and output.
A function is a routine that accepts zero, one, or more arguments and returns a single result based on the argument list.
An intrinsic function is a function supplied with Visual Basic.
NOTE: Lesson 13, “Modular Programming,” and 14, “Built-in
Functions Save Time,” describe how you can write your own
A function takes zero, one, or more arguments and converts
those arguments to a single return value. Figure 6.1 shows an
overview of a function’s job. The most important thing to
remember is that a function always returns a single value.
New Term: An argument is a value you pass to a function so
the function has data to work with.
A function’s job is to save you time. For example, if you need
to compute the square root of a user’s entered value, you could
write the assignments and expressions to compute the square
root. The square root, however, is such a common routine that
Microsoft wrote the code once and stored the square root
routine in an intrinsic function. Now, if you want the square
root of a value, you’ll pass the value as a single argument to the
square root function, and after performing the necessary math,
the square root function will return the root.
This lesson focuses on two intrinsic functions that don’t do
math. Instead, they display messages or receive user input.
Don’t worry too much about what a function is as long as you
have the general idea. You’ll become much more familiar with
them before you’re through with this tutorial.
This lesson spends the rest of the lesson teaching you these
NOTE: Function names, unlike variable names, usually appear
with parentheses at the end. The parentheses hold the function
arguments that you send to the function. Even if a function
receives no arguments, the parentheses are still required when
you use the functions.
A MsgBox() and InputBox() Overview
You use input boxes and message boxes when you need to ask
the user questions or display error messages and advice to the
user. As stated earlier, the form’s controls don’t often work well
for such user dialogs. For example, suppose the user is to enter
a sales code of A, B, or C to indicate a discount to be used in a
total calculation. Users don’t always know what’s expected of
them, so a message box can pop up when the user enters a bad
value and the message box can explain that the user needs to
enter only A, B, or C. If the user enters an invalid code, your
program could display an error message such as the one shown
in Figure 6.2.
New Term: A message box is a dialog box you display to give
the user information.
New Term: An input box is a dialog box you display to ask
the user questions.
WARNING: You may hear about a Visual Basic statement
called the MsgBox statement (as opposed to the MsgBox()
function). Although Visual Basic does still support the MsgBox
statement, Microsoft recommends that you use only the
MsgBox() function due to its inspection ability for a return
value. (The MsgBox statement does not even appear in Visual
Basic 5’s online help.)
The Text Box controls that you’ve seen are great for getting
values from the user. Other controls that you’ll learn as you
progress through this book also accept the user’s input from
the keyboard or mouse. Nevertheless, Visual Basic’s controls
just aren’t enough to handle all the input that your program
will need. Input boxes are great to use when the user must
respond to certain kinds of questions. Text boxes and other
controls are fine for getting fixed input from the user, such as
data values with which the program will compute. Input boxes
are great for asking the user questions that arise only under
certain conditions. Input boxes always give the user a place to
respond with an answer. In Figure 6.3, the input box is asking
the user for a title that will go at the top of a printed report
Figure 6.3. Input boxes get user information.
Note that there is more than one way for the user to respond to
the input box in Figure 6.3. The user can answer the question
by typing the title at the bottom of the input box and pressing
Enter or clicking the OK command button. The user also can
click the Cancel command button whether or not the user
entered a title. Therefore, the program must be capable of
reading the user’s entered answer as well as responding to a
Cancel command button press. Responding to message box
and input box command buttons is part of the processing that
you’ll learn about in the remaining sections of this lesson.
Examining MsgBox()
Always assign a MsgBox() function to an integer variable. The
variable will hold the return value, and that value will indicate
the button the user clicked (message boxes can display multiple
buttons such as OK and Cancel).
Here is the format of the MsgBox() function:
anIntVariable = MsgBox( strMsg [, [intType] [, strTitle]])
NOTE: The MsgBox() function’s format shown here accepts
one required (strMsg) and two optional (intType and strTitle)
arguments. MsgBox() can accept more arguments, but these
three are the only ones needed in most applications.
strMsg is a string (either a variable or a string constant enclosed
in quotation marks) and forms the text of the message
displayed in the message box. intType is an optional numeric
value or expression that describes the options you want in the
message box. Table 6.1, Table 6.2, and Table 6.3 contain all the
possible values you can use for the type of message box you
want displayed. (Visual Basic displays no icon if you don’t
specify an intType value.) If you want to use a value from two
or more of the tables, you’ll add the values together. Although
you can use the integer value, if you use the built-in Visual Basic
named literal, you’ll more easily understand the message box’s
style if you ever have to change the message box in the future.
strTitle is an optional string that represents the text in the
message box’s title bar. If you omit strTitle, Visual Basic uses
the project’s name for the message box’s title bar text.
Table 6.1. The buttons displayed in a message box.
Named Literal Value Description
Displays the OK button.
Displays the OK and Cancel buttons.
vbAbortRetryIgnore 2
Displays the Abort, Retry, and Ignore buttons.
Displays the Yes, No, and Cancel buttons.
Displays the Yes and No buttons.
Displays the Retry and Cancel buttons.
Table 6.2. The icons displayed in a message box.
Named Literal Value Description
Displays Critical Message icon.
Displays Warning Query icon.
Displays Warning Message icon.
Displays Information Message icon.
Table 6.3. The default buttons displayed in a message box.
Named Literal Value Description
vbDefaultButton1 0
The first button is the default.
vbDefaultButton2 256
vbDefaultButton3 512
The second button is the default.
The third button is the default.
The options that you select, using the intType value in the
MsgBox() function, determine whether the message box
displays an icon and controls the modality of the message box.
The modality determines whether a message box is application
specific or system specific. If it is application specific, the user
must respond to the message box before the user can do
anything else in the application. If the message box is system
specific, the user must respond to the message box before
doing anything else on the system.
New Term: Modality determines how the system handles a
dialog box.
The modality often causes confusion. If you don’t specify a
system-modal intType value of 4096 (or if you don’t use the
named literal vbSystemModal to specify the system’s modal
mode), the user’s application will not continue until the user
closes the message box, but the user can switch to another
Windows program by pressing Alt+Tab or by switching to
another program using the application’s control menu. If,
however, you do specify that the message box is system modal,
the user will not be able to switch to another Windows
program until the user responds to the message box because
the message box will have full control of the system. Reserve
the system-modal message boxes for serious error messages
that you want the user to read and respond to before continuing the program.
NOTE: If you don’t specify an icon, Visual Basic doesn’t
display an icon. If you don’t specify the system modality, Visual
Basic assumes that you want an application-modal message
The following MsgBox() function produces the message box
shown in Figure 6.4:
intPress = MsgBox(“Are you ready for the report?”,
vbQuestion + _
vbYesNoCancel, “Report Request”)
as shown in Figure 6.5.
Visual Basic give you help not only with a function’s format,
but also with the function’s named literals. When you get to any
function argument that requires one of the named literals,
Visual Basic displays a drop-down list box such as the one in
Figure 6.6, from which you can select a named literal. To accept
the selected named literal, press Enter, type a comma, or press
the Spacebar to continue with the program.
TIP: If you need to type long VB program statements, such as
this MsgBox() function, you can break the line into multiple,
more manageable lines by terminating the first line with an
underscore character (_).
NOTE: The format and argument list box pop-up help
appears all throughout Visual Basic. As you learn additional
Visual Basic statements, you’ll see the pop-up Code window
help more often.
Figure 6.4. Message boxes support several command buttons.
Remember that the MsgBox() values such as vbQuestion and
vbYesNoCancel are not variables but are named literals that
Visual Basic has defined to correspond with matching integer
values. The named literals vbQuestion and vbYesNoCancel
produced both a question mark icon and the three buttons. A
title also appeared due to the third value inside the MsgBox()
A Short Detour: Remarks
Figures 6.5 and 6.6 show two new program statements you’ve
not seen to this point. Two remark statements appear in each
figure. Remarks help both you and other programmers who
might modify and update your Visual Basic applications in the
future. Remarks offer descriptive messages that explain in
English (or whatever language you prefer) what’s going on in
the program’s event procedures.
It’s said that a program is written once and read many times.
That saying is true because of the nature of applications. Often,
you’ll write a program that helps you or your business compute
required calculations and keep track of daily transactions. Over
time, requirements change. Businesses buy and sell other
businesses, the government changes its reporting and taxing
requirements, and people’s needs change. You should realize
that, after you write and implement a program, you will make
modifications to that program later. If you use the program in
a business, you’ll almost certainly make many modifications to
the program to reflect changing conditions.
TIP: If you program for someone else or as part of a team, the
chances are high that others will modify the programs that you
write and that you’ll modify programs that other programmers
write. Therefore, as you write programs, think about the future
maintenance that you and others will make. Write your programs clearly, using ample spacing and indentation, and add
remarks that explain difficult sections of code.
New Term: A remark is a message that you put inside a
program’s code. Programmers concerned about maintenance
know that ample remarks help clarify code and aid future
maintenance. Visual Basic completely ignores any and all
remarks because those remarks are for people looking at your
program code. Users don’t see remarks because users don’t see
the program’s code; rather, users see a program’s output.
Programmers often add remarks to their programs for the
following purposes:
• To state the programmer’s name and the date that the
program was written
MsgBox()s Return Value
The reason that you assign MsgBox() functions to variables is
so you can tell which button the user presses. Suppose that the
user pressed the Yes button in Figure 6.4. The program could
then print the report. If, however, the user pressed the No
button, the program could describe what the user needed to do
to get ready for the report (load paper, turn on the printer, and
so on). If the user pressed the Cancel button, the program
would know that the user didn’t want the report at all.
Table 6.4 lists the seven possible MsgBox() return values. You
can test either for the integer or the named literal return value.
Table 6.4. MsgBox() return values.
Named Constant Value Description
The user clicked the OK button.
The user clicked the Cancel button.
The user clicked the Abort button.
The user clicked the Retry button.
The user clicked the Ignore button.
The user clicked the Yes button.
The user clicked the No button.
NOTE: You’ll learn how to test for specific values in Lesson 7,
“Making Decisions.”
Visual Basics Code Window Help
Can you remember the named literals in this lesson’s tables?
How can you remember that the named literal value to display
three buttons-Yes, No, and Cancel-is the vbYesNoCancel
named literal?
Fortunately, with version 5, Visual Basic now supplies you with
all the help you need. As soon as VB’s Code window editor
recognizes that you’re entering a function, the editor immediately displays pop-up help that displays the function’s format,
To describe in the general section the overall goal of the
program (the general section appears before all of a
procedure’s procedures and is the location Lesson 5, “Putting
Code into Visual Basic,” described when it talked about
declaring global variables)
To describe at the top of every procedure the overall goal of
that procedure
To explain tricky or difficult statements so that others who
modify the program later can understand the lines of code
without having to decipher cryptic code
Even if you write programs for yourself, and if you are the only
one who will modify your programs, you should still add
remarks to your programs! Weeks or months after you write a
program, you’ll have forgotten the exact details of the program,
and remarks that you interspersed throughout the code will
simplify your maintenance and will help you find the code that
you need to change.
Rem. When someone looks at the program code later, that
person will know who the programmer is, the date that the
program was written, the overall purpose of the program, and
the overall description of each procedure that includes a remark
Say that you used apostrophes in place of the Rem statement in
the previous remarks. The following rewritten remarks demonstrate that the remarks are even more effective because Rem
doesn’t get in the way of each remark’s text:
‘ Programmer: Grant Holdorf, Date: Mar-27-1999
TIP: Add remarks as you write your programs. Often, programmers say to themselves, “I’ll finish the program and add
remarks later.” Trust me-the remarks don’t get added. It’s only
later, when programmers need to modify the program, that
they notice the lack of remarks-and regret it.
Add remarks to your program so that you and others can more
quickly grasp the nature of the program and can make modifications to it more easily when needed. Visual Basic supports
several remark formats. Unlike in some other programming
languages, Visual Basic remarks are easy to add to your code,
and their free-form nature enables you to add remarks whenever
and wherever needed.
‘ This event procedure executes when the user
Visual Basic Supports two kinds of Remarks:
Remarks that begin with the Rem statement
Remarks that begin with the apostrophe (‘)
The Rem statement is more limiting than the apostrophe and
isn’t as easy to use. Nevertheless, you’ll run across programs
that use Rem statements, so you should learn how Rem works.
Here is the format of the Rem statement:
‘ This program supports the check-in and check-out
‘ process for the dry-cleaning business.
‘ clicks on the Exit command button. When pressed,
‘ this event procedure closes the program’s data
‘ files, prints an exception report, and terminates
‘ the application
The remarks don’t have to go at the beginning of event
procedures. You can place remarks between lines of code, as
done here:
Dim intRec As Integer
Rem Step through each customer record
For intRec = 1 To intNumCusts
‘ Test for a high balance
If custBal(intRec) > 5000 Then
Rem The remark’s text
Call PayReq
You can put anything you want in place of The remark’s text.
The following are examples of remarks:
End If
Rem Programmer: Grant Holdorf, Date: Mar-27-1999
Rem This program supports the check-in and check-out
Rem process for the dry-cleaning business.
Next intRec
NOTE: Don’t try to understand the details of this code yet.
Concentrate now on the remarks. The code contains some
advanced features (Visual Basic arrays and subroutine procedures) that you’ll learn about in the last half of this book.
Rem this event procedure closes the program’s data
You can place apostrophe remarks at the end of Visual Basic
statements. By placing a remark to the right of certain lines of
code, you can clarify the purpose of the code. Consider how the
following code section uses a remark to explain a specific line of
Rem files, prints an exception report, and terminates
a = 3.14159 * r ^ r ‘ Calculate a circle’s area
Rem the application
Perhaps only a mathematician could interpret the formula
without the remark. The remark helps even non-mathematicians understand the purpose of the statement. There is no
reason that you should have to re-examine code every time you
look at it. By reading remarks, you can glean the code’s purpose
without taking the time to interpret the Visual Basic code.
Rem This event procedure executes when the user
Rem clicks on the Exit command button. When pressed,
The first of these remark sections consists of a one-line remark
that tells the programmer’s name and the date that the program
was last modified. If someone else must modify the program
later, that person can find the original programmer if needed to
ask questions about the program’s code. The second remark
describes the overall program’s goal by starting with a high-level
description of the program’s purpose. The third remark might
appear at the top of a command button’s Click event procedure.
As you can see, you can add one or more lines of remarks
depending on the amount of description needed at that point
in the program. Visual Basic ignores all lines that begin with
The wrong kind of remarks won’t help clarify code, though, so
don’t overdo remarks. As a matter of fact, lots of lines of code
need no remarks to explain their purpose. The following
remark is redundant and wastes both your programming time
and the time of anyone who may maintain the program later:
Dim Sales As Single ‘ Define a variable named Sales
Examining InputBox()
You’ll find that the InputBox() function is easy because it acts a
lot like the MsgBox() function. The InputBox() function
receives answers that are more complete than the MsgBox()
function can get. Whereas MsgBox() returns one of seven
values that indicate the user’s command button press, the
InputBox() function returns a string data value that holds the
answer typed by the user.
Here is the format of the InputBox() function:
strVariable = InputBox( strprompt [, [strTitle] [, strDefault]
Â[, intXpos, intYpos]]])
strPrompt works a lot like the strmsg value in a MsgBox()
function. The user sees strPrompt inside the input box
displayed on the screen. strTitle is the title inside the input box’s
title bar. strDefault is a default string value that Visual Basic
displays for a default answer, and the user can accept the default
answer or change the default answer.
The intXpos and intYpos positions indicate the exact location
where you want the input box to appear on the form. The
intXpos value holds the number of twips from the left edge of
the Form window to the left edge of the input box. The
intYpos value holds the number of twips from the top edge of
the Form window to the top edge of the input box. If you
omit the intXpos and intYpos values, Visual Basic centers the
message box on the form.
NOTE: Input boxes always contain OK and Cancel command
buttons. If the user clicks OK (or presses Enter, which selects
OK by default), the answer in the input box is sent to the
variable being assigned the returned value. If the user clicks
Cancel, a null string (“”) returns from the InputBox() function.
The following statement displays an input box that asks the
user for a company name. The user either enters a response to
the prompt or clicks the Cancel command button to indicate
that no answer is coming.
strCompName = InputBox(“What is the name of the
 “Company Request”, “XYZ, Inc.”)
TIP: You can offer a default answer that the user can accept or
change in the strDefault argument. The input box function
returns the answer to the string variable to which you assign the
Figure 6.7 contains the message box displayed from this
InputBox() function.
Figure 6.7. Asking the user a question and getting the answer
with InputBox().
This lesson introduces functions so you can prepare for
message boxes and input boxes. Message boxes display output,
and input boxes get input. The message and input boxes offer
ways for your programs to request information that regular
controls can’t handle. Use controls to display and get data values
that are always needed. Use message and input boxes to display
messages and get answers that the program needs in special
cases, such as for error conditions and exception handling.
The next lesson explains how to test the return values from this
lesson’s functions as well as shows you additional operators
with which your applications can make decisions.
Q When do I use controls and when do I use message and
input boxes?
A You use Form controls when the user is to interact with a
form and enter values the form module will process. The
Toolbox controls are extremely useful for guiding the user
through a list of choices. The message box is a program feature
you can use to display one-time notes and warnings to your
users. The input box is a great one-time dialog box you can
display to ask the user for questions when needed during the
execution of the program.
Q Why should I add remarks to my code?
A You’ll modify your programs over time. The more you
modify a program, the faster that modification (called maintenance) will go if you add ample remarks at the time you create
the program. The remarks help you remember what a particular
section of code is for. In addition to remarks, use named literals
when available for options such as the message box button type
because the named literal mnemonics are easier to remember
than their numeric equivalents.
The quiz questions and exercises are provided for your further
understanding. See Appendix C, “Answers,” for answers.
1. What is the difference between a message box and a text box?
2. Which stays on the user’s screen during the majority of a
program’s execution: a text box or an input box?
3. Why do the named literals provide for better program
4. What are the two kinds of remark statements?
5. Who are remarks for?
6. What does modal mean?
7. How many icons can you display with message boxes?
8. True or false: You can pass multiple arguments and receive
multiple return values from functions.
9. What role do default values play in input boxes?
10. True or false: The MsgBox() function can return one of
seven values.
1. Write three remarks for the top of a program that calculates
sales tax. The first remark should hold your name, the
second should hold the date that you write the remark, and
the third should span at least two lines and should describe
the purpose of the program.
2. Write an input box function that asks users for their ages.
Display a default value of 25.
Learning Objectives
New Term: Comparison operators are operators that compare
data values against each other and produce true or false results.
Which comparison operators to use
How to form If statements
When to use an Else branch
You learned VB’s mathematical operators in previous lesson,
“Putting Code into Visual Basic”; but Visual Basic supports
several more operators, as you’ll learn in this lesson. The
operators described here are called the comparison operators
because they compare data and determine the results of the
comparison. By using comparison operators, you can write your
programs so that they make certain runtime decisions based on
the comparison results.
Comparison Operators
All the comparison operators produce true or false results. In
other words, the comparison is either true or the comparison is
false. The mathematical operators produce numeric values,
whereas the comparison operators produce true or false values.
A comparison operator can produce nothing more than a true
or false result. The rest of the program can use the true or false
comparison operator result to make decisions. For example, if a
comparison operator returns False when comparing whether an
employee worked the last pay period, the rest of the program
knows not to print a paycheck for that employee.
NOTE: This section describes just the operators; subsequent
sections in this lesson’s lesson describe new programming
statements that can make use of the comparison operators.
Table 7.1 describes VB’s six comparison operators. The
comparison operators always compare data, and that comparison is either true or false because data either compares as
expected or does not.
TIP: Two values can be equal to one another or one can be
greater than the other. Keep these possibilities in mind as you
read through Table 7.1.
Table 7.1. The comparison operators determine how data
Operator Usage
lblSales.Caption > The greater than operator returns True if the value on the left
side of > is numerically or alphabetically greater than the value
on the right.
Pay < 2000.00
The less than operator returns True if the value on the left side of
< is numerically or alphabetically less than the value on the right.
Age = Limit
The equal to operator (sometimes called the equal operator)
returns True if the values on both sides of = are equal to each
FirstName >=
The greater than or equal to operator returns True if the value on
the left side of >= is numerically or alphabetically greater than or
equal to the value on the right.
Num <=
The less than or equal to operator returns True if the value on the
left side of <= is numerically or alphabetically less than or equal
to the value on the right.
txtAns.Text <>
The not equal to operator returns True if the value on the left
side of <> is numerically or alphabetically unequal to the value
on the right.
NOTE: Remember that if a comparison operator does not
produce a true result, the result must be false.
As you can see from Table 7.1, the comparison operators
compare either variables, literals, control values, or combinations of all those data sources. The comparison operators work
on both numeric and alphabetic values. You can compare any
kind of number against another number, or any kind of string
against another string.
The Comparisons Nature
When you compare strings, Visual Basic uses the ASCII table,
included in Appendix B, “ASCII Table,” to determine how to
compare the characters. For example, the ASCII table says that
the uppercase letter A-whose ASCII numeric value is 65-is less
than the uppercase letter B-whose ASCII numeric value is 66.
Notice that all uppercase letters are less than lowercase letters.
Therefore, the abbreviation ST is less than St.
New Term: An ASCII table contains a list of characters with
corresponding unique numeric representations.
To understand how comparison operators work, you must
understand how to use their true or false results. The If
statement, introduced in the next section, explains how you can
use true and false results to make decisions in your program.
Before you read the next section, make sure that you understand how these operators compare values. Make sure that you
understand the Result column of Table 7.2 before you go any
Table 7.2. Relationship results.
"Apple" <= "Orange"
"Macmillan" < "Mc millan" True
0 >= 0
0 <= 0
1 <> 2
2 >= 3
Keep each sides Data Type Consistent
Take extra care that the expressions on both sides of a comparison operator conform to the same data type or at least
compatible data types. In other words, you cannot compare a
string to a numeric data type. If you try, you will get a type
mismatch error because the data types don’t match. You can
compare any numeric data type against any other numeric data
type most of the time. In other words, you can test whether a
single-precision value is less than or greater than an integer
WARNING: Be careful when you compare non-integers for
equality. Precision numbers are difficult to represent internally.
For example, if you assigned 8.3221 to a single-precision
variable and assigned 8.3221 to another single-precision variable,
Visual Basic might return a false result if you compare the
values for equality. Internally, one of the variables might actually
hold 8.322100001 because of rounding errors that occur in
insignificant decimal places. You can safely compare two currency
values for equality, however, because Visual Basic maintains and
compares their accuracy to two decimal places.
NOTE: The comparison operators are sometimes called the
conditional operators because they test conditions that are either
true or false.
The comparison operators compare values against one another.
You can compare for equality, inequality, and size differences.
The comparison operators work for both string data and
numeric data. By themselves, the comparison operators would
not be worth much. However, you can use them to compare
data by using the If statement, which you’ll learn about in the
next section.
The If Statement
Perhaps the most important statement in a program is the If
statement and its cousin statements. With logic that If
provides, your application can begin to analyze data and make
decisions based on that analysis. For example, your program can
display a three-button message box and determine, with the If
statement, which command button the user clicked to close the
message box.
If uses the comparison operators you learned earlier in this
lesson to test data values. If performs one of two possible
code actions, depending on the result of the comparison.
Visual Basic can test whether to execute complete blocks of
code. In other words, If uses comparison operator results to
test data. If might execute one or more lines of subsequent
code, depending on the results of the comparison’s test.
Before If, the code you wrote executed sequentially, one
statement after another. If lets your program be more decisive
and execute only parts of the program if the data warrants
partial execution. For example, suppose you were writing an
invoicing system. In such a system, no sales tax should be
computed for tax-exempt organizations, so your program
would skip over the tax computation code when processing
such organizations.
If makes decisions. If a comparison test is true, the body of
the If statement executes. (In fact, the previous sentence is
almost identical to Visual Basic’s If statement!) Here is one
format of If:
If comparisonTest Then
One or more Visual Basic statements
End If
End If lets Visual Basic know where the body of the If
statement ends. Suppose that the user enters a sales figure into
a Text Box control named txtSales. The following If computes
a bonus amount based on the sales:
If (txtSales.Text > 5000.00) Then
sngBonus = txtSales.Text * .12
End If
NOTE: Data enters a control such as a text box as a Variant
data type. When you perform arithmetic with a Variant and the
Variant data type holds a numeric value, Visual Basic converts
the Variant to a number for the calculation.
Remember that Visual Basic stores 0 in all numeric variables
that you don’t first initialize. Therefore, sngBonus has a 0
before the If executes. Once the If executes, the code changes
the sngBonus variable only if the value of the txtSales.Text
property is more than 5000.00. In a way, the If reads like this:
If the sales are more than $5,000.00, then compute a bonus
based on that sales value.
Visual Basic stores a null zero in string variables that you have
not yet initialized. If you use an uninitialized Variant data type
variable, the variable holds a null value that becomes zero if you
assign the variable to a numeric variable.
The body of an If can have more than one statement. The
body is often called a block. The following If calculates a bonus,
the cost of sales, and a reorder amount based on the value of
the txtSales text box entry:
If (txtSales.Text > 5000.00) Then
sngBonus = txtSales.Text * .12
curCostOfSales = txtSales.Text * .41
curReorderCost = txtSales.Text * .24
End If
The three statements that make up the body of the If execute
only if the condition txtSales.Text > 5000.00 is true. Suppose
that this code contains another assignment statement immediately after End If. That assignment statement is outside the
body of the If, so the true or false result of the condition
affects only the body of the If. Therefore, the tax computation
in the following routine executes regardless of whether the sales
are more than or less than $5,000.00:
If (txtSales.Text > 5000.00) Then
sngBonus = txtSales.Text * .12
curCostOfSales = txtSales.Text * .41
curReorderCost = txtSales.Text * .24
End If
sngTax = .12 * txtSales.Text
TIP: The parentheses are not required around the comparison
test in an If, but they help separate the test from the rest of the
code. In addition, the indentation helps illustrate the code that
appears inside the If statement’s body.
Can you see how the program makes decisions using If? The
body of the If executes only if the comparison test is true.
Otherwise, the rest of the program continues as usual.
There is a shortcut form of If that you might run across. The
single-line If statement has a format that looks like this:
If comparisonTest Then VBStatement
The single-line If does not require an End If statement because
the comparison test and the body of the If reside on the same
line. Single-line If statements do not provide for easy program
maintenance. If you decide that you want to add to the body of
the If, you must convert the single-line If to a multiple-line If,
and you might forget to then add End If. Therefore, even if the
body of an If statement takes only one line, code the If as a
multiple-line If-End If statement to make the program more
The If Statements Else Branch
Whereas If executes code based on the comparison test’s true
condition, the Else statement executes code based on the
comparison test’s false condition. Else is an optional part of the
If statement. Else specifies the code that executes if the
comparison test is false. Here is the complete format of the If
statement with Else:
If comparisonTest Then
One or more Visual Basic statements
One or more Visual Basic statements
End If
Typically, programmers call this full-blown If statement the IfElse statement. The If-Else statement is sometimes called a
mutually exclusive statement. The term mutually exclusive
simply means that one set of code or the other executes, but
not both. The If-Else statement contains two sets of code-that
is, two bodies of one or more Visual Basic statements-and only
one set executes, depending on the result of the If. An If
statement is either true or false because the If ’s comparison
produces either a true or false result. Therefore, either the first or
the second body of code in an If-Else executes.
Suppose that a salesperson receives a bonus if sales are high
(over $5,000.00) or suffers a pay cut if sales are low (below
$5,000.00). The If-Else shown next contains the code necessary
to reward or punish the salesperson. The code body of the If
computes the bonus as done in the previous section. The code
body of the Else subtracts $25 from the salesperson’s pay,
which is stored in the variable named curPayAmt, if the sales
quota is not met. The following code computes such a payment
amount based on the quota:
If (txtSales.Text > 5000.00) Then
sngBonus = .05 * txtSales.Text
curPayAmt = curPayAmt - 25.00
End If
curTaxes = curPayAmt * .42
The fourth line in these code lines may surprise you at first. The
assignment appears to make the statement that the pay is equal
to the pay minus 25. You know that nothing can be equal to
itself minus 25. In math, the equal sign acts as a balance for the
two sides of the equation. In Visual Basic, however, when the
equal sign is not used inside an If ’s comparison test, it is an
assignment that takes everything to the right of the equal sign
and stores that value in the variable to the left of the equal sign.
Therefore, the fourth line subtracts the 25 from the value stored
in curPayAmt and then assigns that result back to curPayAmt.
In effect, it lowers the value of curPayAmt by 25.
NOTE: When a variable appears on both sides of an
assignment’s equal sign, the variable is being updated in some
To further your understanding of the If-Else statement and to
demonstrate testing for an input box’s return value, study how
Listing 7.1 uses If-Else to respond to an input box. The code
asks the user for a company name and then accepts the name or
recognizes that the user clicked Cancel to get rid of the input
box without answering it. (When a user clicks Cancel in
response to an input box, the input box returns a null string,
E.g Checking an input boxs return value.
Dim strCompName As String
Dim intPress As Integer ‘ MsgBox return value
‘ Ask the user for a name
‘ Use XYZ, Inc. for the default name
strCompName = InputBox(“What is the company name?”, _
“Company Request”, “XYZ, Inc.”)
‘ Check the return value
If (strCompName = “”) Then
‘ The user pressed Cancel
intPress = MsgBox(“Thanks anyway”)
‘ The user entered a company name
intPress = MsgBox(“You entered “ & strCompName)
End If
1. Rewrite the following nested If statement using a single If
with a logical operator:
If (A > 3) Then
If (B > 10) Then
lblAns.Caption = “Yes”
End If
End If
Learning Objectives
Learn About Logical Operators
If (sngSales > 5000.00) And (intUnitsSold > 10000) Then
sngBonus = 50.00
Using IF and Else
End If
How Select Case statements streamline If-Else
How can you rewrite this If to pay the bonus if the salesperson
sells either more than $5,000 in sales or if the salesperson sells
more than 10,000 units? Here is the code:
Compound Comparisons with the Logical
Visual Basic supports three additional operators-And, Or, and
Not-that look more like commands than operators. And, Or,
and Not are called logical operators. Logical operators let you
combine two or more comparison tests into a single compound comparison.
Table 7.3 describes the logical operators, which work just like
their spoken counterparts.
Table 7.3. The logical operators.
Operator Usage
If (A > B) And
(C < D)
Produces True if both sides of the And are true. Therefore, A must
be greater than B and C must be less than D. Otherwise, the
expression produces a false result.
If (A > B) Or
(C < D)
Produces True if either side of the Or is true. Therefore, A must be
greater than B or C must be less than D. If both sides of the Or are
false, the entire expression produces a false result.
If Not(strAns Produces the opposite true or false result. Therefore, if strAns holds
= "Yes")
"Yes", the Not turns the true result to false.
As you can see from Table 7.3, the And and Or logical operators
let you combine more than one comparison test in a single If
statement. The Not negates a comparison test. You can often
turn a Not condition around. Not can produce difficult
comparison tests, and you should use it cautiously. The last If
in Table 7.3, for instance, could easily be changed to If (strAns
<> “Yes”) to eliminate the Not.
Your code often must perform an assignment, print a message,
or display a label if two or more conditions are true. The logical
operators make the combined condition easy to code. Suppose
that you want to reward the salesperson if sales total more than
$5,000 and if the salesperson sells more than 10,000 units of a
particular product. Without And, you have to embed an If
statement in the body of another If statement like this:
If (sngSales > 5000.00) Then
If (intUnitsSold > 10000) Then
sngBonus = 50.00
End I
End If
Here is the same code rewritten as a single If. It is easier to read
and to change later if you need to update the program:
If (sngSales > 5000.00) Or (intUnitsSold > 10000) Then
sngBonus = 50.00
End If
Listing 7.2 contains an If-Else that tests data from two
divisions of a company and calculates values from the data.
E.g. Calculating sales figures for a companys divisions.
If (intDivNum = 3) Or (intDivNum = 4) Then
curDivTotal = curDivSales3 + curDivSales4
curGrandDivCosts = (curDivCost3 * 1.2) + (curDivCost4 *
curDivTotal = curDivSales1 + curDivSales2
curGrandDivCosts = (curDivCost1 * 1.1) + (curDivCost5 *
End If
If intDivNum contains either a 3 or a 4, the user is requesting
figures for the East Coast, and the code in the first If branch
executes to produce an East Coast pair of values. If
intDivNum does not contain a 3 or a 4, the program assumes
that intDivNum contains a 1 or a 2, and the West Coast pair of
values is calculated in the Else portion.
TIP: Notice how easy it is to spot the variable’s data type in
code that names variables with a data type prefix such as cur (for
currency) and sng (for single-precision). Use data type prefixes in
all your variable names. Although you must type a little extra,
your program code will be much clearer.
Multiple Choice with Select Case
If is great for data comparisons in cases where one or two
comparison tests must be made. When you must test against
more than two conditions, however, If becomes difficult to
maintain. The logical operators help in only certain kinds of
conditions. At other times, you must nest several If-Else
statements inside one other.
Consider the If statement shown in Listing 7.3. Although the
logic of the If statement is simple, the coding is extremely
difficult to follow.
E.g Nested If-Else statements get complex quickly.
If (intAge = 5) Then
lblTitle.Caption = “Kindergarten”
If (intAge = 6) Then
lblTitle.Caption = “1st Grade”
If (intAge = 7) Then
lblTitle.Caption = “2nd Grade”
If (intAge = 8) Then
lblTitle.Caption = “3rd Grade”
If (intAge = 9) Then
lblTitle.Caption = “4th Grade”
If (intAge = 10) Then
lblTitle.Caption = “5th Grade”
If (intAge = 11) Then
lblTitle.Caption = “6th Grade”
lblTitle.Caption = “Advanced”
The format of Select Case makes the statement look as difficult
as a complex nested If-Else, but you will soon see that Select
Case statements are actually easier to code and to maintain than
their If-Else counterparts.
Expression can be any Visual Basic expression-such as a
calculation, a string value, or a numeric value-provided that it
results in an integer or a string value. Each value must be an
integer or a string value that matches Expression’s data type.
The Select Case statement is useful when you must make several
choices based on data values. Select Case can have two or more
Case value sections. The code that executes depends on which
value matches Expression. If none of the values matches
Expression, the Case Else body of code executes if you code
the Case Else. Otherwise, nothing happens and control
continues with the statement that follows End Select.
WARNING: Don’t use Select Case when a simple If or If-Else
will suffice. Test logic is often so straightforward that a Select
Case would be overkill and even less clear than an If. Unless you
need to compare against more than a couple values, stick with
the If and If-Else statements because of their simplicity.
The fastest way to learn Select Case is to see an example of it.
Listing 7.4 contains a Select Case version of the child grade
assignments shown in Listing 7.3. Select Case organizes the
multiple-choice selections into a more manageable format.
E.g Using Select Case to simplify complex nested If-Else
End If
End If
End If
End If
End If
End If
End If
Select Case intAge
Case 5: lblTitle.Caption = “Kindergarten”
Case 6: lblTitle.Caption = “1st Grade”
Case 7: lblTitle.Caption = “2nd Grade”
Case 8: lblTitle.Caption = “3rd Grade”
Case 9: lblTitle.Caption = “4th Grade”
Case 10: lblTitle.Caption = “5th Grade”
Visual Basic supports a statement, called Select Case, that
handles such multiple-choice conditions better than If-Else.
Here is the format of the Select Case statement:
Select Case Expression
Case value
One or more Visual Basic statements
Case value
One or more Visual Basic statements
[Case value
One or more Visual Basic statements]
[Case Else
One or more Visual Basic statements]
End Select
Select Case is a good substitute for long, nested If-Else
conditions when several choices are possible. You set up your
Visual Basic program to execute one set of Visual Basic
statements from a list of statements inside Select Case.
Case 11: lblTitle.Caption = “6th Grade”
Case Else: lblTitle.Caption = “Advanced”
End Select
TIP: Use Select Case instead of embedded If-Else because, as
you can see, Select Case keeps the code much simpler and easier
to maintain.
Here’s how the Select Case works: If the intAge variable holds
the value 5, the label is assigned “Kindergarten” in the second
line. If the intAge variable holds the value 6, the label is
assigned “1st Grade” in the third line. The logic continues
through the Case 11: statement. If intAge holds a value that
does not fall within the range of 5 through 11, the final Case
Else assigns “Advanced” to the label.
The body of each Case can consist of more than one statement,
just as the body of an If or If-Else can consist of more than
one statement. Visual Basic executes all the statements for any
given Case match until the next Case is reached. Once Visual
Basic executes a matching Case value, it skips the remaining Case
statements and continues with the code that follows the End
Select statement.
Notice the colons after each Case value statement in Listing 7.4.
The colons are optional, but they do help separate the case
being tested from its code that executes.
TIP: You can combine the extended formats of Select Case
with the standard Select Case so that two or more kinds of Case
formats appear within the same Select Case statement.
Study Listing 7.5 to learn how to combine different Select Case
statements to test for various values.
NOTE: Programmers often trigger the execution of complete
procedures, such as event procedures, from within a Case
statement. As you will learn in Lesson 13, “Modular Programming,” instead of putting several statements in the body of an
If-Else or a Case, you can execute a procedure that contains all
the statements that execute when a given condition is true.
E.g. Using Select Case to simplify complex nested If-Else
Two Additional Select Case Formats
The two additional formats differ only slightly from the
standard Select Case that you learned about in the previous
section. They enable you to extend the power of Select Case so
that Visual Basic can make Case matches on both comparison
tests and on ranges of values. Here is the first additional
Select Case Expression
Case Is Relation:
One or more Visual Basic statements
Case Is Relation:
One or more Visual Basic statements
[Case Is Relation:
One or more Visual Basic statements]
[Case Else:
One or more Visual Basic statements]
End Select
Relation can be whatever comparison test you want to perform
against Expression at the top of the Select Case. The standard
Select Case statement, discussed in the previous section,
compared the Expression value against an exact Case match.
When you use the comparison Is Select Case option, each Case
can be matched on a comparison test.
Here is the format of the second extra Select Case format:
Select Case Expression
Case expr1 To expr2:
One or more Visual Basic statements
Case expr1 To expr2:
One or more Visual Basic statements
[Case expr1 To expr2:
One or more Visual Basic statements]
[Case Else:
One or more Visual Basic statements]
End Select
The Case lines require a range, such as 4 To 6. The To Select Case
option enables you to match against a range instead of a
relation or an exact match.
Rem to the label on the form. The code checks
Rem The following Select Case to End Select code
Rem assigns a student’s grade and school name
Rem to make sure that the student is not too
Rem young to be going to school.
Select Case intAge
‘ Check for too young...
Case Is <5: lblTitle.Text = “Too young”
‘ Five-year olds are next assigned
Case 5: lblTitle.Text = “Kindergarten”
‘ Six to eleven...
Case 6 To 11: lblTitle.Text = “Elementary”
lblSchool.Text = “Lincoln”
‘ Twelve to fifteen...
Case 12 To 15: lblTitle.Text = “Intermediate”
lblSchool.Text = “Washington”
‘ Sixteen to eighteen
Case 16 To 18: lblTitle.Text = “High School”
lblSchool.Text = “Betsy Ross”
‘ Everyone else must go to college
Case Else: lblTitle.Text = “College”
lblSchool.Text = “University”
End Select
If the age is less than 5, the title label becomes Too young, and
the school name remains blank. If the age is exactly 5 (intAge is
obviously an integer value), the title gets Kindergarten, and the
school name still remains blank. Only if the child is 5 or older
do both the title and school name get initialized.
If you were to rewrite this code using embedded If-Else logic,
the code would become a nightmare. The Select Case’s range
testing, such as Case 16 to 18, saves a tremendous amount of
If-Else logic.
In this lesson you have learned how to write Visual Basic
programs that make decisions. Once your programs are able to
test data values against certain conditions, your programs can
begin to make execution decisions and perform smarter
calculations. Visual Basic offers several forms of the If and the
Select Case statements to make comparisons. The comparison
operators, especially when combined with the logical operators,
produce advanced compound conditions.
The next lesson explains how to write looping statements so
that your programs can repeat logic as often as needed.
9. What role do code blocks play in Select Case statements?
10. What is wrong with this If statement?
If (intA < 1) And (intC >= 8) Then
lblDraft.Caption = “Overdrawn”
lblDraft.Caption = “Underdrawn”
End Else
Q Which testing statement is better: If, If-Else, or Select
A No testing statement is better than another in all situations.
The If statement is the fundamental building block for testing
data, and If is extremely common in most applications. When
you need the application to execute one block of code or
another, depending on the result of an If test, use If-Else. If
you need to embed several If-Else statements together because
you’ve got to test for multiple comparisons, the Select Case
almost always makes a better comparison statement than IfElse. You would not, however, save effort or program clarity if
you used Select Case when a simple If-Else would do. The
bottom line is that your application determines the best
statement to use at any one time.
Q Why is the Not operator considered so bad?
A Not is not considered bad, really, but the negative logic that
Not produces often makes for confusing logic. Some logic is
best performed with Not, but you can almost always turn the
Not logic into positive and simpler logic by reversing the
comparison being done.
The quiz questions and exercises are provided for your further
understanding. See Appendix C, “Answers,” for answers.
1. How do comparison operators differ from mathematical
2. What role does the ASCII table play in comparison logic?
3. Which of the following produce true and which produce false
a. 25 <= 25
b. “a” >= “B”
c. 0 < -1
d. 234.32 > 234.321
4. When do you code the Else portion of an If statement?
5. True or false: The End If statement is not needed for oneline If statements.
6. Which statement replaces nested If-Else logic?
7. Which Case option checks for a range of values?
8. What happens if every Case fails and there is no Case Else
1. Rewrite the following If to eliminate the Not and to clarify
the code:
If Not(X < 10) Or Not(Y >= 20) Then
Learning Objectives
What A Loop Is
How You Code A Do Loop
Termination Of Loop
How To Find Which Loop Is Best
This lesson’s lesson explains how to write programs that
contain looping logic. A loop is a set of program instructions
that execute repeatedly. Your programming preferences and
application dictate how many times the loop must repeat.
Loops play important roles in programs because you’ll need to
repeat sections of a program to process multiple data values.
For example, you may need to calculate a total of past due
charges for all past due customers. A loop can read each
customer’s past-due charge and add that amount to the running
The Do While Loops
Visual Basic supports several versions of the Do statement.
The Do While loop is perhaps the most common looping
statement that you’ll put in Visual Basic programs. Do While
works with comparison expressions just as the If statement
does. Therefore, the six comparison operators that you learned
about in the previous lesson work as expected here. Rather than
control the one-time execution of a single block of code,
however, the comparison expression controls the looping
Like the If statement that ends with an End If statement, a
loop will always be a multiline statement that includes an
obvious beginning and ending of the loop. Here is the format
of the Do While loop:
Do While (comparison test)
Block of one or more Visual Basic statements
The block of code continues looping as long as comparison test
is true. Whether you insert one or several lines of code for the
block doesn’t matter. It’s vital, however, that the block of code
somehow change a variable used in comparison test. The block
of code keeps repeating as long as the Do While loop’s
comparison test continues to stay true. Eventually, comparison
test must become false or your program will enter an infinite
loop and the user will have to break the program’s execution
through an inelegant means, such as pressing the Ctrl+Break
key combination.
New Term: An infinite loop is a loop that never terminates.
WARNING: Guard against infinite loops and always make
sure your loops can terminate properly. Even if you provide an
Exit command button or a File|Exit menu option in your
application, the program will often ignore the user’s exit
command if the program enters an infinite loop.
The Do While loop continues executing a block of Visual Basic
statements as long as comparison test is true. As soon as
comparison test becomes false, the loop terminates.
The Loops Termination
As long as comparison test is true, the block of code in the
body of the loop continues executing. When comparison test
becomes false, the loop terminates. After the loop terminates,
Visual Basic begins program execution at the statement
following the Loop statement because Loop signals the end of
the loop. As soon as Do While’s comparison test becomes false,
the loop terminates and doesn’t execute even one more time.
The Do While’s comparison test appears at the top of the loop.
Therefore, if comparison test is false the first time the loop
begins, the body of the loop will never execute.
Listing 8.1 contains a section of an event procedure that
contains a Do While loop that asks the user for an age. If the
user enters an age less than 10 or more than 99, the program
beeps at the error and displays another input box asking for the
age. The program continues looping, asking for the age, as long
as the user enters an age that’s out of range.
E.g The Do While loop executes as long as comparison test is
Dim strAge As String
Dim intAge As Integer
Dim intPress As Integer
‘ Get the age in a string variable
strAge = InputBox(“How old are you?”, “Age Ask”)
‘ Check for the Cancel command button
If (strAge = “”) Then
End ‘ Terminates the application
End If
‘ Cancel was not pressed, so convert Age to integer
‘ The Val() function converts strings to integers
intAge = Val(strAge)
‘ Loop if the age is not in the correct range
Do While ((intAge < 10) Or (intAge > 99))
‘ The user’s age is out of range
intPress = MsgBox(“Your age must be between “ & _
“10 and 99”, vbExclamation, “Error!”)
strAge = InputBox(“How old are you?”, “Age Ask”)
‘ Check for the Cancel command button
If (strAge = “”) Then
End ‘ Terminate the program
End If
intAge = Val(strAge
Figure 8.1 shows the message box error Listing 8.1 displays if
the user enters an age value that’s less than 10 or more than 99.
Listing 8.1 does nothing with MsgBox()’s return value stored in
intPress. The user simply presses Enter to close the message
box so a check for intPress’s value would not help this particular
section of code.
NOTE: Listing 8.1 uses the built-in Val() function. Val() accepts
a string argument and converts that string to a number
(assuming that the string holds the correct digits for a number).
The InputBox() function returns a string so the value the user
enters into the input box must convert to an integer before you
store the value in the integer variable named intAge.
The code contains some redundancy. For example, two lines
contain almost the same InputBox() function, and the same
check for a Cancel command button press appears twice in the
program. There are other looping statements that you’ll learn
about later in this lesson; those statements can help simplify
this code by removing some of the redundancy.
Perhaps the most important thing to note about the Do While
loop in Listing 8.1 is that the body of the loop provides a way
for comparison test to terminate. The code contains an intAge
variable that the body of the loop reassigns each time the loop’s
block of code executes. Therefore, assuming that the user enters
a different value for the age, the loop will test against a different
set of comparison values, the comparison test will fail (which
would mean that the age is inside the range), and the program
will stop looping. If the loop body did nothing with the
comparison test variable, the loop would continue forever.
The Do Until Loop
Visual Basic supports several kinds of loops, and you can use
the one that best matches your application’s requirements.
Whereas the Do While loop continues executing the body of
the loop as long as the comparison test is true, the Do Until
loop executes the body of the loop as long as the comparison
test is false. The program’s logic at the time of the loop
determines which kind of loop works best in a given situation.
Do Until works almost exactly like the Do While loop except
that the Do Until loop continues executing the body of the
loop until the comparison test is true. Like the Do While, the
Do Until is a multiline looping statement that can execute a
block of code that’s one or more lines long.
You can use the Do While or the Do Until for almost any loop.
Listing 8.2 contains the age-checking event procedure that
contains a Do Until loop. The loop ensures that the age falls
between two values. As you can see, comparison test for the Do
Until is the opposite of that used in Listing 8.1’s Do While
Which Loop is best?
Use the loop that makes for the cleanest and clearest comparison test. Sometimes, the logic makes the Do While clearer,
whereas other loops seem to work better when you set them up
with Do Until. Do Until continues executing a block of Visual
Basic statements as long as comparison test is false. As soon as
comparison test becomes true (the loop is said to Do a loop
until the condition becomes false), the loop terminates and the
program continues on the line that follows the closing loop
E.g The Do Until loops until comparison test becomes true.
Dim strAge As String
Dim intAge As Integer
Dim intPress As Integer
‘ Get the age in a string variable
strAge = InputBox(“How old are you?”, “Age Ask”)
‘ Check for the Cancel command button
If (strAge = “”) Then
End ‘ Terminate the program
End If
‘ Cancel was not pressed, so convert Age to integer
intAge = Val(strAge)
‘ Loop if the age is not in the correct range
Do Until ((intAge >= 10) And (intAge <= 99))
‘ The user’s age is out of range
intPress = MsgBox(“Your age must be “ & _
“between 10 and 99”, vbExclamation, “Error!”)
strAge = InputBox(“How old are you?”, “Age Ask”)
‘ Check for the Cancel command button
If (strAge = “”) Then
End ‘ Terminate the program
End If
intAge = Val(strAge)
Here is the format of the Do Until:
Do Until (comparison test)
The 16th line is the only line that marks the difference between
Listing 8.1 and Listing 8.2. The age must now fall within the
valid range for the loop to terminate.
Block of one or more Visual Basic statements
TIP: Remember that the comparison test must be false for the
loop to continue.
NOTE: There is really no technical advantage to using Do
While or Do Until. Use whichever one seems to flow the best
for any given application.
The Other Do Loops
Another pair of Do loops works almost exactly like the two
previous loops. Do-Loop While and Do-Loop Until look very
much like their counterparts that you learned earlier. But these
new loop formats check their comparison tests at the bottom
of the loop rather than at the top.
If a loop begins with a single Do statement, the loop ends with
either Loop While or Loop Until. Here is the format of DoLoop While:
Block of one or more Visual Basic statements
Loop Until (comparison test)
TIP: The hyphen in Do-Loop While serves to remind you that
the body of the loop comes before the Loop While statement.
The hyphen in the Do-Loop Until performs the same purpose.
Some books use ellipses in place of the hyphen, so you may see
the statement written as Do...Loop Until.
That Do looks lonely by itself, doesn’t it? The purpose of the
Do is to signal the beginning of the loop. The loop continues
until the Loop Until statement. The comparison test appears at
the bottom of the loop if you use the Do-Loop While loop
statement. The body of the loop always executes at least once.
The body of the loop executes more than once as long as the
comparison test stays true. There is a corresponding Do-Loop
Until statement that checks for a false condition at the bottom
of the loop’s body.
Notice that the Do-Loop While loop’s comparison test appears
at the bottom of the loop instead of at the top of the loop.
You’ll use the Do-Loop While loop when you want the body
of the loop to execute at least one time. Often, by placing
comparison test at the bottom of the loop, you can eliminate
redundant code that otherwise might be required if you used
Do While.
To complete the loop statements, Visual Basic also supports a
Do-Loop Until statement. Like the Do-Loop While, the DoLoop Until statement tests comparison test at the bottom of
the loop. Therefore, the body of the loop executes at least once
no matter what comparison test turns out to be. The loop
continues as long as the comparison test result stays false.
Listing 8.3 contains the age-checking event procedure that’s
much shorter than the previous versions. comparison test
appears at the bottom of the loop, so the extra InputBox()
function call is not needed.
Listing 8.3. Using the Do-Loop While to check the comparison
at the bottom of the loop.
Dim strAge As String
Dim intAge As Integer
Dim intPress As Integer
strAge = InputBox(“How old are you?”, “Age Ask”)
‘ Check for the Cancel command button
If (strAge = “”) Then
End ‘ Terminate program
End If
intAge = Val(strAge)
If ((intAge < 10) Or (intAge > 99)) Then
‘ The user’s age is out of range
intPress = MsgBox(“Your age must be between “ & _
“10 and 99”, vbExclamation, “Error!”)
End If
Loop While ((intAge < 10) Or (intAge > 99))
The loop begins almost immediately. The loop’s body will
always execute at least once, so InputBox() appears right inside
the loop. By placing the InputBox() function inside the loop,
you eliminate the need to put this function in the code twice
(once before the loop and once inside the loop, as was necessary
using the previous looping statements in Listings 8.1 and 8.2).
NOTE: In this simple application of the looping statements
that you’ve seen here, the Do-Loop While loop required less
code than the Do While and Do Until loops. By changing the
Do-Loop While’s comparison test, a Do Until would also
work. These last two loops will not, in every case, produce less
code as they do here. The logic of the application determines
which loop works best.
Learning Objectives
intSum = intSum + 1
When Visual Basic executes the Next intNumber statement,
Visual Basic returns to the top of the loop (the For statement),
adds the Step value 1 to intNumber, and continues the loop
again using 2 as intNumber in the loop’s body. Therefore, the
second time through the loop, the third line becomes this:
How To Use For Loop
Why Several Do Loop Formats Exist
When To Use For
The For Loop
intSum = intSum + 2
The For loop (sometimes called the For-Next loop) also creates
a loop. Unlike the Do loops, however, the For loop repeats for a
specified number of times. The format of the For loop looks a
little more daunting than that of the Do loops, but after you
master the format, you’ll have little trouble implementing For
loops when your code needs to repeat a section of code for a
specified number of times.
The loop continues, adding the default Step value 1 to
intNumber each time the loop executes. When intNumber
becomes 10 (the format’s EndVal), the loop finishes and the
statement following the Next statement continues.
There isn’t one correct loop to use in all situations. The For
statement provides the mechanism for the fifth Visual Basic
loop block that you’ll learn. A For loop always begins with the
For statement and ends with the Next statement. Here is the
format of the For loop:
For CounterVar = StartVal To EndVal [Step IncrementVal]
Block of one or more
Visual Basic statements
Next CounterVar
A simple example will help demonstrate how the For loop
works. The loop in Listing 8.4 computes the total of the
numbers from 1 to 10.
TIP: Remember, the For loop terminates when the CounterVar
becomes larger than the EndVal. There’s an exception to this: If
you code a negative Step value, the loop terminates when the
CounterVar becomes smaller than the EndVal, as you’ll see a
little later in this section.
You don’t need a For statement to sum the values 1 through
10. You could code one long assignment statement like this:
intSum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
You could also code back-to-back assignment statements like
IntSum = IntSum + 1
IntSum = IntSum + 2
IntSum = IntSum + 3
IntSum = IntSum + 4
E.g Add the numbers from 1 to 10.
IntSum = IntSum + 5
intSum = 0
IntSum = IntSum + 6
For intNumber = 1 To 10
IntSum = IntSum + 7
intSum = intSum + intNumber
IntSum = IntSum + 8
Next intNumber intNumber is the CounterVar in the For’s
format. The CounterVar must be a variable and not a control or
a literal. 1 is the For loop’s StartVal. The StartVal can be either a
number, an expression, or a variable. 10 is the EndVal. EndVal
can be either a number, an expression, or a variable. There is no
Step specified here. In the For statement’s format, the Step
IncrementVal is optional (as you can tell from the format’s
square brackets). If you don’t specify a Step value, Visual Basic
assumes a Step value of 1. Therefore, both of the following
For statements do exactly the same thing:
IntSum = IntSum + 9
For intNumber = 1 To 10
For intNumber = 1 To 100 ‘ Only this line changes
For intNumber = 1 To 10 Step 1
Listing 8.4’s summing For loop initially assigns to the
CounterVar the StartVal in the second line. Therefore,
intNumber is assigned 1 at the top of the loop. Visual Basic
then executes the body of the loop using the value 1 for
intNumber. With intNumber being equal to 1, the third line
works as follows the first time through the loop:
IntSum = IntSum + 10
Neither of these approaches is extremely difficult, but what if
you needed to add together the first 100 integer numbers? The
previous assignments could become tedious indeed, but for the
For loop to add the first 100 integers is just as easy to code as
for the first 10 integers, as Listing 8.5 demonstrates.
E.g Add the numbers from 1 to 100.
IntSum = 0
IntSum = IntSum + Number
Next intNumber
The following loop displays five message boxes:
For intCtr = 1 To 20 Step 4
intPress = MsgBox(“This is a message box”)
Next intCtr
The loop counts up from 1 to 20 by 4s, putting each count into
the counter variable named intCtr and printing a message box
each time. The Step value changes how Visual Basic updates the
CounterVar each time the loop iterates.
New Term: An iteration is one complete cycle through a loop.
If you specify a negative Step value, Visual Basic counts down.
The following loop rings the PC’s speaker five times:
For intCtr = 5 To 1 Step -1
Next intCtr
NOTE: The Beep statement simply buzzes the speaker on your
WARNING: If you specify a negative Step value, EndVal must
be less than StartVal or Visual Basic will execute the loop only
Listing 8.6 contains a fairly comprehensive For loop that
computes compound interest for an initial investment of
$1,000.00. The code appears inside the Click event procedure for
a command button named cmdIntr. With compound interest,
each year the amount of money invested, including interest
earned so far, compounds to build more money. Each time
period, normally a year, means that another year’s interest must
be added to the value of the investment. A For loop is perfect
for calculating interest. Listing 8.6 uses five compound cycles.
Listing 8.6. Using a For loop to calculate compound interest.
Sub cmdIntr_Click ()
‘ Use a For loop to calculate a final total
‘ investment using compound interest.
‘ intNum is a loop control variable
‘ sngIRate is the annual interest rate
‘ intTerm is the Number of years in the investment
‘ curInitInv is the investor’s initial investment
‘ sngInterest is the total interest paid
Dim sngIRate As Single, sngInterest As Single
Dim intTerm As Integer, intNum As Integer
Dim curInitInv As Currency
sngIRate = .08
intTerm = 5
‘ Watch out... The Code window might convert the
‘ following literals, 1000.00 and 1.0, to double‘ precision literals with the suffix # to ensure
‘ accuracy.
curInitInv = 1000.00
sngInterest = 1.0 ‘ Begin at one for first compound
‘ Use loop to calculate total compound amount
For intNum = 1 To intTerm
sngInterest = sngInterest * (1 + sngIRate)
Next intNum
‘ Now we have total interest,
‘ calculate the total investment
‘ at the end of N years
lblFinalInv.Caption = curInitInv * sngInterest
End Sub
This analysis focuses on the loop and not the interest calculation. The most important thing that you can do at this point is
to master the For looping statement. The code’s remarks
contain variable descriptions so that anyone looking at the code
or changing the code later will know what the variables are for.
After the program defines all the variables, the variables are
initialized with start-up values. If you use this event procedure,
be sure to add a label named lblFinalInv to a form and add a
command button named cmdInt to the form. The middle lines
will seem to give you trouble as you type them unless you
remember the description you got in Lesson 5, “Putting Code
into Visual Basic,” of data suffix characters. Visual Basic uses
the pound sign (#), to indicate double-precision values, and
Visual Basic will assume that 1000.00 is a double-precision value
(I don’t know why) and will convert the 1000.00 to 1000# right
after you press Enter at the end of the line! In addition, Visual
Basic converts the 1.0 to 1# on the next line. Don’t worry about
Visual Basic’s pickiness here.
The most important part of this program is the For loop that
iterates through each interest rate period (five of them) and
compounds the interest on top of the investment to date.
Again, don’t let the financial part worry you. The calculation is
less important than understanding the looping process. After
the loop finishes, the event procedure places the compounded
investment in the label’s Caption property.
You Can Terminate Loops Early
Sometimes, you’ll be processing user input or several data
values using looping statements, and an exception occurs in the
data that requires an immediate termination of the loop. For
example, you may be collecting sales values for a company’s 10
divisions inside a For loop that iterates 10 times. However, the
user can enter 0 for a division’s sales value, indicating that there
is no sales data for that division. Rather than complete the loop,
your program might need to quit the loop at that point because
the full divisional report information can’t be gathered at the
time. The Exit Do and the Exit For statements automatically
terminate loops. No matter what the Do loop’s comparison
test results in, or no matter how many more iterations are left in
a For loop, when Visual Basic encounters an Exit Do or Exit
For statement, Visual Basic immediately quits the loop and
sends execution down to the statement following the loop.
Typically, an If statement triggers one of the Exit statements
like this:
For intDivisions = 1 To 10 ‘ Code to get a sales value If
(cngSales <= 0.0) Then
Exit For
‘ Quit the loop early
End If ‘ Process the rest of the code Next intDivisions
The If ensures that the Exit For executes only under one
specific condition (a missing sales value). Without that specific
condition triggering the Exit For, the loop cycles normally.
Visual Basic also supports the Exit Sub statement that terminates a procedure early.
In this lesson you have learned how you can add loops to your
programs. Computers do not get bored. Your program will
execute the same series of instructions over and over until you
terminate the loop. Visual Basic supports several forms of
looping statements. The Do and For loops provide you with
the power to write any kind of looping section your program
needs. The choice of loop you use is up to your style and
coding preference more than anything else.
10. True or false: The Exit statement exits the current
1. Write a program that contains a text box and a command
button. Put a label above the text box that tells the user to
type a number from 1 to 10 inside the text box. When the
user clicks the command button, check the text box for a
valid number and issue an error message box if the number
is not inside the expected range. If the user entered a valid
number, beep the computer’s speaker the number of times
entered in the text box using a For loop.
The next lesson moves away from the theory you’ve been
getting in the last few lessons to get you back to the keyboard
and freshen up your application design and construction skills.
2. Rewrite Listing 8.3 so that the error message box that you
display tells the user that the age entered is too low if the age
is below 10 or that the age entered is too high if the age is
more than 99.
Q How can I guard against infinite loops?
A All loops continue as long as a condition is true or as long as
a condition is false. Therefore, somewhere inside the loop’s
body your code must modify the condition used for the loop.
The For loop’s control variable must reach its ending value or
something inside the Do loop’s condition must change inside
the loop’s body. If the body of a loop does not change the
controlling condition, the loop will execute forever.
Q How do I terminate an infinite loop?
A As the lesson states, you must press Ctrl+Break to terminate
an infinite loop. Until this lesson, you had not heard of
Ctrl+Break, but the keystroke has been the program-stopping
keystroke for many versions of the BASIC language through
the years. In addition, you can click on VB’s End toolbar button
or select Run | End from the menu.
The quiz questions and exercises are provided for your further
understanding. See Appendix C, “Answers,” for answers.
1. Why might your program need a loop?
2. How many forms of Do are there?
3. True or false: The Do-Loop While and the Do While are
identical in every respect.
4. What is the difference between Do-Loop While and DoLoop Until?
5. Which loop checks its condition at the top of the loop: Do
Until or Do-Loop Until?
6. Why do programmers often use the Val() function on control
values and InputBox() returns?
7. True or false: A For loop can count down.?
8. How many times does the following loop iterate?
intI = 10
do While intI >= 1
intI = intI - 1
9. What default Step value does Visual Basic use if you don’t
supply a Step value?
Learning Objectives
Where to place the initial form
What a control array is
How default properties speed development
This lesson takes a short break from the theory you’ve seen for
the past few lessons. In this lesson you will put some of the
code you’ve seen into a fairly large application and run the
application to work with the results. You’ve already learned a lot
about Visual Basic. Nevertheless, as this lesson illustrates,
you’ve got a lot of exciting things yet to learn over the next few
This lesson’s primary goal is to refresh your Visual Basic
knowledge once again by putting together the big picture. In
this lesson you’ll build a simple but complete application just
to get practice working with both code and the controls you’ve
learned so far. Once you refresh your application-building skills
in this lesson, the next lesson teaches more controls from the
toolbox. The more controls you learn to use, the more
powerful your applications become.
The Interest Calculation Application
The previous lesson describes how to compute compound
interest using a For loop. You studied the code in the previous
lesson, and this lesson will build a simple application around
that interest calculation.
NOTE: In creating an application from scratch, this hour lets
you review the application, controls, form, and standard
modules. Therefore, when the next lesson begins to teach some
more advanced controls, you’ll be better prepared for them.
Perform these steps to create the interest calculating
1. Start a new project (select File|New Project). Double-click the
Standard EXE icon (the icon you’ll most often choose for
regular applications).
2. Change the form’s Name property to frmInterest. Change the
Caption property to Interest Calculation.
3. Change the form’s StartUpPosition property to 2CenterScreen. You’ve not seen the StartUpPosition property
yet. The StartUpPosition property determines the location of
the Form window when the user runs the program. Let
Visual Basic center the form on your user’s screen because
you don’t know the exact measurements of the screen that
your users will use. If you set StartUpPosition to 2CenterScreen, Visual Basic always places the form in the
middle of the screen no matter what the user’s screen size
and resolution are. (Use the WindowState property to open
the Form window in its maximized state if you want a fullscreen Form window when the application starts.)
NOTE: The StartUpPosition property makes the Form Layout
window unnecessary in most cases. StartUpPosition gives you
much more accurate placement of the form than the Form
Layout window.
4. You’ve now got to add the labels and text boxes. The form’s
title label is simple to generate. Place a label on the form and
set the following properties: Name: lblTitle, Alignment: 2Center, BorderStyle: 1-Fixed Single, Caption: Interest
Calculator, Font: Bold 18, Height: 495, Left: 2090, Top: 240,
and Width: 3855.
5. You now must set up a series of three label/text box pairs.
Notice that Figure 9.1’s labels all have hotkeys. Although a
label cannot accept the focus, pressing Alt+hotkey sends the
focus to the control next in line, which will be the text box
next to the label (assuming that you place the text box right
after you place the corresponding label).
Set the interest rate label as follows: Name: lblRate,
Alignment: 1-RightJustify, Caption: &Interest rate (8 for
8%):, Font: Regular 14, Height: 375, Left: 2040, Top: 1080,
and Width: 2895. Set the interest rate text box as follows:
Name: txtRate, Alignment: 0-LeftJustify, Font: 10, Height:
375, Left: 5160, ToolTipText: Annual rate investment grows,
Top: 1080, and Width: 615. Blank out the Text property so
nothing appears in the text box at startup. Notice that you
are adding ToolTipText at the same time you add the control
that the user interacts with. Design time is the best time to
add ToolTipText because the control’s meaning is clearest in
your mind then.
Using Control Arrays
This is a great time to introduce a new concept called control
arrays. A control array is a group of more than one control of
the same control type. You will better understand control arrays
after you learn about data arrays in Hour 10, “List Boxes and
Data Lists,” but the interest rate application makes this a great
project to introduce them.
Notice that the interest calculator’s Term and Investment
Amount labels and text boxes all look similar to the Interest
rate label and text box you just placed on the form. All the font
information and Height properties are the same. Therefore,
while you could enter the remaining labels and text boxes, you
can utilize the Windows Clipboard to make the job go faster.
Highlight both the existing Interest rate label and text box. You
can select multiple controls by pressing the Ctrl key while you
click on each control, or you can lasso the controls by dragging a
rectangle around the two controls. When you select both
controls, sizing handles appear around them.
Select Edit|Copy to copy the selected controls to the Windows
Clipboard. Now select Edit|Paste, and Visual Basic pops up a
warning dialog box that reads You already have a control named
‘txtRate’. Do you want to create a control array?
A control array is a set of multiple controls that have the same
name. You distinguish between the controls inside the array
with an index value. For this particular example, you should not
create a control array (you will create one in the next lesson).
Therefore, answer No to the dialog box and again answer No
when Visual Basic asks you about creating a control array for the
text box.
NOTE: Visual Basic saw that you wanted to paste two controls
on the form that already had controls with those same names.
Visual Basic cannot replace existing controls when you paste
new ones with the same name, so Visual Basic guessed (in this
case incorrectly) that you wanted to add a control array named
txtRate. When you refused the control array, Visual Basic made
up its own name for the new label (Label1) and the new text
box (Text1).
Move the pasted label and text box to their correct positions
under the first pair and set these properties for the label: Name:
lblTerm, Caption: &Term (annual periods):, Left: 2040, Top:
1800, and Width: 2895. The Height and Font properties are
already correct because you borrowed these properties from the
control you originally copied from. Set these properties for the
text box: Name: txtTerm, Left: 5160, ToolTipText: Number of
periods, Top: 1800, and Width: 615. As you can see, you don’t
have to set as many properties when you paste from an existing
similar control.
New Term: Default properties are the properties Visual Basic
assumes if you omit the properties from a control inside the
Code window.
Click the form and select Edit|Paste once more (the Clipboard
still holds those first two controls you sent there), refuse the
control array, and set the following properties for the new label:
Name: lblInvest, Caption: I&nvestment Amount:, Left: 1920,
Top: 2520, and Width: 2895. Set the text box’s properties to
Name: txtInvest, Left: 5040, ToolTipText: Money you invested,
Top: 2520, and Width: 1215.
Finishing the Form
You can quickly finish the form now. While the label and text
box still reside on the Windows Clipboard, this would be a
good time to add the Ending Investment label and text box.
Select Edit | Paste once again and set the pasted label’s properties as follows: Name: lblEnding, Caption: Ending
Investment:, Left: 1800, Top: 4560, and Width: 2895. Set the
text box’s properties as follows: Name: txtEnding, Left: 4920,
Locked: True, TabStop: False (so the user cannot send the focus
to this text box), Top: 4560, ToolTipText: Compounded
Investment, and Width: 1455.
The new property you set just now is the Locked property.
When you lock a control, Visual Basic allows no user editing of
the control. Therefore, the code beneath the form can modify
the text box’s Text property but the user cannot. The final text
box will be a holding place for the calculated compound
investment amount, so the user should not be allowed to edit
the control even though it’s a Text Box control.
NOTE: You might wonder why the application uses a text box
and not a read-only control such as a label. The Label control
would work just as well and would not require a Locked
property setting because labels can never be changed by the user.
Nevertheless, the text box keeps a uniform appearance throughout the form, so we’re using a text box here.
Add a command button named cmdCompute, add the caption
&Compute Interest, and add a ToolTipText value of Click to
compute final investment. Place and size the command button
as follows: Height: 495, Left: 2640, Top: 3360, and Width: 2535.
Add a final command button named cmdExit to the lowerright corner with the E&xit Caption property.
NOTE: See, building an application can be tedious, but your
productivity is greater with Visual Basic than with virtually every
other application development system available. Although
you’ve seen most of this lesson’s concepts before, this is the
first lesson that truly ties things together by walking you
through the entire application-creation process.
Adding Code
Often, programmers run their applications as they build them
despite the fact that no code exists yet to make the application
do real work. You should be able to run your application now
to make sure that the labels and text boxes all look correct.
Check out the tooltip text to make sure you’ve entered the text
properly. Click the toolbar’s End button to stop the program so
that you can add the final code.
The code is going to borrow a bit from the interest calculation
routine you learned about in Hour 8, “Visual Basic Looping.”
You’ll have to modify the routine somewhat so the data comes
from the Text Box controls you’ve set up. You want the
calculation to take place when the user clicks the center command button, so add the following code to the command
button’s Click() event procedure. Double-click the Form
window’s Compute Interest command button to open the
cmdCompute_Click () event procedure to complete the code
that follows:
Private Sub cmdCompute_Click()
‘ Use a For loop to calculate a final total
‘ investment using compound interest.
‘ intNum is a loop control variable
‘ sngIRate is the annual interest rate
‘ intTerm is the number of years in the investment
‘ curInitInv is the investor’s initial investment
‘ sngInterest is the total interest paid
Dim sngIRate As Single, sngInterest As Single
Dim intTerm As Integer, intNum As Integer
Dim curInitInv As Currency
sngIRate = txtRate.Text / 100#
intTerm = txtTerm.Text
curInitInv = txtInvest.Text
sngInterest = 1# ‘ Begin at one for first compound
‘ Use loop to calculate total compound amount
For intNum = 1 To intTerm
sngInterest = sngInterest * (1 + sngIRate)
Next intNum
‘ Now we have total interest,
‘ calculate the total investment
The Unload statement lets you use a shortcut that looks like
Unload Me
Me is a special object that refers to the currently active form. Use
Unload Me when the application contains only a single form if
you don’t want to type the full form name. For a multiple-form
application, however, be sure to unload all the forms before
terminating the program.
Unload frmInterest
Finishing Touches
Run your application and enter some sample values. Figure 9.4
shows the application with some sample data entered for a fiveyear investmentif you invested $1,000 today at 11% interest, in
five years you will have approximately $1,685.
The application is not really complete and ready for distribution.
Although you’ve mastered the mechanics of this simple
application, more is needed to make the application professional. Obviously, the ending investment’s decimal place
precision is far too high.
You need to format the value shown in the Ending Investment
text box. When you format a value, you don’t change the value,
but you change the value’s look. Visual Basic includes a built-in
function called Format() that formats numeric and string values
so you can display such values as dollars and cents, area code
formats, or whatever formats you want to use. Although Hour
14, “Built-in Functions Save Time,” explains Format() in detail,
you can use the Format() function now to spruce up your
New Term: To format is to change the way a value appears to
the user.
At the end of the cmdCompute_Click() event procedure,
change the ending investment’s assignment to this:
txtEnding.Text = Format(curInitInv * sngInterest,
TIP: Some formats get lengthy, so programmers often declare a
string variable and assign the format to the variable. They then
use the variable inside the Format() function instead of using
the string literal for the format. If you use the same format in
several locations within the code, the variable means less typing
on your part, and if you ever change the format, you only have
to change the format in one place.
The Format() function’s basic format is this:
‘ at the end of N years
txtEnding.Text = curInitInv * sngInterest
End Sub
NOTE: This is basically the same code that you saw in the
previous lesson when studying For loops. This code does
include a few minor differences so that the application’s control
names properly initialize and receive values.
TIP: Visual Basic supports default properties for most
controls. The default property is the property Visual Basic uses
if you don’t explicitly specify a property. For example, if you use
a Text Box control in code and don’t type the Text property,
Visual Basic assumes you mean Text (as long as you don’t
specify a different property). Therefore, the first assignment in
the application is now sngIRate = txtRate.Text / 100#, but the
following statement is identical in every respect because Visual
Basic assumes that you are using the text box’s Text property:
sngIRate = txtRate / 100#.
You must also add the terminating code for the Exit command
button. Here’s a simple way the Code window lets you add new
1. Click the drop-down object list box (the left list box, directly
beneath the toolbar) and select cmdExit.
2. Select the event for which you want to add code in the right
drop-down list box whose tooltip reads Object. (The default
procedure listed for command buttons is Click, so in this
case you don’t need to select a different procedure.)
Add the following code for the command button’s event
Private Sub cmdExit_Click()
‘ Unload the form and terminate application
End Sub
Format(expression, strFormat)
The Unload Statement
Visual Basic changes the look of expression to match that of
the format string you supply. Therefore, the format string
“$###,##0.00” instructs Visual Basic to display the value with
a dollar sign, floating numbers with the # (if the number is less
than $100,000.00 the numbers will move left to touch the dollar
sign instead of leaving a gap for the missing digits), commas in
the amount if the amount is over $1,000, and a decimal point
with two decimal places showing. If the value happens to be
$0.00, the zeros ensure that the value prints, whereas if you
used a # in place of each 0, the # would show nothing if the
result were zero.
The Exit command button’s Click event procedure contains a
statement you’ve not seen until now. The Unload statement
unloads a form from memory. If the form to unload is
currently displayed, Visual Basic removes the form and returns
all of the form’s control values back to their design-time state.
In most cases the Unload statement is unnecessary, especially
when your application contains only a single form. If you add
multiple forms to the application, however, the user could have
closed one of the Form windows (by clicking the form’s
window close buttons), and the End statement could fail to
release that form’s resources properly.
Once you format the value and rerun the application with the
numbers used earlier, you’ll see a result that looks better.
1. Change this lesson’s application’s form properties so the user
cannot resize the form. Search through the form properties
until you find the property that will do this.
Learning Objectives
Dim sngIRate As Single, sngInterest As Single
Where and how to add external code modules
Dim intTerm As Integer, intNum As Integer
How to write your own functions
Dim curInitInv As Currency
A big problem still exists with the application if you plan to
distribute it to others. The problem is not in the logic or in the
calculation or in the form. The problem is the application’s lack
of error checking. If the user does not enter a value in one or
more of the text boxes, the calculation will not work properly.
Even worse, an error such as a divide by zero error could occur
and stop the running program. Mathematically, one cannot
divide by zero, and Visual Basic stops the program and issues a
runtime error message if a divide by zero occurs. Any time you
write an application that performs division, you should check to
make sure that you never divide by zero.
Therefore, you’ll need to add error checking to the application to
make sure the user enters positive values greater than 0 in each
of the text boxes before clicking the computational command
The error checking can be fairly simple. Convert the text box
values to numbers, and if any text box contains zero or less,
perform the following:
1. Tell the user about the problem with a message box.
2. When the user closes the message box, set the focus on the
control with the bad value so the user can more easily enter a
corrected value.
3. Test the controls again before any calculation is performed to
ensure that the problem is fixed.
Several approaches exist for handling this error. The
approach this lesson uses is slightly advanced, but it gives
you a chance to see an external standard module added to an
application (an external code module that is different from
the form module), and you’ll get a glimpse of the functionwriting instruction you’ll learn in Hour 13, “Modular
Programming.” You will actually create your own function
instead of using one of the built-in functions supplied with
Visual Basic.
‘ Error-checking
If ErrorCheck() = 1 Then
Exit Sub
End If
sngIRate = txtRate.Text / 100#
intTerm = txtTerm.Text
NOTE: The rest of the procedure is identical to the earlier
listing. You only need to add the four lines that follow the
variable declarations.
The ErrorCheck() is a procedure you’ll add that checks the form
for bad values. You will add this procedure in a separate
module, not at the bottom of the form module. Notice that
you use the ErrorCheck() procedure just as you use built-in
functions: You call the function with an empty argument list
(no arguments are necessary), and the function returns a value.
If that value is 1, the form contains an error, so you use the
Exit Sub statement to terminate the event procedure and return
the user to the form. (The previous lesson described other
forms of the Exit statement such as Exit For.) If no error
exists, the ErrorCheck() procedure will not return a 1, and the
processing continues as normal.
New Term: A function procedure is a procedure that you write
that accepts zero or more arguments and returns a single value.
New Term: A subroutine procedure is a procedure that you
write that accepts zero or more arguments but does not return a
Private Sub cmdCompute_Click()
You must now add the ErrorCheck() procedure. Unlike the
event procedures you’ve been writing until now, the
ErrorCheck() procedure is a function procedure and not a
subroutine procedure. A function procedure always returns a
value, whereas a subroutine procedure never returns a value.
(Again, you’ll learn more about function and subroutine
procedures in Hour 13.)
‘ Use a For loop to calculate a final total
To add an extra module to your project, perform these steps:
‘ investment using compound interest.
1. Select Project | Add Module to add a new module (that you
can view in a Code window) to the project. You could also
right-click over your Project window and add the module
from the pop-up menu.
First, assign the hook to the other function in your
cmdCompute_Click() event procedure like this:
‘ intNum is a loop control variable
‘ sngIRate is the annual interest rate
‘ intTerm is the number of years in the investment
‘ curInitInv is the investor’s initial investment
‘ sngInterest is the total interest paid
2. Click the Module icon that appears in the Add Module dialog
box. Visual Basic adds a new module with the default name
Module1 (and the filename Module1.BAS). Project window
shows the new module in your project. Your Code window
will now display a blank module where you can type the
module’s code.
3. Maneuver between modules and the form by double-clicking
the Project window object you want to work with. For now,
however, stay inside the new module.
Type the following function procedure inside the new module’s
Code window:
Public Function ErrorCheck() As Integer
‘ Error-checking for the form
If Val(frmInterest.txtRate.Text) <= 0 Then
intPress = MsgBox(“Enter a value for the rate”, vbCritical)
ErrorCheck = 1
Exit Function
End If
If Val(frmInterest.txtTerm.Text) <= 0 Then
intPress = MsgBox(“Enter a value for the term”, vbCritical)
ErrorCheck = 1
Exit Function
End If
If Val(frmInterest.txtInvest.Text) <= 0 Then
intPress = MsgBox(“Enter a value for the investment”,
Once a text box is found to hold a bad value, a message box
describes the problem. The module then sets the focus to that
control. Therefore, the focus goes straight to the problem so
the user can edit the control without having to find it first once
the error message box goes away.
WARNING: SetFocus is not a property or an event. SetFocus
is known as a method. Controls usually support all three:
properties, events, and methods. A method is a built-in routine
attached directly to a control. In a way, the control executes its
own method. You’ll append method names to the end of a
control as done here. Read the methods from right to left to
understand them fully. For example,
frmInterest.txtTerm.SetFocus tells Visual Basic to set the focus
on the control named txtTerm located on the frmInterest form.
Finally, the code sets the function’s return value to 1 if an error
occurs and exits the function (and therefore the module) and
returns the return value to the calling code, which is the form
module. To return a value from a function procedure, you
simply assign the value that you want to return to the function
Save your project (Lesson 9 Int Proj would be a good name).
When you save the project, Visual Basic asks for a form name
and a module name as well (use Lesson 9 Int Form and Lesson
9 Int Mod to follow the naming convention that this 24-hour
tutorial uses).
ErrorCheck = 1
This hour develops a complete application. Through the
development process, you saw how even a simple project can
require detailed components such as error checking and proper
form management. Too many books rush to the theory
without hands-on work or rush to the hands-on without
explaining the process. This lesson gives your 24-hour tutorial a
needed boost with both hands-on development that strengthens what you already knew and some new topics to consider
such as function procedures and form placement.
Exit Function
End If
‘ No error occurred if execution gets here
ErrorCheck = 0
End Function
The first difference you’ll notice between the function procedure
and the event subroutine procedures you’ve seen so far is the
difference between the opening and closing statements. The
keyword Function distinguishes the function procedure from a
subroutine procedure. The procedures you’ve seen until now
were subroutine procedures that used the Sub keyword to
define them. In addition, the function procedure’s opening line
ends with As Integer. This qualifier tells Visual Basic that the
function procedure will return an integer value. Functions can
return any data type as long as you define the function to return
the proper data type with the As keyword.
The function then checks each text box on the form. All form
references include the form name! Therefore, instead of
referring to the interest rate text box as txtRate, the code
qualifies the text box with a form name as follows:
frmInterest.txtRate. You’ve got to remember that an external
standard module, such as this one, is not part of a form’s code
found in the form module. A standard module might need
access to several forms in the same project, so the standard
module needs the qualifying form name before each control
The next hour describes important list-based controls. You’ll
learn how to produce drop-down list boxes and how to
initialize and work with such lists.
Q Why does End not terminate an application properly?
End seems to work fine without the extra Unload statement.
A End does work fine for single-form applications. Problems
can arise, however, if you create applications with multiple
forms. In certain cases, the End statement may fail to release
every form’s resources. In today’s multitasking, multiuser
networked world, you need to release resources as soon as you
can so that other processes have access to those resources (such
as memory and CPU time). The Unload statement takes care of
closing forms properly.
Q How can I find the default properties for all controls?
A Surprisingly, Visual Basic’s online help does not list the
default properties. The default properties are the most common
properties referenced for a control. Therefore, the default
property for a text box is the Text property, and the default
property for a label is the Caption control. Generally, using a
control’s default property makes for less typing, but default
properties can add confusion later when you try to figure out
the code and change it. Therefore, if you use default properties,
use them only for the label and text box, but specify all other
controls’ default properties explicitly so that your code is as clear
as possible.
The quiz questions and exercises are provided for your further
understanding. See Appendix C, “Answers,” for answers.
1. What does the form’s StartUpPosition value do?
2. Why do label captions often show hotkey letter
3. When is the best time to enter ToolTipText properties and
4. What is a control array?
5. Why does Visual Basic like to offer a control array when you
paste a control on a form that has the source of the paste
already on the form?
6. Why might you want to lock a Text Box control?
7. What is the proper way to terminate an application?
8. What happens when you attempt to divide by zero?
9. True or false: The following two statements are identical:
lblTitle = “The Sound of Multimedia”
lblTitle.Caption = “The Sound of Multimedia”
10. What is the difference between a function procedure and a
subroutine procedure?
1. Add input box routines to the application so that the user
sees the error message in the input box and can enter the
replacement values in the input box. The code then places
the input box’s value into the form. Once the form gets a
replacement value, be sure to check the controls again to
make sure that the replacement value is correct. You might
want to add a Do-While loop around the input box routines
so that the user keeps seeing the input box warnings until
the user enters a value greater than zero.
Learning Objectives
How to add list boxes
What differences exist between list boxes and combo boxes
How to initialize lists
When to use drop-down list boxes
Often the user will need to select from or add to a list of items
such as pay code abbreviations or division names. Visual Basic
supports two controls, the List Box and the Combo Box
controls, that you use to display lists and from which the user
can select items in the lists.
Once you master the List controls, two additional VB programming topics are simple: data arrays and control arrays. You can
combine the List controls and the arrays to work in harmony
when processing lists of information, as you’ll see in this
The List Box Control
Figure 10.1 shows VB’s Options dialog box that appears when
you select Tools | Options and click the Editor Format tab. The
dialog box illustrates a List Box control. You’ve seen list boxes
throughout your work with Windows; list boxes appear on
many forms and dialog boxes. The List Box control gives the
user a choice of several values. The user selects an option
instead of typing a value into a text box. The list box ensures
that the user always chooses one of the available options.
NOTE: The list box displays scrollbars if the list box is not tall
enough or wide enough to display all its data.
As you place the list box on the form, think about the data the
list box will hold and try to size the list box so that it’s large
enough to hold the data. Of course, you don’t always know a
list box’s data in advance because the data might come from a
disk file or from the user at the keyboard, but try to make the
control large enough to hold the data you expect. Your form’s
size and surrounding controls might limit the size of your list
box, so the scrollbars often appear.
Specifies the list box's background color.
Determines the number of columns. If 0, the list box scrolls vertically in a
single column. If 1 or more, the list box items appear in the number of columns
specified (one or more columns) and a horizontal scrollbar appears so you can
see all the items in the list.
Specifies the list box's text color.
Indicates the height of the list box in twips.
Determines whether the list box can display partial items, such as the upper half
of an item that falls toward the bottom of the list box.
Holds, in a drop-down property list box, values that you can enter into the list
box at design time. You can enter only one at a time, and most programmers
usually prefer to initialize the list box at runtime.
The state of the list box's selection rules. If 0-None (the default), the user can
select only one item by clicking with the mouse or by pressing the Spacebar
over an item. If 1-Simple, the user can select more than one item by clicking with
the mouse or by pressing the Spacebar over items in the list. If 2-Extended, the
user can select multiple items using Shift+click and Shift+arrow to extend the
selection from a previously selected item to the current one. Ctrl+click either
selects or deselects an item from the list.
Determines whether the list box values are automatically sorted. If False (the
default value), the values appear in the same order in which the program added
the items to the list.
Determines whether the list box appears in its usual list format or, as shown in
Figure 10.3, with check boxes next to the selected items.
Any list box can have a
single or multiple
columns. In many
situations the single
column makes data
selection easier for your
users, but they will have
to scroll through more
values to locate the item
they want to find. Figure
10.2 shows a form with
two list boxes; the first
list box is a singlecolumn list box, and the
second displays three
columns. (The Columns
property determines the
list box’s number of
To familiarize yourself
with list boxes as quickly
as possible, look over the
property values in Table
10.1. You’ll work with
other properties at
runtime because you
often initialize the list
box at runtime and not
at design time.
Table 10.1. The basic
list box properties.
Figure 10.3. You can add check boxes to list box items.
lstOneCol.AddItem “Robert”
TIP: You can add a command button that operates in conjunction with the list box in many situations. The user can,
therefore, select a value from the list box and then click the
command button to inform your application of the selected
value. You can also add a double-click event procedure to the list
box so that the user’s double-click on a list box item selects that
item. If you set up the command button first, the double-click
event procedure is simple because you can trigger the command
button’s Click() event procedure from within the double-click
procedure with this one line:
You’ll initialize both single-column and multicolumn list boxes
the same way with AddItem. The number of columns the list
box contains has no bearing on how you initialize the list box.
Each item in a list box contains an associated subscript. The
subscript is a number that begins at 0 for the first item, the
second subscript is 1, and so on. Therefore, if you apply the
RemoveItem method as follows, the third item is removed
(because of the first item’s 0 subscript):
cmdAccept_Click ‘ Triggers the button’s click event
Table 10.2 describes the methods available to the list box.
Remember that methods are routines a control knows how to
execute. List boxes use methods more than any other control
you’ve learned about so far. The methods help the user
initialize, add items to, and remove items from list boxes.
Table 10.2. Common list box methods.
Adds a single item to the list box.
Removes all items from the list box.
A string array that holds items from within the list box.
The total number of list box items.
RemoveItem Removes a single item from the list box.
lstOneCol.RemoveItem(2) ‘ 3rd item has a subscript of 2
New Term: A subscript is a value that distinguishes one array
item from the other array items.
As you remove list box items, the remaining item subscripts
adjust upward accordingly. Therefore, if a list box contains
seven items, each item has a subscript that ranges from 0 to 6.
If you remove the fourth item, the list box items will then
range from 0 to 5; the subscript 5 will now indicate the same
item that the subscript 6 indicated before RemoveItem
removed the fourth item.
You can remove all items from the list box with Clear, like this:
‘ Remove all items
You can assign individual items from a list box that contains
data using the List method. You must save list box values in
String or Variant variables unless you convert the items to a
numeric data type using Val() first. The following statements
store the first and fourth list box items in two String variables:
strVar1 = lstOneCol.List(0)
Perhaps the most important method is the AddItem method,
which adds items to the list box. AddItem is to list boxes what
the assignment statement is to variables. A method always
appears between the control name and a period. For example,
the following AddItem method sends the value of Joseph to a
list box named lstOneCol:
lstOneCol.AddItem “Joseph”
NOTE: The one-column list box shown in Figure 10.1 is
named lstOneCol and that’s the name used throughout the
next couple examples.
You’ll often initialize a list box in the Form_Load() event
procedure that initializes the form and the form controls right
before the form appears on the screen. The following code
sends several people’s names to the list boxes shown earlier:
lstOneCol.AddItem “Joseph”
lstOneCol.AddItem “Michael”
lstOneCol.AddItem “Stephanie”
lstOneCol.AddItem “Mary Ann”
lstOneCol.AddItem “Pamela”
lstOneCol.AddItem “Jock”
lstOneCol.AddItem “Bobby”
lstOneCol.AddItem “Cliff ”
lstOneCol.AddItem “Jerry”
lstOneCol.AddItem “Thomas”
strVar2 = lstOneCol.List(3)
The List method requires a subscript so Visual Basic knows
which value from the list to assign to the variable. The value
remains in the list after the assignment, but now the value
appears in the variable as well.
You use ListCount to determine the number of items in the
list box currently defined. The following statement stores the
number of list box items in a numeric variable named intNum:
intNum = lstOneCol.ListCount
TIP: You use ListCount to loop through an entire list box
with a For-Next loop.
You use Selected to determine whether a user has selected a list
box item. Selected returns True for one or more list box items
if the items’ MultiSelect property is set to either 1-Simple or 2Extended. Those properties indicate that the user can select
more than one item at once
Combo Boxes
Combo boxes work much like list boxes except that the user
can add items to a combo box at runtime, whereas the user can
only scroll and select items from a list box at runtime. Visual
Basic supports three kinds of combo boxes, and the kind you
select depends on the combo box you want to display on the
form and on the ability you want the user to have. All the list
box methods that you learned about in the previous section
apply to combo boxes.
lstOneCol.AddItem “George”
Here are the three kinds of combo boxes:
Drop-down combo box-Takes up only a single line on the
form unless the user opens the combo box (by pressing the
combo box’s down arrow) to see additional values. The user
can enter additional items at the top of the drop-down
combo box and select items from the combo box.
Simple combo box-Displays items as if they were in a list
box. The user can add items to the combo box list (whereas
the user cannot with a normal list box).
Drop-down list box-Does not let the user enter new items,
so is similar to a list box. Unlike a list box, however, the
drop-down list box normally appears closed to a single line
until the user clicks the down arrow button to open the list
box to its full size. Technically, drop-down list boxes are not
combo box controls but work more like list boxes. The
reason drop-down list boxes fall in the combo box control
family is that you place drop-down list boxes on forms by
clicking the combo box control and setting the Style combo
box property.
TIP: Think of a combo box as being a combination List Box
and Text Box control. The user sees items in the list but then
enters additional items in the text box portion of the combo
Figure 10.5 shows the three kinds of combo boxes. Each
combo box contains the names of people that you saw in
Figure 10.4. The first combo box, the drop-down combo box,
is normally closed; when the user clicks the combo box’s down
arrow, the combo box opens. The third combo box, the dropdown list box, is left unopened. If the user opens the
drop-down list box, the user will see a list of people’s names
but will not be able to add to the names because no data entry
The combo box's background color.
The combo box's foreground text color.
is possible in drop-down list boxes.
TIP: Study your form’s design and determine the best list
control to use. If the user must enter values, you should use
either a drop-down combo or simple combo box. If the user
only selects a value from a list, use a list box if you have enough
form space or use a drop-down list box if you don’t have a lot
of room to display a full-sized list box.
Table 10.3 describes some of the combo box properties.
Table 10.3. The fundamental combo box properties.
WARNING: The user’s entered value does not add to the
Drop-down Combo Box control or to the Simple Combo Box
control unless you add the capability to capture the user’s entry.
The combo box by itself, without code, cannot handle the
addition of items automatically. You need to write, in the
combo’s Change or LostFocus event procedure, enough code to
add the new item (that always appears in the combo’s Text
property) to the combo box list, like this:
cboBox.AddItem cboBox.Text ‘ Adds user’s value to the box
You can also add a command button that adds the user’s
entered combo box value if the user clicks the command
button and ignores the new value in Text.
TIP: Run Visual Basic’s sample application named ListCombo
(in the VB\Samples\Pguide folder) to see the difference
between a normal list box and a combo box list box.
1. Write an application that builds a list as the user enters new
values. (Hint: Use a Combo Box control for the list.) The list
should hold the user’s favorite book titles. As the user enters
more and more titles, the list should grow. Add a command
button to the form with the caption Add to; when the user
The height, in twips, of the closed combo box.
IntegralHeight Determines whether the combo box can display partial items, such as the upper
half of an item that falls toward the bottom of the combo box.
A drop-down property list box in which you can enter values into the combo
box at design time. You can enter only one at a time, and most programmers
prefer to initialize the combo box at runtime.
Determines whether the combo box values are automatically sorted. If False (the
default value), the values appear in the same order in which the program added
the items to the combo box.
Determines the type of combo box your application needs. If 0-DropDown
the combo box is a drop-down combo box. If 1-Simple Combo, the
combo box turns into a simple combo box that remains open to the height you
use at design time. If 2-DropDown List, the combo box turns into a drop-down
list box that remains closed until the user is ready to see more of the list.
clicks the command button, the title just entered goes to the
list. Keep the list sorted at all times.
Learning Objectives
curDivSales8 + curDivSales9
TIP: If you want to break a long Code window statement into
two or more lines, terminate each continued line with the
underscore character, as shown in the CurTotal assignment.
What is Data Control.
How to declare and use arrays
Why control arrays streamline coding
Data Arrays
Now that you’ve mastered list boxes and combo boxes, you
will have little trouble understanding data arrays. An array is
nothing more than a list of variables. Regular non-array
variables, as opposed to arrays, have separate names such as the
Variables in an array all have the same name. Therefore, an array
that holds a list of 10 division sales figures might be named
curDivSales. Your program must be capable of distinguishing
between an array’s variables, and with the single name this
distinction might seem impossible. Nevertheless, as with list
boxes, your program can distinguish between array variables by
using a subscript. The subscript works just like an index value.
The first value in the array would be subscripted as
curDivSales(0) (subscripts start at 0 unless you use the Option
Base 1 statement in a general module to start the array’s
subscripts at 1). The second value in the array would be
curDivSales(1), and so on.
An array is a list of items with the same name and type.
NOTE: Even without Option Base 1, programmers often
ignore the zero subscript and don’t reference it. Your programming preferences determine the starting subscript that you want
to use.
Figure 10.6 illustrates how an array such as the 10-element
curDivSales resides in memory.
Figure 10.6. Distinguishing array elements with subscripts.
An array makes stepping through and totaling the data much
simpler. Here is the code that uses a For-Next loop to add the
items in an array:
curTotal = 0 ‘ Zero out the total
‘ Step through the elements
For intCtr = 0 To 9
intTotal = intTotal + curDivSales(intCtr) ‘ Add elements
Next intCtr
‘ curTotal not holds the sum of all 10 values
With only 10 variables, does the array make for a lot less coding
than separate variables? With only 10 variables, the array does
not seem to offer a lot of space advantages or coding shortcuts.
What, however, if there were 1,000 variables that you needed to
track and total? By making a simple change to the For-Next
loop, you can easily add together all 1,000 elements, like this:
curTotal = 0 ‘ Zero out the total
‘ Step through the elements
For intCtr = 0 To 999
intTotal = intTotal + curDivSales(intCtr) ‘ Add elements
Next intCtr
‘ curTotal not holds the sum of all 1,000 values
Again, many programmers ignore the 0 subscript and start the
subscript at 1, so this loop would become the following:
curTotal = 0 ‘ Zero out the total
‘ Step through the elements
To declare an array, you use Dim or Public just as you declare
regular non-array variables. In the declaration, specify the
number of elements the array is to hold. The following Dim
statement declares the 10-element Currency array named
For intCtr = 1 To 1000
Dim curDivSales(10) As Currency
Suppose you need to ask the user for several values, such as the
names of children in a class. By declaring a string array, a ForNext loop makes getting the names simple, as you can see here:
NOTE: All elements in an array must be the same data type.
Here’s the great benefit that arrays give you over separate variable
names: When you need to work with a group of variables, if
you don’t use an array, you must list each variable. Therefore, if
you want to add all the divisions’ sales figures and they are
stored in separate non-array variables, you would have to code
something like this:
curTotal = curDivSales0 + curDivSales1 + curDivSales2 + _
curDivSales3 + curDivSales4 + curDivSales5 + _
curDivSales6 + curDivSales6 + curDivSales7 + _
intTotal = intTotal + curDivSales(intCtr) ‘ Add elements
Next intCtr
‘ curTotal not holds the sum of all 1,000 values
For intCtr = 1 To 10
strChildName(intCtr) = InputBox(“What is the next child’s
Next intCtr
WARNING: Remember that if you use a starting subscript of
1, you must declare one more element than you actually need
due to the 0-based subscript that you’re ignoring. Therefore, the
previous code’s strChildName’s array declaration would be Dim
strChildName(11) As String.
Control Arrays
A control array is a list of controls with the same name.
Therefore, instead of using four command buttons with four
separate names, you can place a command button control array
on the form, and that control array holds four command
buttons. The control array can have a single name, and you’ll
distinguish the controls from each other with a subscript.
TIP: Use a control array if several controls on your form are to
look and act similar to each other, such as multiple command
buttons or two or more list boxes.
One of the best reasons to use a control array is that you can
add the first control to your form and set all its properties.
When you create a control array from that first control, all the
elements in the control array take on the same property values.
You then can change those properties that need to be changed
without having to set every property for every control individually.
New Term: A control array is an array of several controls that
you reference with an Index property value that acts as the
subscript. The controls in a control array must be the same
control type.
Control arrays have a lot in common with data arrays. A control
array has one name, and you distinguish all the array’s controls
from each other with the zero-based subscript. (The Index
property holds the control’s subscript number.) All the control
array elements must be the same data type.
As soon as you place a control on a form that has the same
name as an existing control, Visual Basic makes sure that you
want to begin a control array by issuing the warning message
shown in Figure 10.7. The message box keeps you from
accidentally creating a control array when you actually want to
add a different control. You’ll see Figure 10.7’s message box
when you copy an existing control to the Clipboard and paste
the copy elsewhere onto the form. If you click the message
box’s No button, Visual Basic uses a default control name for
the placed control.
All event procedures that use controls from a control array
require a special argument value passed to them that determines
which control is being worked on. For example, if your
application contains a single command button named
cmdTotal, the Click() event procedure begins and ends as
Private Sub cmdTotal_click ()
End Sub
If, however, you created a control array named cmdTotal, the
Click() event procedure begins and ends like this:
Private Sub cmdTotal_click (Index As Integer)
End Sub
The procedure uses the Index argument as the control index
number (the subscript) that the user clicked. Therefore, if you
want to change the clicked command button’s Caption property
inside the cmdTotal_Click() procedure, you would do so like
cmdTotal(Index).Caption = “A new Caption value”
The Index value holds the command button’s index the user
clicked to generate the event procedure so you will always
respond to the proper control clicked if you use Index after the
control array name.
In this hour you have learned how you can add lists of items to
your application. The first kind of list, the List Box control, lets
your users select from a list of items that your application
displays. The combo box works like a list box but lets the user
enter new values into the list.
Data and control arrays help you streamline your programs.
Instead of working with separate variable or control names, you
can work with a single name and use a subscript value to
distinguish between the items. The code to process 10 or 100
array items is virtually the same, as this lesson demonstrated.
Hour 11, “Additional Controls,” teaches several new controls
that you can add to your applications.
Q When do I use a list box and when do I use a combo box?
A A list box presents users with a list of items. The user can
select from the list. The user cannot add new items to the list
box. If you want to present a list of items to the user and let
the user enter new items, use a combo box. A combo box
works a lot like a combination list box and text box. As users
type new values into the text area and then click the appropriate
command button to indicate that the text is ready, the new
values go to the combo box’s list.
Q What’s the difference between a combo drop-down list
box and a regular list box?
A The only difference is that the drop-down list box remains
closed until the user opens it. Therefore, the list box does not
consume a lot of form space until the user is ready to see the
values in the list. If your form contains lots of extra room, you
might want to use a regular list box so your users can see more
values at one time. If form space is tight, use a drop-down list
Q Should I use 0 or 1 for the starting array subscript?
A You can use either unless you’ve added the Option Base 1
statement to a module’s general section, in which case your
subscripts will have to begin at 1. If you don’t use Option Base
1 and you ignore the 0 subscript, however, make sure you
declare enough array elements to hold all your data. If you need
15 elements and you use 1 for the starting subscript, you must
declare 16 values to access subscripts 1 through 15.
The quiz questions and exercises are provided for your further
understanding. See Appendix C, “Answers,” for answers.
1. When do you normally initialize a list box?
2. What method adds new items to a list box?
3. Which method determines the number of items in a list
4. True or false: Visual Basic will automatically keep list box
items sorted if you set a certain property to True.
5. How many combo boxes are there?
6. How do you specify the type of combo box you want to add
to an application?
7. True or false: The drop-down list box is one of the Combo
Box controls, so users can enter new values in the dropdown list box just as they can other Combo Box controls.
8. What is an array?
9. What is the highest subscript in a 10-element array if you do
not use Option Base 1 and you use element 0?
10. True or false: A control array exists when two or more
controls have the same Name property.
1. Write an application that contains four command buttons.
The command buttons should be blue and have boldfaced,
italicized captions that read Change Color, Change Bold,
Change Height, and Change Width. When the user clicks one
of the command buttons, the appropriate property should
change inside the Click() event procedure. Use a Select Case
statement to determine which property should change based
on the event procedure’s Index argument.
Learning Objectives
How option buttons differ from check boxes
When to change the check box’s style
Why scrollbars contain unusual properties
How to set the Timer control to record time passing as an
application executes
Now that you’ve added several programming statements to
your Visual Basic language repertoire, you can learn about
additional controls to add new features to your applications and
to take advantage of some of the more powerful commands
you now know. As you learn about new controls, your programming ability grows by leaps and bounds because your
programs become richer in functionality and user interaction.
You’ll learn about the selection controls, how to program
scrollbars, and how to set the Timer control to let your
application know when a predetermined amount of time has
The highlights of this hour include
Option Buttons
Figure 11.1 shows an application with four option buttons. An
option button gives your user a choice. By clicking the option
button or by sending the focus to the option button and
pressing the Spacebar to choose the option, the user selects or
deselects an option button. The option button has a black
center inside its option button circle when selected.
Option buttons act in a mutually exclusive fashion. Only one
option button can be selected at any one time. Therefore, in
Figure 11.1, the user could not select two or more of the
options. If the user were to click Texas, the California option
would no longer be selected. You don’t have to do anything
special to ensure that only one option button is selected at any
one time; Visual Basic takes care of removing the former
option’s selection when the user selects a subsequent option
NOTE: Option buttons are sometimes called radio buttons.
Many car radios used to have five or six buttons that selected
preset stations. The listener could only select one station; as
soon as the listener pushed a button, the previous station’s
button popped out.
The option button supports several of the properties you’re
already familiar with, such as the Appearance and Alignment
properties. The Alignment property determines whether the
option button text resides to the left or right of the option
button. Figure 11.2 shows the option buttons with their
Alignment property set to 2-Right Justify. The alignment you
set depends on where the option buttons are to fall in relation
to other controls.
TIP: An option button control array makes setting option
button properties, such as the Alignment property, simple.
Several option buttons almost always appear together and the
control array lets you set only one’s property and the others will
receive the same property settings. If you do not create an
option button control array, you can change all the option
button properties at once, even without a control array, by first
selecting all the option button controls and then setting the
properties for all of them at once.
The Value property is perhaps the most important option
button property because the Value property changes at runtime
and determines whether the option button is currently selected.
By the way, the user can select only one option button at a time,
but the application may start up without any option buttons
being set if you don’t set any in the Properties window or in
Frames and Option Buttons
Figure 11.3 shows an application called Controls that comes in
the VB Samples folder. (Load the Controls.VBP project and
run the application to select the Option Buttons command
button and display Figure 11.3’s window.) This option button
application lets you select a computer type and operating
system. Figure 11.3 seems to violate the option button’s
primary rule: More than one option button is selected at the
same time (the Pentium option button and the Windows 95
Sometimes a form will need several sets of option buttons, just
like the form in Figure 11.3. In each set the user should be
allowed to select only one option button, but one option
button should be set from each set at the same time. Therefore,
you must revise the previous rule, which states that only one
option button can be set at one time. The truth is that only one
option button inside a frame can be set at one time.
New Term: A frame is a rectangular region on a form that
holds other controls and groups the controls into a single set.
A frame is a control that holds other controls. The frame is a
rectangular outline with an optional title. When you want to
place multiple sets of option buttons on a form, first place the
frame or frames onto the form. (You can place any control on a
frame, but the frame especially helps group option buttons so
you can offer multiple option button sets.)
NOTE: The form acts as a default frame. Therefore, two sets
of option buttons reside on Figure 11.3’s form: One set resides
in a frame and the other set resides on the form itself so you
consider them framed as well, even though no specific frame
control surrounds them.
The frame control does support properties that determine the
frame’s look and caption and a frame does support a few
events, but most programmers use the frame as a holding place
to group other controls. Once you place controls in a frame, you
can move the frame and all the frame’s controls move with it.
Therefore, adjusting framed controls is relatively easy to do.
Private Sub optItalicTrue_Click()
WARNING: Always place a frame on the form before putting
controls in the frame. If you simply move controls from
elsewhere on the form to the frame, the controls will not be in
the frame but will exist simply on top of the frame. Visual
Basic will not consider them framed together. To add additional
controls to a frame with controls, click one of the framed
controls before adding the new control.
End Sub
An application that contains three frames that determine how
text appears inside a label. The user can select only one option
button inside each frame. As soon as the user changes one of
the options, the option button’s Click() event responds to the
change and sets the Label property accordingly. Listing 11.1
contains the complete form module code that takes care of the
user’s action. The label is initialized in the Form_Load() event
procedure (the procedure that executes right before the user sees
the form) and the remaining event procedures are the responses
to various user clicks on the form’s controls. The controls are
named well enough so that you will know where the controls
appear in Figure 11.4.
Figure 11.4. A form with three frames.
lblFrames.FontUnderline = True
Private Sub optItalicFalse_Click()
lblFrames.FontUnderline = False
End Sub
Private Sub optRed_Click()
lblFrames.ForeColor = vbRed
End Sub
Private Sub optBlue_Click()
lblFrames.ForeColor = vbBlue
End Sub
Private Sub optGreen_Click()
lblFrames.ForeColor = vbGreen
Listing 11.1. The framed option button code.
End Sub
Private Sub Form_Load()
Private Sub optUnderTrue_Click()
‘ Initialize the label’s text
Dim strLabel1 As String
lblFrames.FontItalic = True
End Sub
Dim strLabel2 As String
Dim strLabel3 As String
Dim strLabel4 As String
Private Sub optUnderFalse_Click()
lblFrames.FontItalic = False
End Sub
strLabel1 = “Use frames if you want “
strLabel2 = “to group options together. “
Private Sub cmdExit_Click()
strLabel3 = “Each frame forms one set “
Unload Me
strLabel4 = “of option buttons.”
End Sub
lblFrames.Caption = strLabel1 & strLabel2 & _
strLabel3 & strLabel4
‘ Set the label’s properties
lblFrames.FontItalic = True
optItalicTrue.Value = True
lblFrames.FontUnderline = True
optUnderTrue.Value = True
lblFrames.ForeColor = vbBlue
Color Named Literals
Listing 11.1 demonstrates the use of named literals. The
background colors assigned to the label are named literals that
come with Visual Basic. Table 11.1 lists the named literal colors
that you can use and assign to any property that uses color
values such as the background and foreground colors of several
controls. Given that Windows supports millions of possible
colors, the eight colors that Table 11.1 lists represent a small
number of colors you can possibly set. (Named literals do not
exist for other color values.) Visual Basic supplies several ways
to specify colors so that you can set a color from among the
millions possible. For most situations, however, and for
simplicity, Table 11.1’s named literals work for most applications.
optBlue.Value = True
End Sub
Table 11.1. The color named literals.
vbGreen Green
vbYellow Yellow
vbMagenta Magenta
vbWhite White
Table 11.2. Fundamental scrollbar properties.
Property Description
LargeChange Specifies the amount that the scrollbar changes when the user clicks within the
scrollbar's shaft area.
Indicates the maximum number of units that the scrollbar value represents at its
highest setting. The range is from 1 to 32767 (the default Max value).
Indicates the minimum number of units the scrollbar value represents at its
lowest setting. The range is from 1 (the default Min value) to 32767.
SmallChange Specifies the amount that the scrollbar changes when the user clicks an arrow at
either end of the scrollbar.
Contains the unit of measurement currently represented by the position of the
Check Boxes
When you place a scrollbar on a form, you must decide at that
time what range of values the scrollbar is to represent. The
scrollbar’s full range can extend from 1 to 32767. Set the Min
property to the lowest value you want represented by the
scrollbar. Set the Max property to the highest value you want
represented by the scrollbar.
Figure 11.5 shows a form with check boxes. The Check Box
control works just like the option button, with two differences:
A selected check box shows the selection with a checkmark, and
check boxes are never mutually exclusive. Therefore, the user can
select one or more check boxes even if those check boxes reside
in the same frame or on the same form.
NOTE: Figure 11.5’s application is from the Controls.VBP
project included in VB’s Samples folder.
When the user eventually uses the scrollbar, the scrollbar arrows
control small movements in the scrollbar’s value determined by
the SmallChange property. Clicking the empty part of the shaft
on either side of the scrollbox produces a positive or negative
change in the value represented by the LargeChange property.
The user can drag the scrollbox itself to any position within the
scrollbar shaft to jump to a specific location instead of changing
the value gradually.
The Check Box control supports the same fundamental
properties as the option button except that the Value property
determines not only if the box is checked (if 1) or unchecked (if
0), but a check box can also be grayed (if the Value property
contains 2). Users sometimes use a grayed check box to
determine whether part of a selected option is true. In addition,
the programmer may gray out a box to show that the selection
is unavailable under the current conditions.
Suppose, for example, that a horizontal scrollbar represented a
range of whole dollar amounts from $5 to $100. When the user
clicks the scroll arrows, the scrollbar’s value changes by $1. When
the user clicks the empty shaft on either side of the scrollbox,
the scrollbar’s value changes by $5. Here are the property values
that you would set that determine how VB interprets each click
of the scrollbar: Min: 5, Max: 100, SmallChange: 1, and
LargeChange: 5.
Visual Basic version 5 added a new Style value to the Check Box
control’s property list. The available Style property values are 0Standard and 1-Graphical. The graphical style value makes the
check box look a lot like a command button that stays pressed
(when selected) or unpressed (when not selected).
The physical size of the scrollbar has no bearing on the
scrollbar’s returned values when the user selects from the
scrollbar. Adjust the scrollbars on your form so that the
scrollbars are wide enough or tall enough to be appropriately
sized for the items that they represent.
New Term: A thumb is the scrollbar’s moving scrollbox (the
elevator-like box).
Scrollbars let users control value changes. Rather than type
specific values, the user can move the scrollbars with the mouse
to specify relative positions within a range of values. The
toolbox includes both a Horizontal Scrollbar and a Vertical
Scrollbar control.
Table 11.2 contains a list of important scrollbar properties that
determine the behavior of the scrollbar.
Figure 11.7 shows an application that uses a vertical scrollbar to
change the size of a label’s font size. As the user clicks the top
scrollbar arrow, the font size shrinks by the SmallChange value.
As the user clicks the bottom scrollbar arrow, the font size
increases by the SmallChange value. (The application’s
SmallChange property value is 1.) If the user clicks in the
scrollbar’s shaft on either side of the scrollbar’s thumb, the
LargeChange property value of 5 is either added to or subtracted
from the font size.
Figure 11.7. The vertical scrollbar determines the label’s font
Listing 11.2 shows the code behind Figure 11.7. The code is not
lengthy because the scrollbar’s Click() event procedure must
change only the label’s text font size and the label that displays
the current font size. Any time the user changes the scrollbar,
the scrollbar’s Click() event procedure executes.
Listing 11.2. The code behind the scrollbar application.
Private Sub vsbHeight_Change()
lblScroll.FontSize = vsbHeight.Value
lblFontHeight.Caption = vsbHeight.Value
End Sub
VBs Clock: The Timer Control
The Timer control acts unlike any other control you’ve seen so
far. The Timer control always works in the background and the
user never sees the timer on the form. You will see the Timer
control during design time because you need to be able to select
the control and change its properties. Nevertheless, the timer’s
purpose is to work in the background, triggering an event every
once in a while according to the clock ticks.
Your computer has an internal clock to keep things running
smoothly. The hardware requires an accurate clock for memory
refreshes and CPU cycle coordination efforts. Software, such as
Visual Basic, can tap into the internal clock and utilize its timing
to control certain time-based events that your application may
need to perform.
Figure 11.8 shows the Timer control as it appears when you
place the control on a form. The Timer control supports only
seven properties because the Timer control never appears on the
form at runtime. Therefore, the control has no need for many
of the style and size properties used for other controls the user
Figure 11.8. The Timer control appears on the form only at
design time.
You can place the timer out of the way of your form’s other
controls since its physical location is trivial. Once you place the
timer on the form, you should set its Interval property because
Interval is the most important timer property. The Interval
property contains a value that must range from 1 to 65535. The
value is in milliseconds (or thousandths of a second), so an
Interval value of 500 would equate to half a second. The Timer
control generates only one event: the Timer event. The Timer
control triggers a Timer event after each interval of time goes by.
Therefore, if you named a Timer control tmrClock, and if you
set the control’s Interval property to 1000, Visual Basic would
execute the tmrClock_Timer() event procedure approximately
every second.
New Term: A millisecond is one-thousandth of a second.
WARNING: The Timer control is not a perfect timer, just a
good timer. Other processes occurring inside your computer can
cause the Timer control to be off by a few milliseconds. The
smaller the Interval value, the more likely the Timer event will
be off. Fortunately, the Timer control works without much of a
timing hitch, especially given today’s faster computers.
Figure 11.9 shows the Alarm sample application that comes
with Visual Basic in the Samples\PGuide folder. The Timer’s
Interval property value is set to 500 and the time of day
updates every half-second (the time is shown in full seconds;
the half-second update helps correct timing problems that
might occur every few half-seconds). Therefore, if you run the
Alarm application, a Timer event will occur every one-half
Figure 11.9. The Timer control generates an event every few
Clicking on the Alarm application’s small Form window
produces an input box that asks you for an alarm time. The
Timer() click procedure from then on compares the current time
with the time that the user enters and, if the alarm time has
been reached, the alarm goes off. The alarm displays Figure
11.10’s dialog box, which informs the user that the alarm time
is reached.
Figure 11.10. The Timer() event procedure determined that the
alarm time was reached.
WARNING: Feel free to study the sample Alarm application’s
code, but be warned that the application uses a few built-in
functions that you will not master until Hour 14, “Built-in
Functions Save Time.”
If you need an interval that’s larger than the 65535 Interval
value allows (this maximum Interval value provides only about
a 10-second interval), insert some If logic at the top of the
Timer() event procedure that checks to see if the required
amount of time has passed since the last interval. (To do this,
you will need some of the time functions described in Hour
In this hour you have learned about several new controls so you
can begin adding more user interactivity to your applications.
The option buttons and check boxes work almost exactly alike
except that the option buttons are mutually exclusive and
provide your users with single options from a selection. The
scrollbars let your users select values based on a range using
either a horizontal or vertical scrollbar. Finally, the Timer control
keeps track of time passing during your application’s execution
and triggers a Timer event every time the Interval value of time
has passed.
Hour 12, “Dialog Box Basics,” builds further on your I/O
skills by demonstrating how to create common dialog boxes.
Your users will be able to use the dialog boxes to enter and
select multiple values.
Q Can I program check boxes to be mutually exclusive or
do I have to use option buttons?
A Check boxes are not mutually exclusive by design. Option
buttons are. Therefore, a Visual Basic application’s user can only
select one option button at a time within any one frame or on
the form. If you want to change the behavior of check boxes
and make them act like option buttons, be warned that you are
giving your users mixed signals. Your users are used to being
able to select as many check boxes as they wish and your
application can keep them from doing the usual, which, in
many cases, makes the user dislike your application. Users feel
comfortable when an application follows de facto standards.
Nevertheless, you can make the check boxes act like option
buttons, but you will have to put code in the check boxes’
Click() event procedures to remove the check from the current
check box when the user clicks another check box. The code is
fairly trivial, but again, your users will adapt more easily to your
application if you use option buttons in mutually exclusive
Q How can I trust the Timer control if it is not accurate?
A The Timer control is accurate, but your computer cannot
always let Windows respond to events exactly when needed. A
multitasking operating system such as Windows does a lot of
things at once. If a Timer() event occurs, the operating system
cannot always, at that exact millisecond, go back to the running
application and signal that the event occurred. Therefore, your
applications sometimes take a back seat to system operations.
Today’s fast computers have much less of a time-accuracy
problem than in the past, so you should not worry too much
about the potential millisecond miss now and then.
The quiz questions and exercises are provided for your further
understanding. See Appendix C, “Answers,” for answers.
1. True or false: Option button captions always appear to the
right of the buttons.
2. What happens if the user clicks an option button that is not
currently selected?
3. Why would you gray out a Check Box control?
4. What happens if the user clicks a check box that is not
currently selected?
5. True or false: An application can begin with none of its
option buttons or check boxes selected.
6. What kind of control can you place on a frame?
7. What is the difference between a scrollbar’s Small Change
property and a scrollbar’s Large Change property?
8. Which property changes when the user clicks one of the
scrollbar’s arrows?
9. True or false: The Timer control works like an alarm clock
ready to go off at a preset time of day.
10. True or false: If you need a timer interval greater than
approximately 10 seconds, you must use multiple Timer
1. Create an application that mimics the frame application used
with Listing 11.1. Instead of using separate option buttons,
use an option button array for each frame’s option button,
making a total of three option button arrays. Change Listing
11.1 to reduce the number of event procedures in the
application. Use a Select Case statement based on the event
procedure Index argument to set the appropriate label
2. Change the application you wrote in exercise 1 so that no
frames appear on the form. Remove the Underline and Italic
option buttons (keep the Framed Color option buttons)
and add these check box controls in their place: Underline
and Italic. Change the code so that the text will appear
underlined if the user clicks the Underline check box and so
that the text will be italicized if the user clicks the Italic check
box. Both or only one might be checked at any one time.
3. Duplicate this lesson’s scrollbar application that lets the user
set the label’s text size with the scrollbar. Completely remove
the scrollbar, however, and add a Timer property. Every
second, add 5 to the label’s font size. When the font size
grows to 70 or more points, send the size back down to 8
and start increasing the size once again.
“The lesson content has been compiled from various sources in public domain including but not limited to the
internet for the convenience of the users. The university has no proprietary right on the same.”
Rai Technology University Campus
Dhodballapur Nelmangala Road, SH -74, Off Highway 207, Dhodballapur Taluk, Bangalore - 561204
E-mail: [email protected] | Web:
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF