You are on page 1of 20

Visual Basic 5

Programming - 1
A Specialised Training Course
Contents

INTRODUCTION ................................................................................................................... 2
What is Visual Basic? ...................................................................................................... 2
Why Visual Basic? ........................................................................................................... 2
How is Visual Basic so Effective? .................................................................................... 3
Is Visual Basic Object Oriented? ..................................................................................... 3
What are Objects?............................................................................................................ 3
So where does ‘Event Driven Code’ fit in? ...................................................................... 4
Isn’t Basic old-fashioned? ............................................................................................... 4
WINDOWS TERMINOLOGY .............................................................................................. 5
A ‘WINDOW’ .......................................................................................................................... 5
INFORMATION BOXES ............................................................................................................ 7
Dialog Box ....................................................................................................................... 7
Message box..................................................................................................................... 7
CONTROLS ............................................................................................................................. 8
Buttons ............................................................................................................................. 8
Text Boxes ........................................................................................................................ 8
Option Buttons ................................................................................................................. 8
Check Boxes ..................................................................................................................... 8
List Boxes ......................................................................................................................... 8
Pictures / Images.............................................................................................................. 8
A LOOK AT THE CONTROLS.................................................................................................... 9
OTHER FEATURES .................................................................................................................. 9
THE VISUAL BASIC IDE ................................................................................................... 10
WHAT’S ON SCREEN ............................................................................................................ 10
VISUAL BASIC APPLICATION WINDOW................................................................................ 11
Title Bar ......................................................................................................................... 11
Menu Bar ....................................................................................................................... 11
The Toolbar.................................................................................................................... 11
THE FORM WINDOW ............................................................................................................ 12
THE TOOLBOX ..................................................................................................................... 12
PROJECT WINDOW ............................................................................................................... 13
PROPERTIES WINDOW.......................................................................................................... 13
EDIT WINDOW ...................................................................................................................... 13
THE PROJECT ..................................................................................................................... 14
Forms ............................................................................................................................. 14
Code Modules ................................................................................................................ 14
Class Modules................................................................................................................ 15
Custom Controls ............................................................................................................ 15
Resource Files / Binary Data......................................................................................... 15
PLANNING YOUR PROJECT ON PAPER AND OTHER GOOD PRACTICES .................................... 15
MAKE AN EXE FILE ............................................................................................................. 15
EXERCISES .......................................................................................................................... 16

Visual Basic Book 1 © Mark Collins 1999 Page 1


Introduction
What is Visual Basic?
Visual Basic is a programming tool for developing Applications.
There are several versions available now, in this course we will
use Version 5 Professional Edition, the 32-bit version. Much of
this course is applicable to previous editions, any significant
differences will be mentioned.
Version differences will be highlighted in sections like
this one.
One of the myths surrounding Visual Basic is that you can
develop powerful applications without any ‘programming’. It is
indeed possible to create very simple applications with a minimum
knowledge of the Basic programming language, but in order to
create anything substantial a developer needs to utilise more
advanced concepts of Visual Basic programming. We will develop
these during the course.

Why Visual Basic?


When you choose to develop a Windows application there are
various alternatives available including...
• use a ‘Database’ application (e.g. Access or Paradox).
• use a ‘proper’ programming language such as C, C++ or
Pascal.
• use Visual Basic.
There are advantages and disadvantages with each of these
approaches. With a Database you are locked into using a
Database format, which may limit the scope of your project. With
one of the other languages mentioned you certainly have a lot
more scope and control, but they have a slower learning curve and
development time is far longer than Visual Basic.
Visual Basic allows us to develop fast, powerful applications with
less complexity than say C++, and with the capability to utilise
Microsoft Access database files (if we want). It also allows
increased integration with other applications (e.g. MS Office)
through OLE.

Visual Basic Book 1 © Mark Collins 1999 Page 2


