Beginning Visual Basic 6
Beginning Visual Basic 6
Beginning Visual Basic 6
Copyright 1999
By: Gary Beene
Gary Beene's Online Tutorial: http://web2.airmail.net/gbeene/tutor.html
Gary Beene's Visual Basic World: http://web2.airmail.net/gbeene/visual.html
Tip: To quickly find a chapter, press control+f and type the chapter number and then make certain
to check the option that says match case. After this, press enter to find the chapter.
Table Of Contents:
It can be very difficult to pick up a new skill, especially when the training material starts off assuming you
know more than you actually do! Throughout my tutorials I will continually try to put things into
perspective and to explain why a certain capability of VB is valuable and whether it might be valuable to
you. This means that my introductions to each of the sections will be a bit long, but the intent is to set the
stage so that you will know why you need to know the information in that section. To begin, let's talk about
VB and how it was derived from its predecessor, BASIC.
Send email to [email protected] <mailto:[email protected]>
04/10/99
A Definition
Visual Basic is a much-enhanced version of the BASIC programming language and the BASIC Integrated
Development Environment (IDE). The bottom line of the enhancement is the VB can create Windows
It's a little known fact, but you can write a VB program from scratch using nothing more than a simple text
editor, such as the Edit or Notepad applications which come with Windows. In fact, the Visual Basic project
files are exactly that - text files. However, writing a project from scratch would involve a lot of tedious,
detailed manual entries. To simplify the task, Microsoft has built in to VB a software program to help you
write your VB projects. That software, known as the Integrated Development Environment (IDE for short)
is what comes to the screen when you start VB and is the topic of this section.
Send email to [email protected] <mailto:[email protected]>
06/04/99
• Toolbox
The toolbox is simply a library of controls which you can place on your application. Once you've
placed all the controls you need onto your applications forms, you can hide the toolbox to make
room for working in the other elements of the IDE.
• Project Window
This is simply a list of all the forms which make up your VB project. There are several kinds of
forms which we'll talk about later.
• Property Window
We'll talk about controls later, but such things as push-buttons, scrolling text boxes, pictures boxes
and other features of most VB applications allow you to enter parameters which define how these
controls work. In VB, these parameters are called properties. Some properties can be entered at
design time within the IDE, while others must be entered with code while the program is running.
• Forms
You add these to your VB application as they are needed. They are the windows which hold the
various controls (buttons, text boxes, etc.) which make up your application.
• Code Window
Like it's name implies, this is where you type in the code that VB executes. Notice that the heading
of the window indicates with which event the code is associated.
A VB Session
When VB begins a new project, it starts with a single form which has no controls placed on it. A session in
VB would go something like this:
1. Add additional forms (if needed)
2. Set form properties
3. Place controls on forms
4. Set control properties
5. Write code for form/control event procedures
6. Create executable (.EXE) or simply RUN program within the IDE
7. Save project
It's important to understand that each form in VB is saved as a standalone file on your computer. The listing
of all forms, and their location on your hard disk, are kept in another file which is called the project file. In
VB3 the project file extension was .MAK but in VB6 it is .VBP. This file is just an ASCII text file which
provides information about the VB project. There is a variety of other information which is held within the
file, but all of it is directed towards describing those files (and controls) which make up the VB project.
The end result of most VB programming efforts is an executable program (one that has a .EXE extension).
This file is compiled from the actual text files which make up a VB project. VB doesn't put the entire
project into a single file. Instead, it allows the programmer to break up a project into several smaller files.
Each of these files can be used in more than one VB project. The group of files used to compile the
application is called a VB project and is the topic for discussion in this section of the tutorial.
Send email to [email protected] <mailto:[email protected]>
Project Definition
A typical VB application might consist of more than one forms, each of which may have multiple controls.
In VB, the information about each form (it's own properties as well as those of the controls that are on the
form) is saved into it's own file. In fact, there are several types of files which VB creates (we'll cover them
all later in the tutorial).
VB also saves a "project" file which contains the list of files which VB loads when the "project" is loaded.
The project file includes other information, such as the filenames of controls which are not intrinsic to VB
(they exist as separate files with .OCX extensions).
The project file is a simple ASCII text file and may be edited with any text editor, including NOTEPAD
(which comes with Windows). Once you learn the format of the project file you may have reason to edit it
directly but in general, most programmers do their editing within the VB IDE.
The project file is saved with an extension of .VBP (Visual Basic Project). Other files saved by VB include
the following extensions:
- .FRX : graphics associated with the form
- .BAS : code not associated with control events
The good thing about splitting a project into many files is that you can use a file (form or otherwise) in one
or more projects. If you make a change to the one file, all using projects see the change.
In the following VB IDE example, you see a project with two forms, each with multiple controls. The
filename of each form is displayed in the project window, as is the name of a single .BAS file. Together, all
three files make up the VB project.
Here is the content for each of the files. You will note that the files are in ASCII text. By inspection, you
can guess what a lot of the line items are for.
• Project File
Type=Exe
Form=2ndForm.frm
Reference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#..\WINDOWS\SYSTEM
\STDOLE2.TLB#OLE Automation
Form=testform.frm
Startup="Form1"
Command32=""
Name="Project1"
HelpContextID="0"
CompatibleMode="0"
MajorVer=1
MinorVer=0
RevisionVer=0
AutoIncrementVer=0
ServerSupportFiles=0
VersionCompanyName="Personal"
CompilationType=0
OptimizationType=0
FavorPentiumPro(tm)=0
CodeViewDebugInfo=0
NoAliasing=0
BoundsCheck=0
OverflowCheck=0
FlPointCheck=0
FDIVCheck=0
UnroundedFP=0
StartMode=0
Unattended=0
Retained=0
Visual Basic forms are windows. It's an important piece of data because it ties the concept of a form in with
everything you already know about Windows applications. These rectangular shaped areas of the computer
screen are called windows and the whole strategy of the Windows Operating System is to manage the
display of those windows (while running the code that generates them or which performs calculations in the
background). Since you've already been exposed to other Windows programs, then you already intuitively
understand the concept of a form (window)! This section provides additional details about how VB handles
forms.
Send email to [email protected] <mailto:[email protected]>
04/10/99
What is a Form?
Here's a simple Visual Basic form. It looks just like any other form that you use in Windows applications.
Don't be shocked, but all Windows/NT programs consist of one or more windows. In its simplest form, a
window simply consists of a rectangular area of the screen. Anything that appears inside that area is
considered to be part of the window. However, you can have one window contained inside another.
Controls objects, which are also implemented as windows, will be framed by the form window to which it
belongs. As an operating system, Windows 9.X/NT controls the display of the various, possibly
overlapping, windows on the screen.
In Visual Basic, the basic building block of an application is a form, which is simply a window. The VB
IDE can insert forms into your project, and then you can resize the forms as well as change other properties
of the form.
However, controls (checkboxes, textboxes, ...) are also windows. A form is distinguished from a control in
that only forms can exist as standalone objects. When controls are used, they must be placed in a form. Ok,
there are a few exceptions such as the printer object or the screen object which are not considered part of
any form, but are part of a VB program. I'll talk to these special "system" objects later in the tutorial.
Not to confuse the issue, but controls can also be placed inside of other controls. When this happens the
parent control is known as a container. Likewise, forms are containers but are the highest level of container
there is in a windows application. Forms are always parents of controls, never the other way around.
There is one exception which I will not cover in these tutorials, and that is a special form called an MDI
form. In this special case, an MDI form is always contained within a parent form. This is exactly the same
type of parent/child relationship which you see in Word. Each new Word document is contained in its own
window, but is always framed within the larger window that is the Word application.
The MDI (multiple document interface) forms can be very useful in applications where multiple
files/images/documents need to be open at the same time. Other than this brief mention, I will not cover
MDI forms in these tutorials.
Properties / Events / Methods
Now is a good time to bring up the 3 categories of information which may be used to describe any object,
including forms. Forms, like any object, have properties which you may set. The properties range from the
caption that the form displays to the physical size of the form. Later on this page I list all of the
properties/events/methods that a form recognizes.
Likewise, a form may recognize certain events. All forms recognize the same events, but there are controls
which recognize a broader range of events than forms. Events range from a simple keypress by the user to
the click of a mouse button.
Then, finally, forms and controls also support various actions that may be taken. The actions are known as
methods, and may include such tasks as moving the form, loading it into memory, or refreshing the form to
redraw graphics which may have been overshadowed when one form was placed on top of another.
Remember that even though this part of the tutorial is focussing on forms, that Properties/Events/Methods
apply to all objects in Visual Basic.
Given that there are over 20 controls available to you in the VB Pro edition, you might be concerned that
learning all of the possible properties, events, and methods could be an overwhelming task. However, it's
not at all that bad. Here's a very helpful piece of information that makes your task easier: all forms,
controls, or objects share many of their properties, events, and methods! . Re-read what I just wrote! It's
a very important piece of information and it means you can reuse what you learn about one control to help
you learn about other controls. I've created a control summary chart <controls.zip> which gives the
complete list of VB controls (VB Pro) and lists their properties, events, and methods. The chart is listed in
such a way that you can see the common items, as well as those which are unique to that control. You'll see
that many controls have no unique items at all! In my chart I show 41 common properties, 20 common
events, and 7 common methods. Please note that not every control uses all the common items! Some
common items may be shared by only 2 or 3 controls.
I highly recommend that you look over the chart and become familiar with all of the items on it. I regularly
get questions at my site where the programmer could have performed a desired task by simply setting a
property of the control, if he had just known about it! Just having the chart gives you the ability to look
and see if a control supports a feature that you need.
Detailed descriptions and sample code for using the items can be found in the VB HELP file. There is also a
Microsoft book call "The VB6 Language Reference" which gives additional detail for each of the items.
Quick! How many controls come with VB? Can you list them? Well, it's not as easy as you might think. The
documentation that comes with VB is a bit vague on exactly what is available to you. Even worse, I've
found multiple places in the documentation which don't even say the same thing! Finally, not all that's on
the CD-ROM gets installed on your PC, so you can't simply use the Components dialog box to determine
every OCX control that VB has to offer! Because of that, I've created this part of the tutorial. I still have a
separate section for Intrinsic (built-in) and ActiveX (separate OCX files) controls.
Send email to [email protected] <mailto:[email protected]>
04/11/99
VB comes with 20 built-in controls. In this section of the tutorial I provide a few comments about each one,
Introduction
All controls are not equally useful. Some you will use on every application you write. Others you will use
only when you have a special need for the features the controls offer.
When you start VB, you'll always find the intrinsic controls displayed in the toolbox. The controls are built-
in to the VB files and do not exist in an external file (with a .OCX extension) the way the ActiveX controls
do. In the toolbox, each of the controls has its own distinctive icon.
In the Learning Edition of VB there were only 4 ActiveX controls, but in the Professional Edition of VB,
Microsoft has provided 20 additional controls. Some are very excellent and some you may never use. In this
section of the tutorial I provide a few comments about each one, trying to give some useful pointers on the
use of each control. I strongly suggest that you review the control summary chart <controls.zip>, which
is a zipped Excel spreadsheet that lists the VB controls - along with their properties, methods, and events.
Introduction
As with the Intrinsic controls, not all of the ActiveX controls are equally useful. Some you will use on many
applications but you will use others only when you have a special need for the features the controls offer.
When you start VB, none of the ActiveX controls are displayed in the Toolbox. Only the intrinsic controls
are displayed, so you must manually insert the ActiveX controls into the Toolbox as you need them. To do
so, right-mouse click on the toolbox and go to "Components", select the controls to put on the toolbox and
press "OK".
A little tip - in the startup box for VB you can select to open a project which contains every ActiveX control
that VB installed. You might have missed it because that option is at the end of the list of project types that
VB can open for you when you use the "File/New" menu. Here's a picture of the Toolbox with all of the Pro
controls loaded.
All of the ActiveX controls are contained within OCX files. None are built-in to VB. In some cases,
Microsoft put more than one control into an OCX file. We'll give the file names later.
The Most Useful ActiveX Controls
Of course, everyone will have their opinion but since it's my tutorial I get to give my own opinion for the
most popular Pro controls. These nine intrinsic controls are pretty much used on every VB application I've
written. Start your learning with these and then branch out. Further down on this page I have a brief
comment on each of the controls.
Coolbar Progress Bar
ImageList Tabbed Dialog
Internet Transfer Control Tab Strip
ListView control ToolBar
Multimedia control
The Specialty ActiveX Controls
Some of the VB controls are very excellent tools, but they simply aren't needed in many applications. This
list of controls are ones that would be on my list of the best controls except that they are just not needed that
often:
Communication control RichTextBox
Data Repeater SysInfo
MAPI Winsock
MSChart
The Rest of the ActiveX Controls
Of the remaining ActiveX controls, I find some useful but mostly they sit un-used on my PC. It doesn't
mean they don't perform their features well, it just means that my own applications don't find the need for
the features very often.
Animation MonthView
DateTimePicker PictureClip
FlatScrollBar Slider
ImageCombo UpDown
MaskedEdit
Comments on Each Control
One of the things you'll notice is that I use a few controls a lot, and don't make a heavy effort to use every
available control. I've thought about it a lot and wonder if VB programmers out there are like me, or if
everyone uses their favorites over and over? You'll have to decide for yourself which approach makes
sense. In the comments that follow I provide some of the logic which pulls me to one of these controls, or
what it is that keeps me away!
• Animation Control
Personally, I don't do games and I find animation in business programs to be of marginal value
In this section I'll cover the topic of coding - the use of the Visual Basic language. As part of this section I'll
try to show you which elements of the language you need to know the most, and which elements work
together. Even more than you saw with some of the intrinsic controls, there are groups of the VB language
which are almost always used together because they cover different aspects of a problem.
Send email to [email protected] <mailto:[email protected]>
03/26/99
Overview
It's worth noting that when managers talk about programmers, one of the common metrics used to describe
performance is "lines of code per month". There's all kinds of debate about how good a metric this is, but
the fact is that the metric is used!
It's not that you don't get credit for novel algorithms, or that you won't be a hero to fellow programmers
when they see how you solved a problem with 10 lines of code that took them 100. You'll get that credit
(and mental satisfaction, too!) but looking at the big picture it's clear that the volume of code you can crank
out will be the visible result of your efforts!
Let's walk again through the elements of writing a VB application. The percentages at the right are an
estimate of how much time a programmer might spend on the various phases of the program. For short
programs, a greater percentage would be spent on the concept and user interface phases. For larger
programs, more time will likely be spent on the later phases. However, in either case you can see that the
coding section is one of the key areas in which a programmer will be spending his time.
• Concept / Requirements Definition (10%)
• User Interface Design (20%)
• Coding (50%)
• Test & Debug (20%)
• Customer Acceptance / Evaluation (10%)
Get the picture? If you want to be a great programmer, you have to know how to code!
There's another aspect to coding that you need to be aware of, but it's a little harder to explain. In the
electronics manufacturing business there's a saying that 90% of the cost of a product is determined in the
design. Can you see the link? Writing a program is essentially a design task, aimed at solving a problem.
Like most things, there are many design approaches for every problem. Some solve the problem by grinding
out an answer. Some are very elegant. Others are so complex that even the designer has a hard time keeping
up with the convolutions of the approach.
Remember that in my Beginner's Section <begin.html> I harped on the idea that a programmer's job was
to economically provide the result for which he is being paid. A customer will be more impressed by a job
done on time, on budget and which meets spec than he will be for a project with overruns because of bells
and whistles (or unusual code) which do not improve the utility of the application to him or his employees.
You'll get this kind of philosophy to programming throughout this tutorial.
Let's see if we can tie all this together now.
1. Great programmers must be coding experts
2. Great programmers understand that there are many approaches to a problem
3. Great programmers work efficiently. Remember my Rule 4! <begin.html>
As I go through the rest of the tutorial I'll try to show how these principals can be applied to real life
decisions and solutions.
9. VB Command Descriptions
In the earlier lesson you were introduced to coding, and reviewed a chart which groups VB commands into
useful categories. In this section of the tutorial, I take each one of the commands and provide the syntax and
a brief description of what the command does. For details, you can turn to the VB HELP file. My intent is
to allow you to skim quickly over the commands to determine which one can help out in your situation. This
page is kind of long, but I wanted to keep it all on one page to make it easier for you get scroll through it.
I've also summarized the contents of this page in a command summary chart <tut-chrt.html>.
Last updated 04/03/99
Send email to [email protected] <mailto:[email protected]>
Operators
Here are the VB operators used to perform mathematical operations on one or more variables. Aside from
the normal multiply/add/substract and divide, you will find the AND, OR, Not Equal, MOD and Integer
Division operators very useful.
• / - Normal division
• \ - Integer division (truncates the answer)
• ^ - Exponentiation operator
• * - Multiply
• + - Plus
• - - Minus
• = - Equal
• > - Greater Than
• < - Less Than
Fact is, that few of the VB commands stand alone. More often than not, a command supports only one
aspect of a topic. For example, the OPEN command opens a file so you can read it, whereas the LINE
INPUT command reads one line of data at a time. And so it is in all of the areas of capability which VB
supports. This page provides my own interpretation of VB command grouping. The benefit to you is that
when you have a task to do you can quickly see which commands to consider for the task!
Don't confuse VB commands with control properties/events/methods! In this section I cover only those VB
language elements which are not associated with specific VB objects.
Send email to [email protected] <mailto:[email protected]>
-----------------------------------------
-----------------------------
Declarations Date/Time
-----------------------------------------
-----------------------------
Sub Call Set Date MonthName
Function CallByName Let Time WeekDayName
Dim PropertyGet Event Now Day
ReDim PropertySet ArrayName Timer Hour
Static PropertyLet Implements DateAdd Minute
Public Option Explicit Friend DateDiff Second
Private Option Private Enum DateSerial TimeSerial
Const Option Compare TypeName DateValue TimeValue
Declare Type...EndType VarType Year WeekDay
Is GetObject DefType... Month
CreateObject
GetAutoServerSettings
------------------------------------------------------------------------
---
LOOPS AND CONDITIONAL
------------------------------------------------------------------------
---
IIF For i=1 to j Step k If_Then_Else Select
Case
End - Case
Stop Next i If_Then Case IS
cond
Switch ElseIf_Then Case _
TO _
GoTo... While cond Else Case
Else
GoSub...Return - EndIF End
Select
On...GoSub Wend
On...GoTo
Choose Do While | Until cond For Each
With - -
Exit Function Loop While | Until cond Next
Exit Sub
Exit Do
Exit For
The usual model for all computer programs is that a user inputs data and the computer saves it. Okay,
there's a lot more than that to a computer program, but the point is that virtually every program is written to
save data that is entered or data that is calculated by the software itself. If you want to be an expert VB
programmer then you'll need to know a lot about how VB handles files - what is possible and what is not,
plus how to do something in the smallest code or in the least amount of time. To do this you need to
understand the file handling features which VB offers.
Send email to [email protected] <mailto:[email protected]>
05/20/99
12. Printing
Let's amend the computer program "model" which I gave in the tutorial section on file handling. A
computer program basically consists of a user who enters data, a file in which the data (or calculated
results) are stored, and a paper copy of the data. The printed copy is usually formatted in such a way as to
allow the user to make sense of the data. The point of this short essay is that most users expect to be able to
get a hard copy (meaning a paper copy) of their data. They want it stored, but they also want to be able to
take the results away from the computer for subsequent review. Hence - printing! An important fact is that
how well the data is presented to the user can make or break the success of the application. Learning to use
the printing tools of VB is critical to your success as a programmer.
Send email to [email protected] <mailto:[email protected]>
04/11/99
Introduction
For those of you who remember BASIC printing, the news with Visual Basic is both (mostly) good and (not
much) bad. With BASIC and before the advent of the proportional fonts of Windows it was easier to figure
out where your print statements were going to put the output. Since every character took up the same width,
you only had to count positions (80 per line) as part of figuring out how to code print statements.
The bad news with DOS BASIC was that you had to print one line at a time. You couldn't print line 40, then
go back to line 10. The really good news is that in Visual Basic, an object known as the printer is available
to you. The printer is like a work space to which you can direct the output of print statements or the output
of graphics statements. You can send text/graphics output to the printer object in any order you want, then
when you're done you can tell Visual Basic to print the material to a physical printer.
The other good news about Visual Basic is that you can also "print" inside an applications window (a form
or a picture control) and Windows will handle the movement of the printed output as you move windows
around or as you move other windows in front of the printed material. With DOS BASIC you had to handle
all of that yourself!
The (almost) bad news with Visual Basic printing is really a Windows issue. Although there are non-
proportional fonts (same width for each letter) in Windows, they really don't look professional. So most
folks program the print statements to use proportional (different width for each letter, to enhance to display
of the text) fonts. The downside to this is that since each character is not the same width, you have to
specify the X/Y coordinates of the print location.
VB has some tools to make it a little easier than I make it sound, and the conveniences of the printer object
really do outweigh the inconvenience of handling proporational fonts.
Printing Surfaces
Ok, I've mentioned that in VB you can "print" to more than just a physical printer. In fact, you can print to a
form, to a picture control, to the DEBUG object (more on this in another section) and also to any physical
printer connected to your PC or to any shared network printer to which your PC is connected.