You are on page 1of 45

Programming Fundamentals

of
Visual Basic 6.0

Level 1
Table of Contents

Programming Fundamentals of Visual Basic 6.0


Table of Contents

INTRODUCTION .................................................................................... INTRO-1


A Few Words About This Courseware......................................... INTRO-2
World-Class Courseware Taught by World-Class
Instructors........................................................................ INTRO-2
What We Expect of You................................................... INTRO-2
What Youll Get Out of this Class..................................... INTRO-2
Courseware Conventions................................................. INTRO-3
The Practice Files........................................................................ INTRO-4
About the Author ......................................................................... INTRO-5

YOUR FIRST VISUAL BASIC PROGRAM........................................................1-1


Welcome to Visual Basic! ......................................................................1-2
The Big Picture ..........................................................................1-2
What Exactly Is a Visual Basic Program? ..................................1-3
A Simple Project....................................................................................1-8
Creating the Simple Project .......................................................1-8
Using the Application Wizard...............................................................1-26
What is the Application Wizard? ..............................................1-26
Running the Application Wizard ...............................................1-26
The Aftermath..........................................................................1-37

LAB 1: YOUR FIRST VISUAL BASIC PROGRAM .........................................1-41


Lab 1 Overview ...................................................................................1-42
Create and Run a New Project ............................................................1-43
Changing a Forms Properties.............................................................1-46
Add a Control to a Form ......................................................................1-49
Write Some Code ................................................................................1-51

ADDING CONTROLS TO FORMS ...................................................................2-1


Visual Basic Controls ............................................................................2-2
What Are Controls? ...................................................................2-2
Types of Controls.......................................................................2-2
Creating and Manipulating New Controls ..............................................2-3
Drawing a New Control ..............................................................2-3
Moving a Control........................................................................2-4
Resizing a Control .....................................................................2-5

Programming Fundamentals of Visual Basic 6.0 TOC-1


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

Changing Design Time Control Properties ............................................2-7


Using the Properties Window.....................................................2-7
What Properties Might You Change?.........................................2-8
Using Naming Conventions .....................................................2-10
Visual Basic Built-In Controls ..............................................................2-11
Control Design Tips.............................................................................2-17
Manipulating Multiple Controls .................................................2-17
Using Visual Basics Formatting Commands............................2-18
Drawing Controls Inside Other Controls...................................2-20
Control Drawing Tips ...............................................................2-21

LAB 2: ADDING CONTROLS TO FORMS .....................................................2-27


Lab 2 Overview ...................................................................................2-28
Insert Text Boxes and Labels ..............................................................2-29
Add an Option Group ..........................................................................2-34
Work with the Image Control ...............................................................2-38

UNDERSTANDING EVENTS ...........................................................................3-1


Introducing Events.................................................................................3-2
Interpreting the Log Form Data ..................................................3-3
How Does frmLogEvent Work?..................................................3-3
Event Procedures..................................................................................3-5
The Form Load Event............................................................................3-7
The Form Resize Event.........................................................................3-9
How Does It Work?..................................................................3-10
Command Button Click Event..............................................................3-12
Text Box Change Event.......................................................................3-14
The Timer Controls Timer Event.........................................................3-16
GotFocus/LostFocus Events ...............................................................3-19
Is There More?....................................................................................3-21

LAB 3: UNDERSTANDING EVENTS.............................................................3-27


Lab 3 Overview ...................................................................................3-28
Create a Digital Clock (Timer Event) ...................................................3-29
Create an Analog Clock (Timer Event) ................................................3-31
Initialize the Form in the Load Event ...................................................3-33
Close the Form from the Click Event ...................................................3-35
Maintain the Buttons Position from the Resize Event..........................3-37

TOC-2 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

WORKING WITH FORMS AND CONTROLS ...................................................4-1


Setting Properties at Run Time..............................................................4-2
Setting Property Values .............................................................4-2
Retrieving Property Values ........................................................4-2
Setting Form Properties.........................................................................4-4
Changing the Caption ................................................................4-4
Changing a Forms Mouse Pointer.............................................4-5
Setting Control Properties .....................................................................4-6
Data Entry Controls ...................................................................4-6
Responding to Keystrokes .........................................................4-8
Sharing Key-Handling Code.......................................................4-9
List and Combo Boxes.............................................................4-10
Using ActiveX Controls........................................................................4-14
Where Do ActiveX Controls Come from?.................................4-14
What Can ActiveX Controls Do? ..............................................4-15
Can I Use Every ActiveX Control on my System? ....................4-16
Deploying ActiveX Controls .....................................................4-16
Adding ActiveX Controls to a Project ...................................................4-17
Using the Components Dialog Box ..........................................4-17
A New Tool in the Toolbox! ......................................................4-18
Using the MonthView ActiveX Control .................................................4-19
Adding ActiveX Controls to Forms ...........................................4-19
Using the Properties Window...................................................4-20
Using Custom Property Pages.................................................4-21
Working with ActiveX Control Events .......................................4-22
Getting to Know an ActiveX Control .........................................4-23
Extra ActiveX Samples (On Your Own) ...............................................4-25
Using the Common Dialog Control...........................................4-25
Using the Web Browser Control...............................................4-26

LAB 4: WORKING WITH FORMS AND CONTROLS.....................................4-35