How is Visual Basic so Effective?
Visual Basic is run in a Graphical IDE (Integrated Development
Environment). Many of the controls are mouse controlled and you
are creating your applications interface directly on screen.
It is designed to run under Windows (v3.x, 95 & NT) developing
Windows applications. All the different standard controls are
implemented such as Buttons, Combo Boxes, Menu Bars and
Toolbars. As these have all been provided as standard ‘Objects’
we just need to know how to control them, we don’t need to re-
invent the proverbial wheel each time.
During development you can safely test your project by using
Visual Basic as an interpreter. However, when your project is
finished you can then create an Executable file (or files) to
distribute and use. There are various runtime files which your
executable needs, but you do not need Visual Basic installed to
run a Visual Basic Application.

Is Visual Basic Object Oriented?


With Version 5 the answer is definitely “Yes” although many OO
purists may disagree. At the initial level you do not need to be an
OOPS Guru to use it as the ‘objects’ have been provided for you
to implement and control as you require. You can also be fairly
sure that the Objects provided are fully tested and free of bugs.

What are Objects?


An object is a programming term to describe a special kind of data
item. In addition to containing the data the object also knows how
to manipulate that data. Each different process that the object can
perform on its data is known as a Method. The technical term
used to describe this combination of Data and associated processes
is Encapsulation.
Other OO languages have additional concepts called Inheritance
and Polymorphism. These are not applicable in Visual Basic,
they are complex and unnecessary for most work.
An additional concept of Objects is that the only way to
manipulate the data is to us one of the associated methods. Code
outside the object can not directly manipulate the data, but it can
pass a message to the object activating one of the methods.
In Visual Basic the primary objects available are forms and
controls. A form is simply a Window of one type or another. A
control is an object we place on a form, such as a button or a text
box.
Visual Basic 5 also allows you to create your own class of object
using class modules.
Each Visual Basic Object has a set of properties. These may
contain the actual data we wish to process or some attribute of the
object such as its name or the colour of the background. Much of
the actual programming involves manipulating these properties.

Visual Basic Book 1 © Mark Collins 1999 Page 3


So where does ‘Event Driven Code’ fit in?
Each object also has an associated set of event procedures. For
example a button will probably contain a Click procedure which
contains the code to run when the button is clicked with the
mouse.
This differs greatly from the standard type of program, a
procedural program. A procedural program runs through a
sequence of commands, that may branch through various routes,
but generally leading you through the program from beginning to
end.
An event driven program reacts to...
• your prompting an event (e.g. clicking a button, selecting
from a list, using a scroll bar, starting the application, etc.)
• a system event (e.g. a timer)
• from a program instruction causing an event
• another application exchanging information.
You, the developer, choose which events your program should
react to and what processing to perform at each event. This is
where the actual BASIC coding comes in.

Isn’t Basic old-fashioned?


A decade ago Basic was still used extensively to produce what
were then powerful applications. Programmers however started to
move across to more structured languages as their demands
increased. Basic developed to meet these new demands but was
not taken seriously as a ‘proper’ language. Microsoft persisted,
bundling it in the form of GWBasic and then QBasic with MS-
DOS. It wasn’t until the latter years however that Microsoft
brought it back to the fore. They wanted a language that a
hobbyist programmer could use to develop serious applications in
a new Windows based graphical IDE without too steep a learning
curve.
Their strategy has now developed to replace the various Macro
languages in their Windows applications (Word, Excel etc) with a
standard Visual Basic Macro language, known as Visual Basic for
Applications - effectively a library of objects for use with Visual
Basic. The latest versions are seeing this strategy come to
fruition.

Visual Basic Book 1 © Mark Collins 1999 Page 4


Windows Terminology
Before we start Exploring Visual Basic itself it is important that
we develop a standard terminology to describe it’s various
features. Microsoft have a standard name for each item which we
will use throughout this course. Unfortunately as Microsoft are an
American company many names have an American spelling
which we will use (grudgingly).

