Learn Visual Basic E-Book
 

About the Author
Chuck Easttom

 

   Chuck Easttom is a software developer and author.  You can get to his homepage at www.chuckeasttom.com  He currently holds over 20 different computer industry certifications and is continually working on more. He lives with his wife Misty, his son AJ and their two cats Sagan and Monte.

     In his spare time (when he is not working, researching, or reading a computer book) Chuck likes to play chess, read voraciously and is a very bad golfer.  You can find him on his home web site (that also has a pretty decent VB web site) at www.chuckeasttom.com

Here is a picture of the author at work at his computer (Well Sort of…)


 

Introduction

     This book is meant for the beginner.  Its primary purpose is to get you up and writing programs in the shortest possible time.  For that reason I take a very practical approach (thus the title).  My goal is that you be able to function as a competent Visual Basic programmer in at the end of this book, and write useful programs.  That means that I don’t go in depth into theory, or into advanced topics.  However this book should provide you with the ground work necessary to move on to more advanced programming topics. While some of the code examples and lessons can be accomplished with Visual Basic 4, 5, or  6, much will require Visual Basic 6.0.


 

   When you see the icon It denotes a tip that can save you a lot of cursing at your code!

New in this edition:

   Several things are new in this 3rd edition.  The first, and most obvious, are the increased examples.  More examples added to several chapters.  Then we have the chapter on object orientation reworked and clarified.  Finally a few  completely new chapters have been added including a chapter on building your own Active X controls and building your own Active X dll’s. About 30 extra pages are in this edition

    There have also been a few formatting changes.  All the examples are now highlighted so they can more easily be found.

  

Table of Contents

Chapter 1    Introduction to Visual Basic…………………………4

Chapter 2    Introduction to Database Programming…………….29

Chapter 3    Essentials of Writing Code…………………………56

Chapter 4    In Depth VB Coding………………………………..84

Chapter 5    Object Oriented Programming…………………….111

Chapter 6    VB Printing and More……………………………..136

Chapter 7    ADO……………………………………………….159

Chapter 8    Active X Dll’s…..…………………………………179

Chapter 9    Active X Controls…………………………………185

Chapter 10  TCP/IP programming………………………………190

Appendix A  Keywords………………………………………….193

Appendix B  Controls……………………………………………196

Appendix C  Other Resources…………………………………...201

Appendix D  DDE & OLE………………………………………206

Appendix F Ten Commandments of Coding…………………….214.

 

Chapter One
Introduction 
to
Visual Basic
 

 

 

 

 

 

 

Chapter Objectives:

 

Ø       Understand Controls and form

Ø       Understand Events

Ø       Understand Control Properties

Ø       Become familiar with terminology

Ø       Become comfortable with the development environment

 