Lab 4 Overview ...................................................................................4-36
Work with Text Boxes..........................................................................4-37
Use a Combo Box ...............................................................................4-41
Add an ActiveX Component ................................................................4-45
Use the Object Browser.......................................................................4-47
Draw the Control .................................................................................4-52
Write Event Code to Handle an Event .................................................4-55

Programming Fundamentals of Visual Basic 6.0 TOC-3


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

CREATING AND USING MENUS.....................................................................5-1


Menus in Visual Basic ...........................................................................5-2
Menu Basics ..............................................................................5-2
Using the Menu Editor...........................................................................5-4
Creating a New Top-Level Menu Command ..............................5-4
Saving Newly Created Menu Commands...................................5-5
Setting Menu Command Properties ...........................................5-6
Changing Menu Structure ..........................................................5-7
Menu Design Conventions.........................................................5-8
Working with Menus ..............................................................................5-9
Menus are Controls ...................................................................5-9
Menu Events..............................................................................5-9
Manipulating Menus at Run Time ........................................................5-10
Reusing Menus ...................................................................................5-12
Retrieving Saved Menu Information .........................................5-12
Creating Your Own Menu Templates .......................................5-14
Creating Popup Menus (On Your Own) ...............................................5-16
What Is a Popup Menu? ..........................................................5-16
Creating a Popup Menu ...........................................................5-16
Using the PopupMenu Method.................................................5-17

LAB 5: CREATING AND USING MENUS ......................................................5-23


Lab 5 Overview ...................................................................................5-24
Using the Menu Editor.........................................................................5-25
Responding to Menu Clicks.................................................................5-29
Manipulating Run-Time Properties ......................................................5-32

COMPILING AND DISTRIBUTING APPLICATIONS.........................................6-1


Finishing Touches .................................................................................6-2
Project Properties..................................................................................6-3
The General Tab........................................................................6-4
The Make Tab ...........................................................................6-5
Working with Properties Programmatically.................................6-6
Native Code vs. p-code .........................................................................6-8
Pros and Cons...........................................................................6-8
Optimizations.............................................................................6-9
Creating Your Executable....................................................................6-11
Using Project Properties from Windows...................................6-11
Using the Package and Deployment Wizard........................................6-13

TOC-4 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

Starting the P&D Wizard ..........................................................6-13


Running the Wizard from within Visual Basic ...........................6-13
Running the P&D Wizard from Windows..................................6-14
P&D Wizard Options................................................................6-15
The Package Wizard, Page by Page .......................................6-15
The Deployment Wizard, Page by Page ..................................6-26
From the End Users Point of View ..........................................6-29

LAB 6: COMPILING AND DISTRIBUTING APPLICATIONS ..........................6-33


Lab 6 Overview ...................................................................................6-34
Create a Sample Application ...............................................................6-35
Set Project Options .............................................................................6-36
Create the Executable.........................................................................6-38
Build the Distribution Files and Run.....................................................6-39

WORKING WITH VBA ......................................................................................7-1


Creating a Simple Procedure ................................................................7-2
Whats a Function? ....................................................................7-2
Your First VBA Function (Try It Out!) .........................................7-4
Calling Procedures ....................................................................7-7
Variables and Parameters .....................................................................7-9
What Is a Variable? ...................................................................7-9
An Example ...............................................................................7-9
Give Your Variables Meaningful Names ..................................7-11
Data Types..........................................................................................7-12
Variable Types.........................................................................7-12
Variable Behavior ....................................................................7-13
The Variant Data Type.............................................................7-14
Initializing Variables .................................................................7-15
Implicit vs. Explicit Declarations ...............................................7-15
Using Constants..................................................................................7-19
Using MsgBox .........................................................................7-20
Creating Your Own Constants .................................................7-22
Investigating Built-In Functions............................................................7-23
VBAs Built-In Functions ..........................................................7-23
Categorized Information in the Object Browser ........................7-23
Branching Structures...........................................................................7-25
Why Branch? ...........................................................................7-25
If ... Then ... End If ...................................................................7-25

Programming Fundamentals of Visual Basic 6.0 TOC-5


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

If...Then...[Else...]End If ...........................................................7-26
If...Then...Else[If]...End If .........................................................7-27
Select Case .............................................................................7-28
GoTo .......................................................................................7-29
Looping Structures ..............................................................................7-31
What Is a Loop?.......................................................................7-31
For...Next.................................................................................7-31
DoLoop ................................................................................7-33
Using For...Next.......................................................................7-35
A DoLoop Example ..............................................................7-36

LAB 7: WORKING WITH VBA .......................................................................7-43


Lab 7 Overview ...................................................................................7-44
Create a Simple Function ....................................................................7-45
Use Data Types and Variables ............................................................7-47
Call a Function from a Form ................................................................7-49
Use the MsgBox Function ...................................................................7-52

HANDLING ERRORS .......................................................................................8-1


Handling Syntax Errors .........................................................................8-2
Control Compilation and Syntax Errors ......................................8-2
Handling Run-Time Errors.....................................................................8-3
Doesnt Visual Basic Handle Run-Time Errors? .........................8-3
The Error Handling Standard.................................................................8-5
The Three-Step Program ...........................................................8-5
How Do Most Developers Handle Errors?..................................8-5
Which Error Occurred? ..............................................................8-7
Using the Error Number .............................................................8-8
Taking a Closer Look ..........................................................................8-11
Setting the Error Trap ..............................................................8-11
Exiting the Error Handler..........................................................8-13
Who Handles Errors? ..........................................................................8-17
Unanticipated Errors ................................................................8-17
A Simple Example ...................................................................8-17
When Do You See Errors? ......................................................8-19