A ‘window’
To avoid confusion I will refer throughout to Windows (3.x, 95/98
or NT), the software package, with a capital W and in italics. An
individual window will be in normal text.
A ‘window’ is a rectangular frame that can contain anything from
a complete application to a group of icons to a picture document.
Your work happens inside these windows. You can have several
of these windows open simultaneously, each running a different
application. By switching the focus from window to window you
can move between them, effectively running multiple applications.
A window containing a running application is an application
window. An application window may contain several child
windows. These are otherwise known as document windows. In
Windows a document can be more than a text file. It can be a
picture, a list of filenames, a group of icons (like within Program
Manager) or another type of document.

Child Window within Parent Window

Child
Window

Visual Basic Book 1 © Mark Collins 1999 Page 5


All windows have common features, which have a different
appearance in Windows 95 to version 3.x. Some windows may
not use all of them depending on the window’s use. The following
diagrams indicates some of these features which are described
below in the table. Title Bar

Menu Bar Min and Max

Toolbar
Border

Component Description
Title Bar The strip along the top of each window containing the title
of that window.
Border Defines the boundary of a window and allows resizing of
the window with a mouse.
Minimize To the right of the title bar, this reduces the window to an
button icon.
Maximize To the right of the minimize button, this enlarges to window
button to fill the screen when it is replaced by the Restore button.
Close Button Closes window / application
Restore button Replaces the Maximize button when the window is
maximised. It resizes the window to it’s previous size and
the button changes back to the maximize button.
Menu Bar The horizontal strip just below the title bar. It contains the
titles of the menus supported by that window.
Scroll Bars These control which part of the document you view in the
window if the document is larger than the viewing window.
Icon These represent windows that have been minimized. You
can restore the window by double clicking).
Toolbar A single click on one of these generally performs an action
similar to a menu selection.

Visual Basic Book 1 © Mark Collins 1999 Page 6


Information Boxes
These are often confused with windows but perform specific input
and/or output tasks. The two main instances to understand are the
dialog box and message box.

Dialog Box
A dialog box prompts the user to supply information needed by
the program to continue with the application. There are standard
common dialog boxes used in many Windows applications for
example for file-specification.
A dialog box will usually consist of some input controls (text
boxes, list boxes etc.) and at least two buttons. An OK button is
used to accept the input and proceed. A Cancel button is used to
back-out of the dialog box without accepting any of the input.

Message box
A message box appears when the program or the system needs to
inform you about a specific situation. This may be a warning or
error message.
To indicate the message type it is standard practice to include one
of four icons...
• Exclamation mark
• Question mark
• Stop sign
• Information sign
There should be at least one button to select depending on the
choices available.

Visual Basic Book 1 © Mark Collins 1999 Page 7


Controls
As mentioned previously, controls are objects placed within forms
(i.e. windows or information boxes). As the name suggests these
objects can be manipulated to allow input or output from the
application. Here is the first set of the most common...

Buttons
Respond to a single mouse click. A caption or icon/picture on the
button indicates its use. Buttons generally appear three-
dimensional and sink into the screen when activated.

Text Boxes
A text box is an object containing all the functionality to enter
textual or numerical information into your application. This
functionality includes full editing (insertion, deletion etc.).
A text box may be single-line to enter a single word or number, or
multi-line to enter large blocks of text.

Option Buttons
Otherwise known as Radio-buttons, they appear in groups where
one button only is to be selected. Selecting a new button will
deactivate the previously selected button. If a single button is
required then you should use Check Boxes.

Check Boxes
Often confused with option buttons, a check box is a square which
may or may not be selected (on/off, yes/no, true/false). May
appear in groups, but unlike option buttons any combination of
selected buttons may be allowed.

List Boxes
Provides a list from which to choose one or more items.
Depending on the mode chosen you can select single or multiple
items. If the size of the list is too big for the list box then a vertical
scroll bar is added.
There are two basic types, a standard list box and a combo-box .
In the combo-box only a single selected item is usually shown, but
clicking the down arrow button to the right drops a list from which
to select.

Pictures / Images
These are graphical controls. A picture control is usually used to
display information although it is possible for them to respond to
mouse clicks etc.

Visual Basic Book 1 © Mark Collins 1999 Page 8