Chapter 1:  Introduction

     This chapter is designed to introduce you to the essentials of Visual Basic.  At the end of this chapter, you should have a basic understanding of forms, controls, properties, and events.  You should also be getting comfortable with the programming interface and know how to move around in the tool bar, tool box, and drop down menus.


    When you first launch Visual Basic you will be confronted with a screen that asks you what type of application you wish to make.  For now we will always start with the first option “Standard EXE”.  This denotes a Standard Executable or program.  When you select this, you will then see the following screen:


   This is referred to as the IDE or Integrated Development Environment.  The top of the screen has the drop down menus and the tool bar.  These contain various functions you will use when programming.  Functions such as saving, running, and debugging your program.  The tool bar looks like this:

       

     The buttons on this toolbar are shortcut keys for common tasks.  The first button will open a new form for you to use.  You will be prompted to see if you want a blank standard form or one of the pre-made forms that Visual Basic starts with. The second will give you a new blank code module.  The third will give you a standard windows dialogue box, allowing you to open an existing file.  The fourth will save your current work.  Towards the middle of the toolbar is a button with an image of an arrow pointing to the right.  This causes your current project to run.  Next to it are pause and stop buttons.

  

     Immediately above it is the drop down menu.  If you click on the drop down menu, a menu will drop down with other options you can click on.  The tool bar simply provides rapid access to some of the most common functions in the drop down menu.


     The window on the right is the properties window (see above).  The window on the left is the toolbox (See below).   The large gray area in the middle is a form.  A form is where you lay out your programs visual interface.  The interface the user sees is referred to as a Graphical User Interface or GUI (Pronounced G-U-I or “gooie”).

   

     Also, note that at the top of the title bar is the name of the project you are working on.  Visual basic gives the new project the default name of “Project1”.  You will probably want to go to the drop down menu “File” and select the option “Save As” and save your project under a name that is more appropriate for the application you are developing.

     Visual Basic is a RAD or Rapid Application Development tool.  This means that you can develop professional applications much faster than you would with some other languages (C/C++, Pascal, COBOL).   The way Visual Basic accomplishes this task is by giving you templates for most common items a program might need.  You then merely change certain facets of the template to make it do what you want.  These templates are called controls and can be found in your toolbox.

    The facets of a control that you can change are called properties and are found in the properties box.  You can access the properties box by clicking on “View” on the drop down menu at the top of your screen and then clicking on properties, or just by pressing the F4 key.  It is important to realize that the properties window will display properties for whatever control currently has focus.  You change focus by clicking once on the control you wish to have the focus.  The properties are all listed in alphabetical order with the exception of the name property that is listed first.  It is vital that you realize that the name property is what the computer will call your control, not what the user will see.  The user will see the caption property (for those controls that have one.) Here is an example of a property window:


 

   You can simply drag a control from your toolbox and then place it on the form.  You then drag it to any spot on the form you want to place it. You can also simply double click on a control in the tool box and it will appear in the center of the form. All controls can also be stretched to alter their size.  After you have placed the control on the form you can then proceed to set the properties in the properties window.  Below is a picture of what a form looks like:


Common Controls and their properties

Some controls are used more often than others.  The form is the most basic control.  It is the container in which you place all the other controls.  It is also what your user will see.  The most important properties you will set for a form are its name (What the computer will call it); its caption (What appears in the title bar that the user will see), and  its back color (what color do you want the background to be).  You may also wish to set its border style (this determines if it can be resized by the user or not).  Below are listed some other common controls and the properties you will be most concerned with:


Text box:  This control allows the end user to enter data.  You will want to set its name (What the computer will call it), its text (the default text that initially appears when you run the program), and possibly its font if you wish a different font in the text box.  You can also enter something into the text property as a default text. Finally you may want to set its max length property.  This determines the maximum number of characters a user can type into the text box. You can also set its password character property to denote a symbol to show in lieu of passwords.  The multi-line and scroll bar properties allow you to have a text box that can handle several lines of text.

Label:  Labels are used to display information to the end user, but the end user cannot change any information in the label.  The properties you will set in this control are the name (What the computer will call it), its caption (what will the user see), and its font.

Command Button:  Command buttons allow the user to click a button.  A lot of the code that you write will be associated with command buttons.  The properties you are most interested in are: its name (What the computer will call it), its caption (What the user will see), its style (Will your button have a text caption or a picture, if you choose the graphical style you must set the caption equal to nothing and select a picture in the picture property) , and its font.


 

List Box:  A list box simply allows you to list items for a user to select from.  The property you are concerned with is the font.  The items are listed using code and will be discussed later.

Combo Box:  This is like a list box but you can set more options.


 

Picture box:  Using this control you can place any bitmap (*.bmp), Windows MetaFile (*.wmf), or icon (*.ico) on your form.  Starting with Visual Basic Version 5.0 you can also add in JPEG (*.jpg) and GIF (*.gif) image files.  All you do is set the stretch property to true (that ensures that the picture you insert will be the size of your picture box) and then use the picture property to select the picture you want to use.


 

Frame:  A frame is basically a container control.  It is used to group other controls.  The property you will use most with it is its caption.


 

Font:  Many controls have a font property that lets you select the font for that control.  Below is what you will see if you select the font property of any control:


 

    A lot of the programming you do will be concerned with using code to alter the properties of some control.  The way you do this is you write the control name you wish to alter followed by a period then the name of the property you want to change.  A generic example of this is: 

                        Controlname. Property = “whatever”

 