LAB 8: HANDLING ERRORS ........................................................................8-23


Lab 8 Overview ...................................................................................8-24
Read Me First ..........................................................................8-24
Use Simple Error Handling ..................................................................8-25

TOC-6 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

Use the Err Object...............................................................................8-28


Handle the Error..................................................................................8-30

DEBUGGING APPLICATIONS .........................................................................9-1


Handling Logic Errors............................................................................9-2
A Demonstration Case...............................................................9-2
Walking Through Your Code......................................................9-6
What You Can Do in Break Mode ..............................................9-7
Setting a Breakpoint ..................................................................9-9
Stepping Through Code...........................................................9-10
Keeping an Eye on Your Variables ..........................................9-14
Watch Expressions..............................................................................9-16
Setting a Watch Expression .....................................................9-17
Conditional Watch Expressions ...............................................9-19
The Call Stack.....................................................................................9-21
What Is the Call Stack?............................................................9-21
Viewing Called Procedures......................................................9-21
The Debugging Process......................................................................9-22
Write Bug-Free Code...............................................................9-22
Debugging Hints ......................................................................9-22

LAB 9: DEBUGGING APPLICATIONS...........................................................9-29


Lab 9 Overview ...................................................................................9-30
Working with Breakpoints ....................................................................9-31
Stepping Through Code ......................................................................9-35
Using Watch Variables ........................................................................9-39

MORE VBA ISSUES.......................................................................................10-1


Scope, Lifetime, and Precedence........................................................10-2
Defining the Terms ..................................................................10-2
Variable Scope ........................................................................10-2
Declaring Variables..................................................................10-3
Variable Precedence ...............................................................10-6
Variable Lifetime ......................................................................10-6
Passing by Value and by Reference....................................................10-8
Whats the Difference?.............................................................10-8
Testing It Out .........................................................................10-10
What Do ByRef and ByVal Mean to You? ..............................10-11
Should You Use ByRef or ByVal? ..........................................10-13
Arrays................................................................................................10-14

Programming Fundamentals of Visual Basic 6.0 TOC-7


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

What Is an Array? ..................................................................10-14


Declaring Arrays ....................................................................10-15
Working with Elements of Arrays ...........................................10-16
Changing an Arrays Size ......................................................10-17
Detecting Array Bounds .........................................................10-18
An Array Example..................................................................10-19
Optional Arguments...........................................................................10-20
Declaring Optional Arguments ...............................................10-20
Defining Default Values .........................................................10-21
Named Parameters with Optional Arguments ........................10-23

LAB 10: MORE VBA ISSUES ......................................................................10-29


Lab 10 Overview ...............................................................................10-30
Pass Values by Reference ................................................................10-31
Work with Arrays ...............................................................................10-37
Use Optional Parameters ..................................................................10-42
Use Named Parameters ....................................................................10-45

MORE FORM AND CONTROL ISSUES.........................................................11-1


Using Multiple Forms...........................................................................11-2
Referring to Properties and Controls........................................11-2
Load vs. Show .........................................................................11-3
Hiding Forms ...........................................................................11-5
Unloading Forms .....................................................................11-6
List Boxes Revisited ............................................................................11-8
Creating Multi-Select List Boxes ..............................................11-8
Control Arrays ...................................................................................11-11
What Are Control Arrays? ......................................................11-11
Creating a Control Array ........................................................11-11
Changing Control Properties..................................................11-13
Writing Code for Control Arrays .............................................11-13

LAB 11: MORE FORM AND CONTROL ISSUES ........................................11-19


Lab 11 Overview ...............................................................................11-20
Use Multiple Forms ...........................................................................11-21
Create a Multi-Select List Box ...........................................................11-23
Create a Control Array ......................................................................11-26

ADDING SIMPLE DATABASE SUPPORT......................................................12-1


Support for Data Access in Visual Basic 6.0........................................12-2

TOC-8 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

ADO Data Control....................................................................12-2


ActiveX Data Objects (ADO) ....................................................12-2
Other ActiveX Components......................................................12-2
In This Course......................................................................12-3
What You Need to Know..........................................................12-3
Using the ADO Data Control ...............................................................12-4
Getting Started with the ADO Data Control ..............................12-4
Adding a Data Control to a Form .............................................12-5
Setting Data Control Properties ...............................................12-6
Binding Controls to Data....................................................................12-10
Data Binding Explained..........................................................12-10
Binding a Control to a Field....................................................12-11
Moving Through the Data ......................................................12-12
Some Considerations.............................................................12-12
Writing Code for the Data Control......................................................12-13
Distributing Apps with the Data Control..................................12-13
Changing Properties at Run Time..........................................12-13
Solving Typical Problems.......................................................12-14
Whats a Recordset? .............................................................12-14
Updating the Caption Area.....................................................12-15
Deleting a Record ..................................................................12-16
Validating Data in Bound Controls .........................................12-17

LAB 12: ADDING SIMPLE DATABASE SUPPORT .....................................12-23