A look at the Controls
The following diagram shows some of these controls in use.

Other Features
There are many other features too many to mention at this stage
but that we will cover through the course.
These include DDE (Dynamic Data Exchange) and OLE (Object
Linking and Embedding) - especially OLE, which allow us to
integrate applications. There is also the Windows API, a body of
over 800 functions that we can use to interact with the Windows
environment. This is advanced stuff, but will allow us eventually
to create powerful applications.
For the most part the complexity involved in developing Windows
applications has been dramatically reduced with Visual Basic as
most of the complex details are dealt with automatically - until we
want to take full control ourselves.

Visual Basic Book 1 © Mark Collins 1999 Page 9


The Visual Basic IDE
In order to develop our Windows applications in Visual Basic we
use the Visual Basic IDE (Integrated Development Environment).
As a Windows application itself it offers all the benefits of a
graphical interface. Using the mouse and keyboard we can
quickly design and code our applications on it.

What’s on Screen
When we start-up Visual Basic, the following windows appear on
screen. We will work through the windows in turn.

Visual Basic Book 1 © Mark Collins 1999 Page 10


Visual Basic Application Window
This consists of the...
• Title bar
• Menu bar
• Toolbar

Title Bar
Contains the title “Microsoft Visual Basic [mode]” where the
mode is either [design], [break] or [run].

Menu Bar
As with many Windows applications you have several ways of
selecting menu options; by using the mouse or keyboard to select
an option, or by using a keyboard shortcut. You should
familiarise yourself with the menu commands, but for now here’s
a summary of the important sections...
Menu Activities
File Opening, closing and saving projects.
Printing forms or code.
Creating an EXE file.
Edit Undoing and redoing actions.
Cut / copy / Paste.
Find / replace.
View Affects what you see in the Visual Basic IDE.
Insert For adding extra forms / modules etc.
Run Alters depending on which mode you are in, and lets you
switch between mode. Debug stepping here too.
Tools Tools and Options
Add-Ins Particularly the Data-Manager, other extras can be added
Help Used to access Visual Basic Help files. There are several files
on various topics, each of which can be accessed.

The Toolbar
This consists of a set of buttons / icons used as short-cuts for many
of the menu options.

Visual Basic Book 1 © Mark Collins 1999 Page 11


The Form Window
This is where we design the windows and dialog boxes that are
going to appear in our application. One way of viewing it is as a
Visual Basic ‘Document’. Depending on the design we may place
controls on our form.

The Toolbox
This window contains buttons to access the set of controls that you
select to include in your application. As you add or remove
modules from your default project file or your current project file
the buttons change.

part of the toolbox.

The set of tools shown depends on which version and edition you
have and which custom controls you have enabled through the
Project / Components menu.
To add a control to our form we select the relevant button from the
toolbox and click on the form to place a default size control, or
click and drag on the form to place a control of a specific size.
NB. If you open up a project and you want to a control that’s not
on the toolbox then press ctrl+T to load up the tabbed components
dialogue box. During the course various controls will be needed
and you have to use this dialogue box to select the required
controls to add to the general toolbar, so that the controls can be
used in your project.

Visual Basic Book 1 © Mark Collins 1999 Page 12


Project Window
This window lists the various forms and modules included in this
project. You can access the various components from here as well
as adding and deleting them.

Properties Window
As you manipulate forms and the controls on those forms this
window shows the properties of the currently selected object(s).
You can change a property at design-time by selecting the
property and editing its value.

Edit window
This is where you can edit the code associated with an object.
Double clicking an object brings up the code edit window.

Visual Basic Book 1 © Mark Collins 1999 Page 13


The Project
In Visual Basic a project can be regarded as all the parts required
to create our application. The details of these are contained in a
Project file with the extension *.VBP ( *.MAK in VB3) Your
application will consist of several parts including...
• Forms
• Code Modules
• Class Modules (VB4 and VB5)
• Custom controls
• Binary Data / Resources
Each of these apart from the Custom controls are files that you
will create. For a single project it is good practice to store them in
a single sub-directory with the same name as your project file.
What are the different components of a Project for?