A specific example is:

                         Text1.text = “Howdy”

                         Form1.caption = “This is my form”

                         Picturebox1.image = “c:\folder\image.bmp”

                         Data1.recordsource = sSQL

                         Label1.caption = “This is a label”


  Tip:  If your code referencing a property does not work, it is most likely because you misspelled either the control or the property name.

 

Using this basic technique, you can write code to change the properties of any control you want.  This is important to remember since much of the code you write in Visual Basic is concerned with altering the properties of various controls.

Example 1-1

Lets try a simple project right now.  Start up Visual Basic (If you are using VB 5 or 6 then choose “standard.exe”).  It should start off with one form in view.   If you don’t have the tool box in view, then you can go to the drop down ;menu and select “View” then select “toolbox”.

Now on that form place 1 list box, 1 text box, and 1 command button.  In the properties window (either select “view” and “ properties” or press the f4 key) change the command buttons caption to “add text”. Now if you will double click on the command button you will get its code window. 

Now go to the “click” event.  In it place this code:

List1.additem text1.text

Now run your program.  You can do this by clicking on the run button in  the toolbar, it looks like a play button on a CD player or by using the f5 key. You will be prompted to save it and give it a name.

Now every time you click on the command button, whatever you have typed into the text box will now be added to the list box!

It is important to note that every control has a default property.  That is essentially its primary or most important property.  If you refer to a control and do not specify the property you wish to refer to, Visual Basic will assume you intend to refer to the default property.  For example, you could write the code above as:

                       Text1 = “Howdy”

Since the text property is the default property for the text box.  However, in this book we will always explicitly state the property we are referring to.

Note: An event is just a function that the user calls by doing some action.

 

 

Glossary:

     The following is a list of standard Visual Basic and programming terms that you will need to be familiar with.  In programming, proper nomenclature (or naming) is simply vital.  You cannot understand instructions and you cannot communicate with other programmers without an understanding of proper nomenclature

Project:  This is all the files in your program.  It includes forms, code modules, class modules, etc.

Forms:  This is the control on which you place other controls and design the User Interface.

Controls:  These are the various objects or templates that Visual Basic has for you to use in your program.  Examples are the textbox, command button, list box, combo box, and picture box.

Code:  This is the actual programming that you write. 

Bug: an error in your program.

Debug: to remove errors in your program

Event:  This is something the user does.  The click event is a good example.

Sub routine:  A sub section of code.  Events are pre made subroutines in Visual Basic.

Code Module:  A module of separate sub routines completely separate from a form.

IDE:  Integrated Development Environment.

Application:  A fancy word for the program you write

Statement:  A single line of code that performs an action.

Function:  A group of related statements that perform some action

 

The Drop Down Menu:  

The drop down menu gives you access to several possible functions.  On the next page are listed the main drop down options you see at the top of your screen and several of the sub options along with their functions.  I do not cover all of the drop down menu options, only the ones that you as a beginner need.  We will cover others later in this book.

 

File:

New Project:  This opens a new blank project for you to begin working with

Open Project:  This allows you to open an existing project.  When you select this option, you will see a dialogue box that you can use to browse your computer to find the project.

Save Project As...: This allows you to save the project your working on under some name you select and in a folder/directory of your choosing.


Tip:  Be very careful of what name you give your project and where you save it to.  Putting all of a project's files (including database files) in a single folder with an appropriate name is the best idea.

 

Save Project:  This will save the project you are working on under the last name you gave it and in the last location you saved it to.

Save Form:  This works just like the Save project option, only it saves the specific form that currently has focus.

Save Form As:  This option will allow you to save a specific form under a name of your choosing and in the folder/directory that you select.



 
Tip:  As with the “Save Project” As option you want to make sure you are saving these forms (and any other project files) to the same location

Print:  This allows you to print the source code for your project.

Make exe:  This makes an executable program from your source code.

Exit:  This will exit Visual Basic


Edit
:

Undo:  This option allows you to undo whatever action you last performed.


              Tip:  The Undo option exists in most windows programs.  If you do something you wish you had not done, don’t freak out.  Simply go to “Undo”

 