Lab 12 Overview ...............................................................................12-24
Add the Data Control to a Form.........................................................12-25
Bind Text Boxes to the Data Control..................................................12-30
Write Code to Delete Records...........................................................12-32

APPENDIX A: THE REDDICK VBA NAMING CONVENTIONS ....................... A-1


Introduction .......................................................................................... A-2
Changes to the Conventions..................................................... A-2
An Introduction to Hungarian................................................................ A-3
Tags ......................................................................................... A-3
Creating Data Types................................................................. A-6
Constructing Procedures .......................................................... A-8
Prefixes .................................................................................... A-9
Suffixes................................................................................... A-11
File Names ............................................................................. A-11

Programming Fundamentals of Visual Basic 6.0 TOC-9


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Table of Contents

Host Application and Component Extensions to the


Conventions............................................................................ A-12

APPENDIX B: USEFUL VBA FUNCTIONS...................................................... B-1


Lots of Functions to Choose From........................................................ B-2
Strings ...................................................................................... B-2
Dates and Times....................................................................... B-3
Conversion ............................................................................... B-3
Other ........................................................................................ B-4
New in Visual Basic 6.0 ............................................................ B-4

APPENDIX C: USEFUL SHORTCUTS ............................................................ C-1


Table of Shortcut Keys ......................................................................... C-2
Design Environment ................................................................. C-3
Debugging ................................................................................ C-3

APPENDIX D: VERSIONS OF VISUAL BASIC 6.0.......................................... D-1


Versions of Visual Basic ....................................................................... D-2

APPENDIX E: SETTING UP THE ENVIRONMENT ......................................... E-1


Global Settings in Visual Basic ............................................................. E-2
Setting IDE Properties.......................................................................... E-3
Setting Up Windows ............................................................................. E-5

INDEX......................................................................................................INDEX-1

TOC-10 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Creating and Using Menus

Creating and
Using Menus
Objectives
Review the basic elements of menus in Windows applications.
Understand how Visual Basic implements menus.
Learn how to use the Visual Basic Menu Editor.
See how to run VBA code from a menu command.
See how to change menu properties at run time.
Use menu templates.
Learn how to create popup menus for your forms.

The sample project for this chapter is MENUS.VBP.

Programming Fundamentals of Visual Basic 6.0 5-1


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Creating and Using Menus

Menus in Visual Basic


Although you can create many applications that dont require menus, sooner or
later youll need to add menu support to a program. This is especially true if
you are going to create applications that utilize a multiple document interface
(MDI). This section explains how Visual Basic treats custom menus.

Menu Basics
Figure 1 shows a diagram illustrating the basic aspects of menus in Windows
applications. You can see these menus on the sample form for this section. All
of these terms are summarized below.

Menu Separator Shortcut Key

Menu Bar

Top-Level
Menu
Command

Checked
Menu Item

Disabled
Menu Item

Access Key

Drop-Down Fly-Out
Menu (or Cascading)
Menu

Figure 1. The basic elements of menus in Windows.

Windows has a menu bar that appears just below the window caption
and contains all the top-level menu commands.
Clicking on one of the top-level menu commands reveals a drop-
down menu containing other commands.
Drop-down menus may have fly-out or cascading menus that appear
to the left or right of a menu command when the user selects it. These

5-2 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Menus in Visual Basic

contain other menu commands and can even contain other fly-out
menus!
Menu separators are used to segregate groups of related menu items
or to provide a visual break in a large menu structure.
Menu commands usually contain access keys denoted by underlined
letters in the menu text. Users can quickly select menu commands by
pressing the ALT key along with the access key.
Some commonly used menu commands may also have a shortcut key
(usually a function key or a letter combined with the Ctrl, Alt and/or
Shift keys). Shortcut keys activate the menu command without having
to select it.
Menu commands can be disabled, preventing the user from selecting
them.
Menu commands can also be checked, indicating a persistent option
that can be toggled by selecting the menu.

Programming Fundamentals of Visual Basic 6.0 5-3


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Creating and Using Menus

Using the Menu Editor


You use a specialized dialog box to create and edit form menus. You create the
menu structure graphically (almost) and set property values for individual
menu items.

Figure 2 shows the Menu Editor window. You can only open the Menu Editor
when a form designer window is active. Select Tools|Menu Editor, press
The Menu Editor CTRL+E, or click the Menu Editor toolbar button (shown on the left). The
button Menu Editor modifies the menu of the active form.

Figure 2. You create menus for each form using the Menu Editor.

Creating a New Top-Level Menu


Command
To create a top-level new menu command:

1. Enter a caption for the menu command in the Caption field. (Include an
ampersand (&) in the caption to create an access key.)

2. Enter a name for the menu command in the Name field.

NOTE The name you enter in the Name field is the control name youll
use in any VBA code you write.

5-4 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Using the Menu Editor

Visual Basic will add the new menu command to the list of commands at the
bottom of the dialog box. Figure 3 shows the Menu Editor after creating a new
menu command named mnuFile with the caption &File.

Figure 3. Creating a File command using the Menu Editor.

To create another new command, press ENTER to select the next, blank menu
command in the list. You can also click the Next button.

To insert new menu items in the middle of the list, select the item before which
you want to insert the new item and click the Insert button. (The Menu Editor
always maintains a blank row at the end of the list for adding new menu
commands at the end.)

Likewise, you can click the Delete button to remove a menu item.