Forms
These are the workspaces on which we will design our windows
and dialogue boxes. An application may consist of several forms
which can be loaded, unloaded, shown and hidden by the code.
Each form is stored in its own *.FRM file and contains a
description of the form’s appearance, including the controls placed
on it. The form also contains the code for procedures and
variables associated with the form itself and the individual
controls.

Code Modules
In an application with several forms it is likely that there will be
code not specifically attached to a single form. This code
(variables, constants & procedures) is stored in a Code Module
and is available to any form. A Code module has a file extension
of *.BAS

Visual Basic Book 1 © Mark Collins 1999 Page 14


Class Modules
A new addition since VB4, class modules differ from code
modules in that it is more object-oriented - a single class of object
is defined in a Class Module. They are stored in *.CLS files

Custom Controls
These are additional controls to the standard set that can be added
to your toolbox. The Professional Edition has many more of these
that the Standard Edition. It is also possible to obtain third-party
controls to add yourself. A custom control has the file extension
*.OCX or the older *.VBX. Active X controls can be regarded as
more complex custom controls.

Resource Files / Binary Data


These files store specialised data required when an icon or picture
is included at design time. In VB3 they were *.FRX, in VB4 they
are *.RES files and in VB5 & 6 they are *.FRX.

Planning your Project on Paper and other good


practices
Initially we will be dealing with simple applications that are
relatively small and simple to create. As you start to develop
larger applications keeping track of your project becomes difficult
so spending time planning and designing on paper becomes
important. You should prepare what controls you are likely to
need; the processes to be performed and the variables and
constants that are required to support the processing. Attempting
to develop “on the fly” will soon present you with problems.
Visual Basic allows a very flexible approach to development. The
ability to click the Run button and test what you have at any time,
without a lengthy compile process, enables you to test-as-you-go.
This cycle of creating or modifying an object (including properties
and code) followed by a test followed by a rethink and repeating
the cycle can continue as your project develops stage by stage
until you have a finished product. This you convert to an EXE file
and use outside Visual Basic.
This prototyping method should not be allowed to take over from
careful and considered planning. It is all too easy to return to a
project after a weekend away and to have completely lost track of
what you were doing. Your code will also develop in a haphazard
way with inconsistencies, duplication or redundancy creeping in.

Make an EXE file


This prepares your project for use independent of Visual Basic.
All the necessary code is ‘compiled’ into files that can then run
independently. Your application is now ready to use, distribute or
sell as necessary.

Visual Basic Book 1 © Mark Collins 1999 Page 15


Exercises
• Create a sub-directory C:\PROJECTS\WELCOME to save the project of
the same name in exercise 2.
Exercise 1.
Run a Sample Project.
This exercise uses an existing project to familiarise you with the Visual Basic
IDE.
1. Either click on the Open project button on the tool bar or select
File/Open project from the menu.
Locate On drive C:\ PROGRAM FILES \DEVSTUDIO \PGUIDE
\SAMPLES \CONTROLS directory. In the file selection box you
should see “CONTROLS.VBP”. Select this project (double click the
name, or highlight the name and click OK).
2. The Project window will appear with one entry. Expand this by
clicking on the plus symbol. Note the contents identifying the type of
files included. How many forms are there?
Has the Toolbox changed? Can you explain why (hint - *.OCX files)?
3. Use the Run button on the toolbar to execute the project. Note how the
Visual Basic Application window remains, but the mode is now [Run].
A window will appear with a single menu called Options. Select each
option in turn, trying out various controls on each.
4. When you have investigated enough, exit the application. How many
ways are there to exit this application? (You should find at least three)
5. You should now be back in [design] mode. Use the Project window to
view each form in turn. Can you identify the control types on each
form?
6. Return to the MAIN form in [design] mode. The EXIT command
button has some code to perform when it is clicked. Double-click it in
design mode to see that code. It is not vital that you understand the
construct of the code yet.
7. If you are exiting Visual Basic now or starting a new project you need
not save any changes you may have made to this project.