Redo:  This will let you redo whatever action you last used undo on.

Cut:  This will cut the code or the control you have selected and place it on the clipboard.

Copy:  This works much like the cut command except that the original is still in place.

Paste:  This command lets you paste something that you have previously copied or cut.

Find:  You can enter a key word and search all  your project for it.

Find Next:  It finds the next instance of whatever you last used find for.

Replace:  This will go through your code replacing one word or phrase with another.

View:

  Tip:  I always hear at least one student in  panic yelling “I can’t find (project/form/code module/etc.). You probably just need to go to “View” and select that object to view.

Code:  This will give you the underlying code for any object that currently has focus.

Object:  This lets you view the object of the code you are currently viewing


Project Explorer:  Selecting this option will give you the window with a listing of all files in your project.  It looks like this

Properties Window:  This shows you the properties window.  It will usually appear to the right hand side of the IDE.  You can get to it using the drop down menu option “View” and then “Properties” or the shortcut key “F4”  It will display the properties of whatever control currently has focus.


 

Tool Box:  You can use this to make your tool box visible. This is usually on the left hand side of the IDE


 

Project

Add Form:  This lets you add a new form to your project.  When you select this, you will be prompted as to what type of form you wish to add.  You will often select the blank form option, but Visual Basic has a number of pre made forms you may want to use.

Add Module:  This option lets you add in a  blank code module.

Add Control :  This is another  way to add in a control

Remove:  This will remove whatever currently has focus, be it a form, control, or code module


Components:  Visual Basic has many more controls than you see in your toolbox.  This option lets you select which controls you want to see in your toolbox.  If you select this option you will see a window like the one below from which you can choose which controls you want available for your project:

Run:

This window simply lets you either run your program, pause it, or stop it.

Help:

This will let you ask questions and look up topics from Microsoft help.


            Tip:  Microsoft has included an awesome help file.  If you ever see a keyword you don’t understand look it up in the help file.  You can learn a lot from the help file.  Each version of VB seems to have an even better help file.  VB 6.0 has an incredible help file.

Short Cut Keys:

    The following are a few of the most commonly used shortcut keys.  You may want to memorize them.

    F7:  View the Code window of an object

    F4:  View an objects property window

    F3:  Find

    F5:  Run  

    CTRL Z: Undo

    CTRL C: Copy

    CTRL X: Cut

    CTRL V: Paste

  


Short Cut:  You can also right click on your mouse and a pop up window will display the more commonly used functions. The window looks like this:

Events:

     Events are things that happen.  If you double click on any control you will be looking at an event, specifically the default event for that control.  The default event for the Command Button is the click event.  This means that any code you place in here will be executed when the user clicks that button.  Let's do an example.  Place a label on your form.  By default, it will be named label1.  Then place a command button on your form.  By default, it will be named command1.  Now double click on the command button so you can view the code in the click event.  You should see something like this:

   Private Sub Command1_Click()

 

   End Sub

 

All events are subroutines that Visual Basic has already defined for you.  You must place code between these two lines.  If you write code before the “Private Sub…” line or after the “End Sub” line, you will get an error.   Below is a picture of the form load event:


 

 

Now lets put some code in our command1 click event:

     Private Sub Command1_Click()

            Label1.caption = “Howdy”

     End Sub

 

Now let's run our program.  You can do this by selecting the button in the middle of the tool bar that looks like a blue arrow pointing to the right.  You can also do this by pressing the F5 key, or by going to the drop down menu and clicking on “Run” then clicking on “Start”.  You will be asked if you wish to save your new project and your form.  If you select “yes”, you will be prompted to name the project and the form.  You will also be prompted to select a location in which to save them. 

 

Once the program is running, click on the command button and see what happens to the label.  You should see the word “Howdy” appear in the label.  This may seem rather simple, but you will see that a great deal can be accomplished merely by changing properties in your code.

 

When a user causes any event to occur then the code that you have placed inside the subroutine for that event will be initiated.  If there is no code inside the events subroutine then nothing will occur.  All events begin with no code.  You must place the code in them.

 