TIP: You create menu separators by setting the Caption property of a menu
command to a hyphen (-). Even though users can never select a menu
separator you must still assign it a unique Name property.

Saving Newly Created Menu Commands


Once youve added one or more menu commands (or made changes to existing
commands), click the OK button to save your changes. If there are no errors in
your menu structure Visual Basic updates the form in its designer window to
include the menu. Figure 4 shows a form after adding the new menu.

Programming Fundamentals of Visual Basic 6.0 5-5


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Creating and Using Menus

Figure 4. A new form after creating a single menu command.

Setting Menu Command Properties


Supplying a name and caption is all thats required to create a menu command.
You may, however, want to set some additional properties that affect the
appearance and behavior of certain menu items. These properties are
summarized below:

The Shortcut property defines the shortcut key for the menu
command. You choose from a set list of keyboard combinations (e.g.,
CTRL+C, SHIFT+F9). No two menu items can have the same shortcut
key.
The HelpContextID property lets you assign a Help topic to the menu
command. (The Help file itself is set by the applications properties.)
The Checked property allows you to place a check mark next to the
menu command at design time.
The Enabled property allows you to enable or disable a menu
command. Users can see, but not select disabled menu items.
The Visible property allows you to hide a menu command at design
time. You can set this property to True at run time to display the
command.
The WindowList property designates the menu as a window list.
Window lists are used in MDI applications to display a list of the open
child windows.
The Index property allows you to create arrays of menu items. Each
item in the array has the same name, but is differentiated by its index.
This allows you to write one event procedure for the whole group of

5-6 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Using the Menu Editor

items. This feature also allows you to create menu items at run time
(using the Load statement, not covered here).

Changing Menu Structure


So far you have learned how to create top-level menu commands. You will
undoubtedly want to create a more complex menu structureone that includes
drop-down and, possibly, fly-out menus.

You change the hierarchical structure using the arrow buttons on the Menu
Editor dialog box. Indenting a menu command once to the right creates a drop-
down menu. Indenting a menu command twice to the right creates a fly-out
menu.

TIP: You can change the position of a menu command by clicking the up or down
arrows.

Figure 5 shows the Menu Editor open to the File menu of the sample form.

Figure 5. Indentation denotes the hierarchical structure of a forms menu.

Programming Fundamentals of Visual Basic 6.0 5-7


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Creating and Using Menus

Menu Design Conventions


As you design your menus you will want to adhere to several accepted
practices used in most Windows applications.

All menu commands should be assigned an access key. All of the


access keys on the same menu should be unique.
Menu commands that result in a direct action should be given as
standard text. Menu commands that open a subsequent form or dialog
box should be followed by an ellipsis ().
Most applications feature an initial menu called File that, at a
minimum, includes a command for exiting the application.
If your application includes custom, online Help, you should include a
Help menu as the right-most menu command.

5-8 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Working with Menus

Working with Menus


The next few sections discuss the infrastructure Visual Basic adds to normal
menus, so you can refer to them, and react to their events, from within your
applications.

Menus are Controls


As far as Visual Basic is concerned, menus are just special types of controls
that you place on a form. Visual Basic controls the placement and display of
menu commands (just under a forms title bar) but they are controls
nonetheless. Each menu command you create is treated as a separate control
with its own set of properties and methods.

Menu Events
Menu commands have one event, Click, that is triggered when a user selects
the command. You write VBA code to respond to a menu selection in the
Click event. The sample form has numerous menus that display a message box
when you click them. The code for one of those is shown below:

Private Sub mnuEditCopy_Click()


MsgBox "Edit | Copy"
End Sub

NOTE Unfortunately there is no built-in event that fires as a user scrolls


through menu items before selecting one. If Visual Basic had such
an event it would be useful for displaying help information (e.g.,
status bar text). You can, however, purchase ActiveX controls that
provide this functionality. You can also write VBA code to do
this, although it is far from simple.

Programming Fundamentals of Visual Basic 6.0 5-9


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Creating and Using Menus

Manipulating Menus at Run Time


One of the more powerful aspects of Visual Basic menus is the ability to
manipulate them while your application is running, using VBA code. You can
change menu items properties, such as Visible, Checked, and Enabled.

Changing menu properties at run time is simple because, after all, menus are
just controls. The sample form features buttons that toggle the Enabled and
Visible properties of various menu items. The code listing below contains the
event code from the buttons.

TIP: Although there are other ways to toggle the state of a True/False (Boolean)
property value, the simplest way is to use the Not operator. This operator
toggles a Boolean value so that if it was True, it becomes False. If the value
was False, it becomes True.

Private Sub cmdDisable_Click()


' Toggle the Enabled property of the
' the Edit | Undo menu
mnuEditUndo.Enabled = Not mnuEditUndo.Enabled
End Sub

Private Sub cmdVisible_Click()


' Toggle the Visible property of the
' the View | Full Screen menu
mnuViewFullScreen.Visible = _
Not mnuViewFullScreen.Visible
End Sub

You can also change a menus Checked property to add or remove a check box
next to the menus caption. This has been done for the Tools|AutoCorrect
menu on the sample form. Code in the menus Click event accomplishes the
task:

5-10 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Manipulating Menus at Run Time

Private Sub mnuToolsAutoCorrect_Click()


MsgBox "Tools | AutoCorrect popup"

' Change the checked state of the