Visual Basic Book 1 © Mark Collins 1999 Page 16


Exercise 2
Writing a simple application
If you are not in Visual Basic load it as previously. If you are select File/New
Project from the menu (do not save any changes to the sample application
from exercise 1)
1. You should have a blank form window with the title bar “form 1”.
Make sure that this is the active window. Note the various defaults in
the properties window. Make the following changes in the property
window...
Property Old value New value
Name Form1 frmWelcome
Caption Form1 Welcome

2. Adjust the size of the form until it is about a quarter of the size of your
screen. Do you notice properties changing as you do this?
3. Add a simple label control. Select the label control (the toolbox button
with a capital A) and click-and-drag a rectangle in the middle of your
form. Make sure that this control is highlighted and change the
following properties. (To change the autosize property between True
and False you can either use the drop-box selector or double click the
property)
Property Old value New value
Autosize False True
Caption Label1 Welcome yourname

4. Reposition the label and resize the window if you like. When you are
happy with your layout Run your application (a grand title at this stage
I know, but from small acorns...).
5. There is not a lot we can do at this stage except play around with the
window, so stop the application.
6. Save the project.
- Select File/Save Project from the menu or click the Save button on
the toolbar.
- You are first asked to select the name and location to store any forms
or modules. The form we renamed in part 2 of this exercise already
has a suitable name (frmWELCO.FRM) . We now need to select the
E:\PROJECTS\WELCOME directory we created earlier and click OK.
- You are now asked to save the project file. PROJECT1.VBP is not
that informative, so rename it WELCOME.VBP. The location is
the F:\PROJECTS\WELCOME directory from before so click OK.

Note: The general routines described above for creating and saving new
projects will be the same except for the filenames for future projects.

Visual Basic Book 1 © Mark Collins 1999 Page 17


Exercise 3
Improving the Welcome application.
If you are continuing on directly from exercise 2 the Welcome project should
be active in Visual Basic, if not then load it from disk.
1. Amend the label in the frmWelcome form as follows...
Property Old value New value
Caption Welcome yourname Enter your name:

2. Add a text box below the label (identify and select the correct toolbox
button, the click and drag a rectangle). Make it approximately the
same size as the label. Change the following properties for this
control...
Property Old value New value
Name Text1 txtName
Text Text1 clear the text

3. Add a command button below the text box, again about the same
width but about three times as tall. Give this button the following
properties...
Property Old value New value
Name Command1 cmdOK
Caption Command1 OK

4. Now for some code. Double-click the button to bring up the code
window. Amend the text for this event to appear as follows...
Sub cmdOK_Click ()
MsgBox "Welcome " & txtName.Text
End Sub

Although VB will allow you to use a ‘+’ instead of an ‘&’ to


concatenate strings the ampersand is safer.

5. Run and use the application. Note how we already have quite a lot
going on, but we have only written a single line of code. Return to
[design] mode.

Visual Basic Book 1 © Mark Collins 1999 Page 18


6. Add a second button to the right of the OK button of the same size.
Give it the following properties...
Property Old value New value
Name Command1 cmdQuit
Caption Command1 QUIT

7. We will use this button to exit our application. Amend the


cmdQuit_Click code as follows...
Sub cmdQuit_Click ()
End
End Sub

8. Test your application again. If you are happy with it then save your
project again (the filenames shouldn’t need changing).
9. Make an executable file so that we can run it outside of Visual Basic.
- Select File/Make EXE file...
- Select C:\ as the location for WELCOME.EXE
10. Quit Visual Basic (saving any changes if not done so already).
Load Welcome.exe as an icon in Program manager and run it.

Supplementary Tasks
• Run through the windows tutorial to familiarise yourself with the
terminology etc. (Accessible from the Help menu of Program Manager
or run Start/Help from Windows ‘95/98)
• Try running and investigating some of the other sample applications.

Visual Basic Book 1 © Mark Collins 1999 Page 19

You might also like