Each control will have several events you can choose from.  Each event corresponds to an action that the user takes or to something that happens in the program.  Below are some common events found in many controls and what they mean:

 

Click:  This event is triggered whenever a user clicks that control.  (this is most often used in command buttons, list boxes, and combo boxes.)


Tip:  A lot of your code will be in click events.  However, when you first open up a command button the first event displayed is the change event.  I have seen lots of beginners put some nice code in an event and the spend hours trying to find out why it won’t work, only to find they put the code in the wrong event.

 

Double Click:  This event is triggered whenever a user double clicks on that control.

 

Mouse Move:  When a user passes the mouse over a control this event is triggered.

 

Get Focus:  This event is triggered when you first give focus to a control either by clicking on it or by tabbing to it.

 

Lost Focus:  This event is triggered when you have had focus on a control and then attempt to move focus from that control.

 

Load:  This event is only in the form control and it is initiated when the form is first loaded.

 

Naming Conventions:

    Microsoft has established some naming conventions you should use when naming controls.  This makes for a more uniform code that is easy to read.  By default each of your controls will have a name like: text1, label1, command4, etc.  You must go to the “name” property of each control to change its name.  Naming conventions simply make it much easier for another programmer to see what you are doing. Below is a chart of some Microsoft naming conventions:

 

Control Type

Naming Convention

Text Box

TxtWhatever

Command Button

CmdWhatever

Label

LblWhatever

Panel

PnlWhatever

Frame

FraWhatever

Combo Box

CmboWhatever

 

 

 

List Box

LstWhatever

 

Using these naming conventions will make reading your code much easier.

Yes I realize that it is easier and faster to just leave your controls with the default name.  And while you are working on simple projects it won’t really matter.  But when you have to work on real world applications do you really want to spend time trying to figure out that text1 refers to the account number when you could simply have named it txtAccountNum to start with?

 

Example 1-2

  The following is a very simple program that will allow you to build an image viewer.  The program is simple but lets you see how controls and their properties can be used.

First, start a new project with a single form on it.  On that form you will want to place a drive list box



 directory list box



 and a file list box



You will also need to place a picture box on the form


 

Now in the change event of the drive list box place this code:


Sub drive1_change ()

    Dir1.path =drive1.drive

End sub

This will cause your directory list box to look at those directories that are on the drive, you drive list box points too.

 

Then in your directory list box change event place this code:

 

Sub dir1_Change()

     File1.path =dir1.path

End sub

 

Now your file directory list box will only look at files in the same directory that your directory list box is pointing too.
 

Now how do we make pictures appear?  And what type of pictures do we want to look at?  Well that’s the next step.  At the top of your form place 4 command buttons.  One will have the caption “Bitmaps”, the second will have the caption “Meta Files” , The third “Gifs”, and the fourth “Icons”.  Name each command button appropriately (cmdbmp, cmdwmf, cmdgif, and cmdicon.)

Now in the click event of each we will place some code:

 

Cmdbmp_click()

 

   File1.pattern = “*.bmp”  ‘when you click this button the file list box will show only

                                            ‘maps

end sub

 

cmdwmf_click()

 

    file1.pattern = “*.wmf”

 

end sub

cmdgif_click()

 

         file1.pattern = “*.gif”

 

end sub

2

cmdicon_click()

 

          file1.pattern = “*.ico”

 

end sub

 

Note:  You should also place a default file pattern in your form load event:

 

Form1_load()

           File1.pattern = “*.bmp”

End sub

 

Now for the slightly complex part (Don’t Panic I said slightly!!).  We need to put the real meat of this little program into the file list boxes. Click event:

 

File1_click()

Dim graphic

   If right(file1.path,1) <> “\”  then

         Graphic = file1.path & “\” & file1.filename

  Else

         Picturgraphic= file1.path & file1.filename

  End if

 

Picture1.picture = loadpicture(graphic)

 

End sub

 

Basically, this code just says to point at the file that the file list box is currently on and place that picture file in the picture box.  But you have now built a simple program with virtually no writing of code!

 