' AutoCorrect menu
mnuToolsAutoCorrect.Checked = _
Not mnuToolsAutoCorrect.Checked

End Sub

TIP: You can also change a menus Caption property. This lets you change the
menu text as necessary.

Programming Fundamentals of Visual Basic 6.0 5-11


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Creating and Using Menus

Reusing Menus
Visual Basic 6.0 makes it easy to set up a forms menu structure, and then
reuse it later on other forms. By setting up menu templates for commonly used
menu structures, you can save a great deal of time when designing forms.

Retrieving Saved Menu Information


The key to this technology is the VB 6 Template Manager, made available
using the Add-Ins|Add-In Manager dialog box. Once youve added this add-
in, you can use the Tools|Add Menu item to insert existing menu structures
into your forms.

To install the Template Manager, follow these steps (the result of the steps is
shown in Figure 6):

1. Choose Add-Ins|Add-In Manager.

2. Scroll down in the list of add-ins, until you find VB 6 Template


Manager.

3. Click the Loaded/Unloaded check box (to load the add-in immediately)
and the Load on Startup check box (so the add-in loads for future Visual
Basic sessions).

Figure 6. Add the template manager add-in, so you can add existing menu
structures to your forms.

5-12 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Reusing Menus

With the form youd like to modify selected, choose the Tools|Add Menu
menu item, and youll see the dialog box shown in Figure 7. Select the menu
structure youd like to add to your form, and Visual Basic does the rest for
you. It reads the menu information from the selected template, and adds the
menus supplied by the template to your form. In addition, the Add Menu tool
also copies any code associated with the menu items to your form, as well.

Figure 7. Select a menu structure from this list of available templates.

NOTE If any existing top-level menus in your form conflict with any top-
level menus in the template, Visual Basic will add no new menus
to your form. Youll get no indication of whats gone wrong, but
nothing on your form will change.

Try It Out!
Follow these steps to try out the menu templates:

1. Open the test form (frmTest) in design view.

2. Choose the Tools|Add Menu menu item.

3. Choose the Explorer File Menu item from the list of templates, and click
the Open button.

4. Check out the various menu items on the form.

Programming Fundamentals of Visual Basic 6.0 5-13


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Creating and Using Menus

5. Double-click on the form to view the forms module. Note all the code that
was placed in your form when Visual Basic added menus to the form.

Creating Your Own Menu Templates


Once youve created a form with menus that youd like to reuse, simply save a
copy of that form in the appropriate folder, and youll have a new menu
template.

To create a menu template, save your template form (with its menus created,
and associated code written) to the Templates\Menus folder underneath the
Visual Basic folder. This location is user-settable, however, and may have
been changed. To get the correct folder, use the Tools|Options menu item, and
check the Environment page, as shown in Figure 8.

Figure 8. Check on this page to make sure you place your menu template in the
correct folder.

Try It Out!
To test the menu template mechanism, follow these steps:

1. In the project window, select the frmMenus form.

2. Right-click on the form, and select the Save Menus.frm As... item.

5-14 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Reusing Menus

3. In the Save File As dialog box, navigate to the folder shown in the
Templates Directory field in Figure 8, and drill down into the Menus
subfolder.

4. Change the name to AppDevTest, and click the Save button to save the
new copy of the form.

5. Back in Visual Basic, open the frmTest form in design mode.

6. Select Tools|Add Menu, and choose the new AppDevTest item you find
there.

7. Your form should now have menus identical to the original forms menus,
including all the code that was in the forms module.

8. When you quit Visual Basic, make sure you dont save the project or any
of its items, because saving the form to a new folder changed the project
file, and you may want to work with the project again later.

Programming Fundamentals of Visual Basic 6.0 5-15


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Creating and Using Menus

Creating Popup Menus (On Your Own)


If you're creating complete applications, you may want to add context-
sensitive popup menus to your forms. This section introduces that concept, and
you may want to work through this after class.

What Is a Popup Menu?


The Menu Editor is useful for creating the main menu associated with a form.
There is, however, another type of menu a form may havea popup menu.
Popup menus typically appear on a form when the user clicks the right mouse
button. Figure 9 shows the chapters sample form with a popup menu
displayed.

Figure 9. The sample form features a popup menu that appears when you click the
right mouse button.

Creating a Popup Menu


Creating a popup menu is just like creating a normal menu with one
exceptionthe top-level menu item is normally not displayed. That is, you
normally set the Visible property of the top-level menu item to False. The
popup menu is formed by the submenus of the top-level menu.

Figure 10 shows the Menu Editor open to the mnuPopup menu, which is the
top-level menu for the popup menu. Note that the Visible check box is
unchecked. Since the user will never see the top-level menu it doesnt matter
what the caption is.

5-16 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Creating Popup Menus (On Your Own)

Figure 10. You can create a popup menu on a form by hiding the top-level item.

Using the PopupMenu Method


Creating popup menus in Visual Basic is simpleyou call the PopupMenu
method of a form, and Visual Basic handles the rest. The PopupMenu method
accepts a reference to the menu to act as the popup menu. Visual Basic does
not display that menu, however. What Visual Basic displays are any submenus
that the menu has. You typically call the method in the MouseUp event for a
form or control.

For example, the following line of code would create a popup menu from the
mnuPopup menu and display it when the user clicked the right mouse button
on the form:

Programming Fundamentals of Visual Basic 6.0 5-17


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Creating and Using Menus

Private Sub Form_MouseUp(Button As Integer, _


Shift As Integer, X As Single, Y As Single)

' If the user right-clicked the mouse,


' pop up the menu
If Button = vbRightButton Then
Me.PopupMenu mnuPopup, vbPopupMenuRightButton
End If
End Sub

TIP: You can control the location where the popup menu appears by passing x and
y coordinates to the PopupMenu method.

NOTE In this example, youve passed vbPopupMenuRightButton as the


second parameter to the PopupMenu method. Without this
parameter, popup menus in Visual Basic applications would work
differently than they do in all other applicationsyoud be
required to use the left mouse button to make selections on the
popup menu. Because youve used the right mouse button to get
the menu to pop up, it seems silly to then make you use the left
button to select an item. Most Windows applications allow you to
use either button to select an item, and thats what you accomplish
by supplying the vbPopupMenuRightButton option.

5-18 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Creating Popup Menus (On Your Own)

Summary
Each form in a Visual Basic application can have its own custom
menu.
Use the Menu Editor to create and modify form menus.
Visual Basic supports top-level, drop-down, and fly-out menus.
Visual Basic treats each separate menu item as a control, complete
with an event procedure (Click).
Change menu item properties at run time.
Visual Basic 6.0 provides a simple way to reuse menussave a form
with the menus you like to the Templates\Menus folder, and then
choose the Tools|Add Menu menu item.
Create popup menus by calling a forms PopupMenu method.

Programming Fundamentals of Visual Basic 6.0 5-19


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Creating and Using Menus

(Review questions and answers on the following pages.)

5-20 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Creating Popup Menus (On Your Own)

Questions
1. How do you specify the hierarchical structure of a menu system?

2. What does the ampersand in a menu caption do?

3. How do you run the code associated with a menu item without selecting it?

Programming Fundamentals of Visual Basic 6.0 5-21


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Creating and Using Menus

Answers
1. How do you specify the hierarchical structure of a menu system?
Use the arrow keys in the menu editor to indent or outdent menu
items

2. What does the ampersand in a menu caption do?


Creates an access key for the menu command

3. How do you run the code associated with a menu item without selecting it?
Assign the menu command a shortcut key and press it

5-22 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Creating Popup Menus (On Your Own)

Lab 5:
Creating and
Using Menus

Programming Fundamentals of Visual Basic 6.0 5-23


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Lab 5:
Creating and Using Menus

Lab 5 Overview
In this lab youll learn how to create and manipulate menus on Visual Basic
forms.

To complete this lab, youll need to work through three exercises:

Using the Menu Editor


Responding to Menu Clicks
Manipulating Run-Time Properties
Each exercise includes an Objective section that describes the purpose of the
exercise. You are encouraged to try to complete the exercise from the
information given in the Objective section. If you require more information to
complete the exercise, the Objective section is followed by detailed step-by-
step instructions.

5-24 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Using the Menu Editor

Using the Menu Editor

Objective
In this exercises youll use the Visual Basic Menu Editor to create a simple
menu structure. Youll begin with a blank form and create a top-level menu
bar consisting of File and Help menus. Beneath the File menu youll create
New, Open, Save, and Exit menu commands, with a menu separator between
Save and Exit. Beneath the Help menu youll create an About menu. Lastly,
youll assign shortcut keys to the New, Open, Save, and Exit commands of
Ctrl+N, Ctrl+O, Ctrl+S, and Ctrl+Q, respectively.

Things to Consider
How do you open the Menu Editor?
How do you add menus and menu commands?
How do you designate top-level menus and menu commands beneath
them?
How to assign a shortcut key combination to a menu command?

Step-by-Step Instructions
1. Begin by launching Visual Basic and creating a new Standard EXE
project. Visual Basic presents you with a blank form, Form1.

2. Open the Menu Editor by clicking the Menu Editor toolbar button or by
selecting Tools|Menu Editor (or press CTRL+E). Visual Basic opens the
Menu Editor dialog box (see Figure 11).

Programming Fundamentals of Visual Basic 6.0 5-25


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Lab 5:
Creating and Using Menus

Figure 11. The Menu Editor dialog box showing no menu items.

3. Create the File menu by typing &File in the Caption field and mnuFile in
the Name field. Visual Basic adds the text &File to the first row in the
list at the bottom of the dialog box.

4. Press ENTER or ALT+N, or click the Next button to add the next menu
command. Visual Basic highlights the second row in the list and places the
insertion point back in the Caption field.

5. Create the New menu command by typing &New in the Caption field and
mnuFileNew in the Name field.

6. From the Shortcut list, select CTRL+N as the shortcut key combination.

7. Press ENTER again to move to the next menu command.

8. Repeat steps 5 through 7 to create the menu commands listed in the table
below:

Caption Name Shortcut

&Open mnuFileOpen CTRL+O


&Save mnuFileSave CTRL+S
- mnuFileSep (none)
E&xit mnuFileExit CTRL+Q

9. Select the &New menu command in the list at the bottom of the dialog box
and click the right arrow button once. Visual Basic adds four dots in front
of the menu command, indicating that it will appear beneath the File menu.

5-26 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Using the Menu Editor

10. Repeat this step for each of the remaining menu commands that will
appear beneath the File menu.

11. When you have finished indenting the existing menu commands, click on
the blank row in the list of menu commands, just beneath the E&xit
command.

12. Create the Help menu by typing &Help in the Caption field and mnuHelp
in the Name field. Press ENTER. Visual Basic highlights the next blank
row.

13. Create the About menu command by typing &About in the Caption field
and mnuHelpAbout in the Name field.

14. Indent the &About menu command beneath the Help menu by selecting it
in the list and clicking the right arrow once. The Menu Editor should now
display the menu structure shown in Figure 12.

Figure 12. You should have a menu structure that looks like this.

15. Click the OK button in the Menu Editor dialog box. Visual Basic displays
the blank form with the newly created menu bar (see Figure 13).

Programming Fundamentals of Visual Basic 6.0 5-27


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Lab 5:
Creating and Using Menus

Figure 13. This shows the new menu in design mode.

16. Press F5 to run the program.

17. Verify that the menu looks and works as you expect. When you click the
File menu you should see the menu commands illustrated in Figure 14.

Figure 14. Heres the menu in run mode.

18. When you are finished experimenting, stop the program and, optionally,
save the project.

5-28 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Responding to Menu Clicks

Responding to Menu Clicks

Objective
In this exercise youll write code that runs when a menu command is selected.
Youll complete two tasks. First, youll add code to the form that ends the
program when you select the Exit menu command. Second, youll add an
About dialog box to the project and display it when you select the About menu
command.

Things to Consider
What event corresponds to a menu being clicked?
How do you end a Visual Basic program?
How can you quickly add a simple About dialog box to your
application?

Step-by-Step Instructions
1. With the form you created in the last example displayed in design mode,
select the File|Exit command from the forms menu. Visual Basic opens
the code window and creates an empty procedure named
mnuFileExit_Click.

2. Add the code to unload the form when this menu is selected. The
procedure should look like this:

Private Sub mnuFileExit_Click()


Unload Me
End Sub

3. Press F5 to run the program.

4. After Visual Basic displays the form in run mode, select the File|Exit
command. Visual Basic terminates the application and returns to design
mode.

5. Press F5 to run the program again.

Programming Fundamentals of Visual Basic 6.0 5-29


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Lab 5:
Creating and Using Menus
6. This time, test the shortcut key by pressing CTRL+Q. Again, Visual Basic
ends the program.

7. Now add an About dialog box to the project by selecting Project|Add


Form. Visual Basic displays the Add Form dialog box shown in Figure 15.

Figure 15. Add an About dialog box to the project using a template.

8. Select the About Dialog icon and click the Open button. Visual Basic
adds a new form called frmAbout to the project.

9. Add the code to open the dialog box when you select the Help|About
menu command. Begin by double-clicking Form1 in the Project window.
Visual Basic displays the form in design mode.

10. Select the Help|About menu command from the forms menu. Visual
Basic displays the forms module and creates an empty procedure called
mnuHelpAbout_Click.

11. Add the code to open the dialog box. The procedure should look like this:

Private Sub mnuHelpAbout_Click()


frmAbout.Show vbModal
End Sub

12. Press F5 to run the program.

5-30 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Responding to Menu Clicks

13. Select the Help|About menu command. Visual Basic displays the About
dialog box in run mode (see Figure 16).

Figure 16. This dialog box was opened by selecting the Help|About menu
command.

14. Close the About dialog box and stop the program.

Programming Fundamentals of Visual Basic 6.0 5-31


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Lab 5:
Creating and Using Menus

Manipulating Run-Time Properties

Objective
In this exercise you will manipulate menu properties at run time. Youll add
code to the sample application so that when you select the File|New menu
command the application will disable the New menu and change the caption of
the Save menu to Save As After choosing the Save As menu, the application
will enable the New menu and change the caption of the Save As menu back to
Save.

Step-by-Step Instructions
1. With the sample project in design mode, double-click Form1 in the
Project Window.

2. Select the File|New command from the forms menu. Visual Basic opens
the forms module and creates an empty procedure called
mnuFileNew_Click.

3. Write the code to disable the menu command and change the caption of
the Save menu to Save As. The procedure should look like this:

Private Sub mnuFileNew_Click()


mnuFileNew.Enabled = False
mnuFileSave.Caption = "Save &As..."
End Sub

4. From the object list at the top of the code window, select mnuFileSave.
Visual Basic creates an empty procedure called mnuFileSave_Click.

5. Write the code to enable the New menu command and change the caption
of the Save menu back to Save. The procedure should look like this:

Private Sub mnuFileSave_Click()


mnuFileNew.Enabled = True
mnuFileSave.Caption = "&Save"
End Sub

5-32 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Manipulating Run-Time Properties

6. Press F5 to run the program.

7. Select the File|New menu command.

8. Select the File menu again. You should see that the New menu has been
disabled and that the caption of the Save menu has been changed, as
illustrated in Figure 17.

Figure 17. The File menu has been modified at run time.

9. Select the File|Save As menu item and verify that the File menu is
changed back to its original appearance.

10. Stop the program and, optionally, save the project.

Programming Fundamentals of Visual Basic 6.0 5-33


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.
Lab 5:
Creating and Using Menus

5-34 Programming Fundamentals of Visual Basic 6.0


Copyright by Application Developers Training Company and AppDev Products Company, LLC
Licensed to ITCourseware, LLC. Reprinted with permission.

You might also like