Some Notes:

    Always start by creating a new folder to put all your project files in.  This folder should contain all the files you need to do this project.  That means any forms (*.frm), Code Modules (*.bas), Class Modules (*.cls), Project Files (*.vbp), or databases (*.mdb)

 

Conclusion:

     Visual Basic is referred to as an “Event Driven” programming language because all the code is triggered by specific events that the user performs.  This puts the user firmly in control of how the program flows and therefore increases user satisfaction with the program. 

 

     The key portions of a Visual Basic project are the forms, controls, and code modules.  A form or control has properties that you can alter.  The program’s code is contained primarily in events.

   

Additional Practice Exercises

 

Example 2-3

 

    Step 1: Start a new project with a standard executable.

    Step 3  place 1 text box and 4 labels on the form. Set the label captions to blank and their border styles to 1.

    Step 4: place 1 command button on the form.

    Step 5: Change your forms caption to read “String Stuff”

    Now your form should look like this:

 

In the click event of the command button place the following code:

Dim mystring as string

 

Mystring = text1.text

 

Label1.caption = ucase(mystring) ‘ display the upper case version of the string

Label2.caption = lcase(mystring) ‘display the lower case version of the string

Label3.caption = len(mystring)    ‘ display the length  of the string

 

Now run the application.

 

This exercise gives you more practice placing controls on forms and using control properties.  It also introduces you to some of the many functions built in to Visual Basic.

 

Exercise 1-3

 

1.      Again we need a new executable with a single form.  This forms caption should read “Math Made easy”

2.      Place 1 textbox on the form and two frames.  The first frames caption will be “Trig Functions”, the Second “Other Math functions”.  The first frame will have 6 labels and the second frame will have 4.  Those labels will be given a border.  Then some borderless labels will be placed by them with captions.  Your form should look like this:

3.      You will place two command buttons on the form.  One with the caption “trig functions” and the other “other math”.  Your form should then look like this:

 

Then in the command button with the caption ‘trig functions’ you will place this code:

 

Dim mynumber As Double

mynumber = Val(Text1.Text)

 

Label6.Caption = Sin(mynumber)

Label7.Caption = Cos(mynumber)

Label8.Caption = Tan(mynumber)

Label9.Caption = Atn(mynumber)

 

 

And in the other command button you will place this code:

 

Dim mynumber As Single

mynumber = Val(Text1.Text)

 

Label1.Caption = Sqr(mynumber)

Label2.Caption = mynumber * mynumber * mynumber

Label3.Caption = Abs(mynumber)

Label4.Caption = Log(mynumber)

 

Now run your program, place a number in your text box and press your buttons.  This exercise is designed to give you even more practice with Visual Basic controls, and also to introduce you to some of Visual Basic’s built in math functions.
 

Review Questions:

 

1.      What is a property?

 

2.      Name 3 properties of the text box

 

3.      What is an event?

 

4.      What is the default event of the command button

 

5.      Name 4 controls

 

6.      Give an example of code that changes another controls property.

 

7.      What is the mouse move event?

 

8.      What does GUI mean?

 

9.      What does IDE mean?

 

10.   How do you add controls to your tool box?

 

11.  What is a bug?

 

12.  What is the default property of a text box?

 

13.  What is the drop down menu option to add new controls to your toolbox?

 

14.  Give the functions of at least 2 buttons on the tool bar.

 

15.  What is the difference between “Save” and “Save as”

 

16.  How do you remove a form from a project?

 

17.   What is the shortcut key to get to the properties window?

 

18.  What is the shortcut key to make the program run?

 

  Chapter Project # 1:  

   Make a standard executable(.exe) with 1 form. Place a label on the form.  On that form place a command button with the caption “Press Me”.   In the click event of that command button place code that will change the labels property to “Ahh that’s good”. The save the project under the name firstapp.vbp and run it.

 

Chapter Project #2:

   Create  the picture viewer outlined earlier in this chapter.  It should allow the user to view at least 4 file times, but you could have more.

 

Chapter Project #3:

  Create a program with a single form that allows a person to type text into a text box, then click on a command button and have that text display in a label.