0% found this document useful (0 votes)
50 views51 pages

VBA Foundations For Microsoft Office

Visual basic 6.1 tech

Uploaded by

KL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views51 pages

VBA Foundations For Microsoft Office

Visual basic 6.1 tech

Uploaded by

KL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

VBA Foundations

for Microsoft
Office
Table of Contents

VBA Foundations for Microsoft Office


Table of Contents

INTRODUCTION .......................................................................................INTRO-1
Courseware Conventions ..............................................................INTRO-2
The Practice Disks.........................................................................INTRO-3
Working with the Office Samples .......................................INTRO-3
About the Author............................................................................INTRO-5

GETTING STARTED WITH VBA .......................................................................1-1


What Is VBA? .........................................................................................1-2
Why Would You Want to Use VBA? ...........................................1-2
What Products Host VBA?......................................................................1-4
The Flavors of Office...................................................................1-4
Who Has Licensed VBA?............................................................1-5
What Does a VBA Application Look Like?..............................................1-6
Custom Dialog Boxes .................................................................1-6
Custom Toolbars and Menus......................................................1-7
Custom Buttons ..........................................................................1-7
Behind-the-Scenes Operations...................................................1-8
The Code Underneath It All ........................................................1-9
Working with VBA in a Host Product ....................................................1-10
Where Does VBA Code Live?...................................................1-10
Where are Projects Stored in Office Products? ........................1-11
Where Are Projects Stored in Other VBA Hosts? .....................1-12
How Do You Make VBA Code Happen? ..............................................1-13
The Immediate Window ............................................................1-13
User Interface Tools..................................................................1-14
Events .......................................................................................1-17
Starting with VBA by Recording Macros...............................................1-19
Recorded Macros in Excel, Word, and PowerPoint ..................1-19
Using the Macro Recorder ........................................................1-19
Running a Recorded Macro ......................................................1-21
Looking at the Code You Wrote................................................1-22
Modifying the Code to Make It Do More (or Less) ....................1-23
Why Not Just Record Macros? .................................................1-25
A Word About Access Macros ..................................................1-25

LAB 1: GETTING STARTED WITH VBA.........................................................1-31

VBA Foundations for Microsoft Office TOC-1


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

Lab 1 Overview.....................................................................................1-32
Setting Security Levels .........................................................................1-33
Explore an Excel VBA Application ........................................................1-35
Call a Function from the Excel User Interface ......................................1-39
Try Out a Word VBA Application ..........................................................1-41
Record a Macro in Word.......................................................................1-46
Create a Toolbar and Button in Word ...................................................1-51
Call a Function from an Access Query .................................................1-55

WRITING VBA PROCEDURES .........................................................................2-1


Overview of the Visual Basic Editor........................................................2-2
Opening the Visual Basic Editor .................................................2-2
The Project Explorer ...................................................................2-3
The Properties Window...............................................................2-4
The Immediate Window ..............................................................2-4
The Code Window ......................................................................2-4
Working with the Project Explorer...........................................................2-5
What Kinds of Components Does a Project Contain? ................2-5
Adding Items to a Project............................................................2-7
Removing Items from a Project...................................................2-7
Saving a Project..........................................................................2-7
Working with Multiple Projects ....................................................2-7
Naming Your Project...................................................................2-8
Creating Simple Procedures.................................................................2-10
Understanding Functions ..........................................................2-10
Writing Your First VBA Function ...............................................2-12
Key Concepts............................................................................2-15
Running Your Function from Word ...........................................2-17
Creating a Simple Sub Procedure ............................................2-18
Running a Sub Procedure.........................................................2-19
Understanding the Code Window .........................................................2-20
Anatomy of a Module ................................................................2-20
Changing a Module’s Name......................................................2-21
Customizing the Visual Basic Editor .....................................................2-22
Showing and Hiding Windows ..................................................2-22
Docking and Undocking Windows ............................................2-22
Changing the Editor Format......................................................2-23
Displaying Toolbars ..................................................................2-24

LAB 2: WRITING VBA PROCEDURES...........................................................2-29

TOC-2 VBA Foundations for Microsoft Office


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

Lab 2 Overview.....................................................................................2-30
Create and Rename a VBA Project ......................................................2-31
Add a New Module to a Project ............................................................2-33
Create a Simple Function .....................................................................2-36
Call a VBA Procedure from an Excel Worksheet..................................2-39
Change the Visual Basic Editor Format................................................2-40

WORKING WITH VARIABLES AND CONSTANTS ...........................................3-1


What Is a Variable? ................................................................................3-2
Give Your Variables Meaningful Names .....................................3-3
Data Types .............................................................................................3-4
What Is a Data Type? .................................................................3-4
Choosing a Data Type ................................................................3-5
Declaring Variables.....................................................................3-6
Using a Naming Convention .......................................................3-8
Initializing Variables ....................................................................3-9
Why Not Just Use the Variant Data Type? ...............................3-10
When Can I Use the Variant Data Type?..................................3-10
Implicit vs. Explicit Declarations................................................3-12
Working with Arrays..............................................................................3-15
What Is An Array?.....................................................................3-15
Declaring Arrays .......................................................................3-16
Working with Elements of Arrays ..............................................3-17
Changing an Array’s Size .........................................................3-18
Detecting Array Bounds ............................................................3-19
An Array Example .....................................................................3-20
Using Constants ...................................................................................3-21
The Carriage Return-Line Feed Constant.................................3-21
Using the MsgBox Function ......................................................3-22
Creating Your Own Constants ..................................................3-25

LAB 3: WORKING WITH VARIABLES AND CONSTANTS ............................3-29


Lab 3 Overview.....................................................................................3-30
Use Data Types and Variables .............................................................3-31
Use Option Explicit ...............................................................................3-33
Set Option Explicit as the Default .........................................................3-36
Apply a Naming Convention .................................................................3-39
Use Built-In Constants ..........................................................................3-42

VBA Foundations for Microsoft Office TOC-3


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

Define and Use a Constant...................................................................3-44

VISUAL BASIC EDITOR TECHNIQUES............................................................4-1


Writing Code Efficiently...........................................................................4-2
Moving Code Around ..................................................................4-2
Printing Code ..............................................................................4-3
Viewing Multiple Procedures.......................................................4-3
Formatting Code .........................................................................4-4
Commenting Out Code ...............................................................4-5
Setting a Bookmark.....................................................................4-5
Taking Advantage of IntelliSense ...........................................................4-7
List Properties/Methods (CTRL+J)................................................4-7
List Constants (CTRL+SHIFT+J) ....................................................4-8
Parameter Info (CTRL+SHIFT+I)....................................................4-8
Word Completion ........................................................................4-9
Optional and Named Arguments ..........................................................4-11
Optional Arguments ..................................................................4-11
Introducing Named Arguments .................................................4-11

LAB 4: VISUAL BASIC EDITOR TECHNIQUES .............................................4-17


Lab 4 Overview.....................................................................................4-18
Move Code to a New Procedure...........................................................4-19
Comment Out Code with the Edit Toolbar ............................................4-21
Use IntelliSense to Get Help.................................................................4-23
Use Named Arguments ........................................................................4-25

MASTERING VBA CONTROL STRUCTURES..................................................5-1


Branching Structures ..............................................................................5-2
Why Branch? ..............................................................................5-2
If...Then...[Else...]End If ..............................................................5-2
If...Then...Else[If]...End If ............................................................5-4
Select Case.................................................................................5-5
GoTo ...........................................................................................5-9
Looping Structures................................................................................5-11
What is a Loop? ........................................................................5-11
Do...Loops.................................................................................5-11
Do…Loop with Conditions ........................................................5-13
For...Next ..................................................................................5-16

LAB 5: MASTERING VBA CONTROL STRUCTURES ...................................5-23


Lab 5 Overview.....................................................................................5-24

TOC-4 VBA Foundations for Microsoft Office


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

Use If…Then/Else…End If....................................................................5-25


Use Select Case ...................................................................................5-27
Use a Do…Loop ...................................................................................5-29
Use a For…Next Loop ..........................................................................5-31

INVESTIGATING BUILT-IN FUNCTIONS..........................................................6-1


VBA’s Built-In Functions .........................................................................6-2
Using the Object Browser to Find VBA Functions ..................................6-3
Testing Functions in the Immediate Window ..........................................6-6
Convert Your Name to Proper Case ...........................................6-6
Calculate Your Age in Weeks ...................................................6-10
Interacting with the Computer...............................................................6-14
Working with the Windows Registry..........................................6-14
VBA Registry Functions ............................................................6-15
Calling the Functions ................................................................6-16
VBA Functions You’ll Probably Need ...................................................6-19
Strings.......................................................................................6-19
Dates and Times.......................................................................6-19
Conversion................................................................................6-20
Other Useful Functions .............................................................6-21

LAB 6: INVESTIGATING BUILT-IN FUNCTIONS ...........................................6-25


Lab 6 Overview.....................................................................................6-26
Request Data Using the InputBox Function..........................................6-27
Work with Strings..................................................................................6-30
Work with Dates....................................................................................6-32
Work with the Format Function.............................................................6-34

CREATING USER FORMS ................................................................................7-1


Working with User Forms .......................................................................7-2
What Are User Forms? ...............................................................7-2
Creating a New User Form .........................................................7-2
Design Mode vs. Run Mode........................................................7-3
Adding Controls to a User Form .............................................................7-5
What Are Controls?.....................................................................7-5
Introducing a Few Controls .........................................................7-5
Formatting Controls ................................................................................7-8
Selecting a Control......................................................................7-8
Moving a Control.........................................................................7-8

VBA Foundations for Microsoft Office TOC-5


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

Resizing a Control.......................................................................7-8
Working with Multiple Controls....................................................7-9
Deleting Controls ......................................................................7-10
Formatting Controls ..................................................................7-10
Setting Properties at Design Time ........................................................7-11
Working with the Properties Window ........................................7-12
A Few Common Properties.......................................................7-13
Introducing Events ................................................................................7-17
Event Procedures .....................................................................7-17
Creating an Event Procedure....................................................7-18
The Click Event.........................................................................7-19
The Change Event ....................................................................7-20
Setting Properties at Run Time.............................................................7-22
Setting Property Values ............................................................7-22
Retrieving Property Values .......................................................7-23
Setting Control Properties.........................................................7-23
Additional ActiveX Controls ..................................................................7-26
Where Do I Get These Other Controls?....................................7-26
Adding a Control to the Toolbox ...............................................7-26
Organizing the Toolbox.............................................................7-28
Modifying an ActiveX Control’s Properties................................7-28
Using the Calendar Control.......................................................7-30
Working with Methods ..........................................................................7-33
The Show Method.....................................................................7-33
The SetFocus Method...............................................................7-34
Working with List Boxes and Combo Boxes .........................................7-36
Using the AddItem Method or Combo Box ...............................7-36
Using a List Box’s or Combo Box’s List Property......................7-37
What Did the User Choose? .....................................................7-38

LAB 7: CREATING USER FORMS .................................................................7-43


Lab 7 Overview.....................................................................................7-44
Create Text Boxes and Labels .............................................................7-45
Use the Click Event ..............................................................................7-50
Change Control Properties from Code .................................................7-53
Open a Form from a Toolbar Button.....................................................7-54
Use the SetFocus Method ....................................................................7-60

UNDERSTANDING OBJECT MODELS.............................................................8-1

TOC-6 VBA Foundations for Microsoft Office


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

Defining the Terms .................................................................................8-2


What Is an Object? .....................................................................8-2
Object Models .............................................................................8-2
The Excel Object Model..............................................................8-3
The Microsoft Forms Object Model.............................................8-4
Typical Objects in Other Products ..............................................8-4
Using the Object Browser .......................................................................8-6
Opening the Object Browser.......................................................8-6
The Parts of the Object Browser.................................................8-7
Working with Object Models in VBA .......................................................8-9
Referring to Objects in Collections..............................................8-9
Referring to Collections Within Objects ....................................8-11
Setting Properties on Objects ...................................................8-12
Object Variables ...................................................................................8-14
Introducing Object Variables.....................................................8-14
Using Object Variables .............................................................8-15
What About Uninitialized Object Variables? .............................8-16
Special VBA Control Structures for Objects .........................................8-17
Using With...End With ...............................................................8-17
Introducing For Each...Next ......................................................8-18
Differentiating Types of Controls...............................................8-19
Working with the Office Object Models.................................................8-22
The CommandBars Object Model.............................................8-22

LAB 8: UNDERSTANDING OBJECT MODELS ..............................................8-31


Lab 8 Overview.....................................................................................8-32
Use Object Variables ............................................................................8-33
Use With…End With .............................................................................8-37
Use the Object Browser........................................................................8-39

HANDLING ERRORS.........................................................................................9-1
Recognizing a Run-Time Error ...............................................................9-2
Different Kinds of Errors..............................................................9-2
Doesn’t VBA Handle Run-Time Errors?......................................9-2
The Error-Handling Standard..................................................................9-4
The Three-Step Program ............................................................9-4
Creating a Standard Error Handler .............................................9-4
Setting the Error Trap .................................................................9-6
Which Error Occurred? ...............................................................9-6

VBA Foundations for Microsoft Office TOC-7


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

Using the Error Number ..............................................................9-7


Exiting the Error Handler ........................................................................9-9
Resume.......................................................................................9-9
Resume Next ............................................................................9-11
Resume Label...........................................................................9-11
Inline Error Handling .............................................................................9-12
On Error Resume Next .............................................................9-12
Disregarding Errors...................................................................9-12
Handling Errors as They Occur.................................................9-12
Combining Types of Error Handling......................................................9-14

LAB 9: HANDLING ERRORS..........................................................................9-19


Lab 9 Overview.....................................................................................9-20
Use Simple Error Handling ...................................................................9-22
Use the Err Object ................................................................................9-26
Handle the Error ...................................................................................9-28

DEBUGGING YOUR VBA CODE.....................................................................10-1


Debugging Your Code ..........................................................................10-2
What Is Break Mode? ...............................................................10-2
What You Can Do In Break Mode.............................................10-4
The Debug Toolbar ...................................................................10-5
Setting a Breakpoint .............................................................................10-6
Hard-Coding Breakpoints..........................................................10-6
Using Debug.Assert in Office 2000/XP .....................................10-7
Stepping Through Code......................................................................10-10
Single Step Mode....................................................................10-10
Procedure Step Mode .............................................................10-10
Stepping Out of a Procedure ..................................................10-11
Running to the Cursor.............................................................10-12
Continuing Execution ..............................................................10-12
Resetting the Project...............................................................10-12
Checking Values at Run Time ............................................................10-13
Using Auto Data Tips ..............................................................10-13
Using the Immediate Window .................................................10-14
Using the Locals Window........................................................10-15
Watch Expressions .............................................................................10-17
Using Watch Expressions .......................................................10-17
Conditional Watch Expressions ..............................................10-20

TOC-8 VBA Foundations for Microsoft Office


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

The Call Stack ....................................................................................10-22


Using the VBA Call Stack Dialog Box .....................................10-22
Working with Error Handling ...............................................................10-23
The Debugging Process .....................................................................10-29
Write Bug-Free Code ..............................................................10-29
Debugging Hints .....................................................................10-29

LAB 10: DEBUGGING YOUR VBA CODE....................................................10-35


Lab 10 Overview.................................................................................10-36
Experiment with Break Mode..............................................................10-37
Watch Expressions .............................................................................10-39

UNDERSTANDING EVENTS...........................................................................11-1
Events and Event Procedures ..............................................................11-2
What Did You Just Do?.............................................................11-3
Where To from Here? ...............................................................11-3
Which Objects Have Events? ...............................................................11-4
User Form Events.................................................................................11-5
The UserForm QueryClose Event.............................................11-5
Event Procedure Arguments.....................................................11-6
Control Events ......................................................................................11-8
Before/AfterUpdate Events .......................................................11-8
Click Event ................................................................................11-9
Product-Specific Events......................................................................11-11
Word’s Open Event.................................................................11-11
The Worksheet Change Event................................................11-13
Outlook’s ItemSend Event ......................................................11-14
Is There More? ...................................................................................11-15
Getting At Other Events ..........................................................11-16

LAB 11: UNDERSTANDING EVENTS ..........................................................11-23


Lab 11 Overview.................................................................................11-24
Change a Form’s Caption on Load.....................................................11-25
Capitalize Data Entry in a Text Box ....................................................11-27
Spell-Check a Document on Close.....................................................11-28
Work with a Cancelable Event............................................................11-30

PUTTING IT ALL TOGETHER .........................................................................12-1


Assembling the Pieces .........................................................................12-2

VBA Foundations for Microsoft Office TOC-9


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

Building a Solution in Excel ..................................................................12-3


Creating the User Form ............................................................12-3
Using the Product-Specific Event .............................................12-4
Running the Solution.................................................................12-5
Using the Solution in Word ...................................................................12-7
Copying the User Form.............................................................12-7
Changing the User Form...........................................................12-7
Using the Product-Specific Event .............................................12-8
Creating a Template .................................................................12-8
Running the Solution.................................................................12-8
Where Are You Going from Here?......................................................12-10

APPENDIX A: CALLING VBA PROCEDURES FROM THE


USER INTERFACE ........................................................................................... A-1
Calling a VBA Procedure from the User Interface ................................. A-2
Adding Shortcut Keys ................................................................ A-2
Adding Form Controls to a Document........................................ A-6
Creating Custom Toolbars and Buttons..................................... A-8
Using User Defined Functions in an Excel Worksheet Cell ..... A-11
Calling a Function in an Access Form or Query ...................... A-11

APPENDIX B: COMPARISON OF VBA, VISUAL BASIC, AND


MICROSOFT ACCESS FORMS ....................................................................... B-1
Confused Yet? ....................................................................................... B-2
Loading and Unloading Forms............................................................... B-3
Events.................................................................................................... B-4
Properties .............................................................................................. B-5

APPENDIX C: THE REDDICK VBA NAMING CONVENTIONS,


VERSION 6.0 .................................................................................................... C-1
Changes to the Conventions...................................................... C-2
An Introduction to Hungarian ................................................................. C-3
Tags ........................................................................................... C-4
Creating Data Types .................................................................. C-6
Constructing Procedures ........................................................... C-9
Prefixes .................................................................................... C-10
Suffixes .................................................................................... C-12
File Names............................................................................... C-12
Host Application and Component Extensions to the
Conventions ............................................................................. C-13

APPENDIX D: CREATING REUSABLE PROCEDURES.................................. D-1

TOC-10 VBA Foundations for Microsoft Office


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

Design before Code............................................................................... D-2


Why Bother? .............................................................................. D-2
Writing the Same Code Once ................................................................ D-3
An Example: Parsing a String into Words .................................. D-3
Move Duplicate Code to a New Procedure................................ D-6
Don’t Hard-Code ........................................................................ D-9
Design with the Next Project in Mind ....................................... D-12

APPENDIX E: TECHNIQUES WITH LIST BOXES AND COMBO BOXES....... E-1


Using Multi-Column List Boxes and Combo Boxes ............................... E-2
Multiple Selection in List Boxes ............................................................. E-6
Figuring Out What Was Selected............................................... E-6
Moving Items Between List Boxes......................................................... E-8
Controlling Data Entry in Combo Boxes ................................................ E-9

APPENDIX F: RESOURCES .............................................................................F-1


Where Can You Go for More Information? .............................................F-2
Books ..........................................................................................F-2
Journals ......................................................................................F-3
Web Sites....................................................................................F-3

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

VBA Foundations for Microsoft Office TOC-11


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

TOC-12 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Introduction

Introduction

VBA Foundations for Microsoft Office Intro-1


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Introduction

Courseware Conventions
We’ve followed several conventions to make this Professional Skills
Development material easy to follow:

• Each chapter is numbered separately to make it easy to find your


place.
• Examples in the sample database are noted in the left-hand column.
• There are Try It Out! sections sprinkled throughout the courseware.
These sections were specially created so that you could try the
example on your own. You may want to do this back at your office or
at home.
• To make it easier to follow all the samples in this class, we follow a
consistent set of naming conventions that were created by one of our
instructors, Greg Reddick. These naming conventions are explained in
detail in an appendix.
• There’s an index in the back of the book for your convenience.

Intro-2 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
The Practice CDs

The Practice CDs


All of the samples shown in this course workbook are included on a CD, which
you’ll receive as part of the course. You can use the samples to review what
you’ve learned in each day of the course, and as a jumping-off point for
writing your own applications. You should feel free to reuse any code in the
samples in your own applications.

The samples are provided in files created in one or more of the Microsoft
Office applications that include VBA. For example, they are saved with a
Microsoft Word file or a Microsoft Excel file.

You must be using a copy of Windows (virtually any version from Windows
98 forward) to be able to use these samples. You must be using a product that
includes VBA to run these samples. Sample files are provided for Office XP,
Office 2000, and Office 97.

Copying and Expanding the Practice Files


Before you can use the sample databases, you must follow the setup
instructions in the Readme.txt file, or let the CD self-install the samples.

Working with the Office Samples


To work with a sample saved with a Microsoft Access, Microsoft Excel,
Microsoft Word, or Microsoft PowerPoint file, you should perform the
following steps:

1. Open the sample file in its corresponding application.

2. Open the Visual Basic Editor from the host application by choosing
the following menu items: Tools|Macro|Visual Basic Editor.

3. Select the sample project in the Project Explorer. The samples are
available in the modules and forms beneath this project.

NOTE Some of the samples include code that’s specific to a particular


product. In that case you may need to change the sample code to
use it in the product you’re working in.

Working with Other VBA Hosts


If the samples aren’t saved in the file format of the application you’re working
in, then you must import the forms and modules in the sample directory into

VBA Foundations for Microsoft Office Intro-3


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Introduction

your application. You can then work with them in a VBA project and save
them with your project.

Intro-4 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
About the Author

About the Author


Jan Fransen has been helping people develop business applications and
streamline processes for about 15 years. As a consultant and trainer, Jan has
specialized in database applications that use Microsoft Access and the rest of
the Office family. As an author, Jan has written courseware for VBA, Access,
and XSLT, and contributed to books on Access.

VBA Foundations for Microsoft Office Intro-5


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Mastering VBA Control Structures

Mastering VBA
Control Structures
Objectives
• Learn about Visual Basic for Application control structures.
• Understand the principles of branching and looping.

VBA Foundations for Microsoft Office 5-1


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Mastering VBA Control Structures

Branching Structures

Why Branch?
Any complete programming language must supply some way in which your
code can control the flow of execution, depending on choices made during
execution. For example, a procedure may need to execute one statement or
group of statements if a condition is True, and a different statement or
statements if it’s False.

VBA provides a number of branching structures, each of which is covered in


the following sections.

If...Then...[Else...]End If
You can use the If...Then...[Else...] End If statement to execute one or more
statements if a condition is True, and a different group of statements if it’s not.
In concept, it is logical decision making:

If <some condition is true> Then


<Do some stuff>
Else
<Do some other stuff>
End If

In real world terms:

If Today is WeekEndDay Then


Sleep late
Read the paper, slowly
Else
Get up at 6AM
Go to work
End If

In this example, the condition is “Today is WeekEndDay.” If that’s true, then


you’ll do the weekend activities; otherwise, you’ll do the weekday activities.

5-2 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Branching Structures

In VBA code, the condition must be some sort of expression that returns a
value. If the returned value is 0, VBA treats it as False. VBA treats anything
besides 0 as True.

The Else portion is optional, as you’ll see in the example below.

For example, you could use the WeekDay() and Date() functions that are built
into VBA to write the condition from the previous example (Date() returns the
current date, and WeekDay() returns an integer indicating the day of the week,
given a date value):

If WeekDay(Date) = vbSunday Or _
WeekDay(Date) = vbSaturday Then
' Do Weekend stuff
End If

The End If statement is crucial; it tells VBA at what point you’re finished
telling it what to do. It ends the block of statements that make up the chunk of
code.

Try out For example, the procedure ValidateData in basIfThen uses the If…Then
ValidateData in statement to validate user input:
basIfThen

Public Sub ValidateData()


Dim strInput As String, strMsg As String
Dim intInput As Integer

strMsg = "Please enter a value greater than 0."


' Prompt user for number.
strInput = InputBox(strMsg)
' Convert string to integer.
' This will fail if input is not numeric!
intInput = CInt(strInput)
' Check whether input is valid.
If intInput <= 0 Then
MsgBox "Invalid number!"
End If
End Sub

VBA Foundations for Microsoft Office 5-3


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Mastering VBA Control Structures

NOTE VBA also supplies a special case version of If…Then that can
exist on a single line. In that case, you don’t need to provide the
End If at the end of the block. Most developers seldom use this
construct because it’s difficult to read and limited in use.

TIP If you are checking a value to see whether it’s True or False, you can leave
the comparison operator out of the If…Then statement. That is, the following
two lines of code are equivalent:

If IsDate(dteTest) Then
' is the same as
If IsDate(dteTest) = True Then

If...Then...Else[If]...End If
If you require more than a single condition, and the conditions are mutually
exclusive, you may find that ElseIf may be what you need.

The general syntax is:

If <condition1> Then
<statement block 1>
ElseIf <condition2> Then
<statement block 2>
...
Else
<statement block 3>
End If

You can have as many ElseIf’s as you want (0, or more) but only a single Else.
The Else clause catches any condition you’ve not checked for explicitly, and is
optional.

Run InputType in As an example, look at the function InputType in basIfThen. This function
basIfThen prompts the user for a value, then checks whether the value is a numeric value,
a date, or an alphanumeric text string.

The code looks like this:

5-4 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Branching Structures

Public Sub InputType()


Dim strInput As String, strMsg As String

strMsg = "Enter any value."


' Prompt user for number.
strInput = InputBox(strMsg)

' Check whether input is numeric, a date,


' or alphanumeric (text).
If IsNumeric(strInput) Then
strMsg = "You entered a number."
ElseIf IsDate(strInput) Then
strMsg = "You entered a date."
Else
strMsg = "You entered a string."
End If
' Display response.
MsgBox strMsg
End Sub

Select Case
The Select Case control structure compares a condition against a single value,
and based on the value, selects a block of statements to execute.

The general syntax looks like this:

VBA Foundations for Microsoft Office 5-5


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Mastering VBA Control Structures

Select Case <expression>


Case <expression 1>
<statement block 1>
Case <expression 2>
<statement block 2>
...
Case Else
<statement block>
End Select

VBA reads the Case options in order until it finds one that matches your
expression. Even if multiple Case options are True, only the first Case option
is executed.

If you have multiple conditions you must test against, you’ll find the Select
Case structure easier to use than If...Then...ElseIf...End If.

You have several options for how you compare the expression. You can use a
delimited list (separated with commas) of any of the following forms:

• Expression
• Expression To expression
• Is comparisonOperator expression
For example, the following expression is valid, and will match against a vowel,
the digits 0 through 9, and any letter greater than “M”:

Case "A", "E", "I", "O", "U", "0" to "9", Is > "M"

A Simple Date Example

See TestYear in The following function takes an argument of type Date. It evaluates the year
basSelect portion of the date within a Select Case statement.

5-6 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Branching Structures

Public Sub TestYear(dte As Date)


Dim lngYear As Long, lngThisYear As Long

' Get the year portion of the date.


lngYear = Year(dte)

lngThisYear = Year(Date)

Select Case lngYear


Case lngThisYear - 1
Debug.Print "Last year"
Case lngThisYear
Debug.Print "This year"
Case lngThisYear + 1
Debug.Print "Next year"
Case Else
Debug.Print "Some year"
End Select
End Sub

A Client Name Example


Imagine that as part of an application, you need to group clients by the quartile
of the alphabet in which their last name falls. (Okay, it doesn’t work out
evenly, but it’s close!)

See CalcQuartile in In this application, you want to know how many people you have in the range
basSelect from A-F, G-L, M-S, and T-Z. To do this, you must have a function that, given
a name, will calculate the appropriate quartile value.

VBA Foundations for Microsoft Office 5-7


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Mastering VBA Control Structures

Public Function CalcQuartile(strValue As String) _


As Integer
' Calculate the quartile of the alphabet for
' the first letter of varValue.

' The breakdown is: A-F (1), G-L (2),


' M-S (3), T-Z (4)

' This example, in an attempt to show all the


' possible ways to use the Case statement, is
' possibly more complex than necessary.

Dim strCh As String

strCh = UCase(Left(strValue, 1))


Select Case strCh
Case "A" To "Z"
Select Case strCh
Case "A", "B", "C", "D", "E", "F"
CalcQuartile = 1
Case "G" To "L"
CalcQuartile = 2
Case Is <= "S"
CalcQuartile = 3
Case "T" To "Z"
CalcQuartile = 4
End Select
Case Else
CalcQuartile = 0
End Select
End Function

5-8 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Branching Structures

GoTo
It’s true; VBA supports the humble GoTo statement. GoTo was nearly the
death of Basic in the 80s. Basic got a bad reputation because in its infancy,
GoTo was Basic’s only branching control structure. This led to ugly, hard-to-
read, and hard-to-maintain code.

However, even with all the different branching methods available, there are
times when GoTo has its place in VBA programming.

GoTo allows you to jump, unconditionally, to a label or line number in the


current procedure. Although you can still number your lines in VBA just as
you could in GW-BASIC in 1983, we recommend that you don’t. Instead, if
you need to jump to a specific line, provide a label for that line.

The line label must begin with an alphabetical character and end with a colon.
No matter what you would like it to do, GoTo can only jump to a label within
its own procedure.

You’ll seldom have a reason to use GoTo, except to use it for error handling,
which is covered in a later section. One common way to use GoTo is to use it
to jump to an exit point. For example, if your procedure determines early on
that it must exit, rather than continue processing you can use GoTo, as the
following procedure shows:

Public Sub GoToTest()


' There’s no example in the sample file
' for this.

If someBadCondition Then
GoTo ProcedureExit
End If

' Handle the normal stuff.


' You'd only use this technique if this
' section of the code was long, or heavily indented.

ProcedureExit:
' Clean up for exit
End Sub

VBA Foundations for Microsoft Office 5-9


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Mastering VBA Control Structures

There are other ways to solve this problem, but GoTo is commonly used in this
situation and offers the advantage of providing a common exit point for the
procedure, no matter what happens when it is running.

5-10 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Looping Structures

Looping Structures

What is a Loop?
A looping structure allows you to repeat a set of statements in code. You
control the number of times your statements execute by using either a
condition or a fixed number that terminates the loop. Figure 1 displays a
schematic diagram of a loop.

Figure 1. Repeat while/until some condition, or set a number of times.

VBA has a variety of looping structures that fall into two overall types: Do
loops, and For...Next loops.

Do...Loops
This is the simplest form of the Do…Loop construct:

Do
<statements>
Loop

See Overflow in Here’s an example that uses this construct:


basLoop

VBA Foundations for Microsoft Office 5-11


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Mastering VBA Control Structures

Public Sub Overflow()


Dim byt As Byte

Do
byt = byt + 1
Debug.Print byt
Loop
End Sub

NOTE We use the Byte data type here simply to facilitate demonstration.
Because a Byte variable can only hold values between 0 and 255,
we don’t need to wait very long to see the results of our infinite
loop. In practice, you don’t typically use the Byte data type to
work with numeric values.

The problem here, of course, is that this loop won’t stop executing until a
memory overflow occurs. In practice, you don’t want a loop to execute until
this happens; you want it to execute a particular number of times, then stop.

In order to jump out of a Do loop early, you need to use the Exit Do statement.

Jumping Out Early


VBA allows you to exit from a loop before its natural finish. You can use the
Exit Do statement to end looping, and jump to the line following the Loop
statement.

See ExitLoop1 in For example, the following procedure will loop until it hits a specific value,
basLoop and will then jump out of the loop:

5-12 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Looping Structures

Public Sub ExitLoop1()


Dim byt As Byte

Do
byt = byt + 1
Debug.Print byt
If byt = 255 Then
Exit Do
End If
Loop
End Sub

You can also use a Do While or Until loop to exit the loop once a certain
condition is met.

Do…Loop with Conditions


Use this construct to loop, executing one or more statements, while some
condition is True, or until some condition becomes True.

You can check for the condition before you execute the statements, or after.
Table 1 displays the four ways you can loop with Do Loop.

Loop Until Condition is True Loop While Condition is True

Check Do Until <condition> Do While <condition>


condition at <statements> <statements>
top of loop Loop Loop

Check Do Do
condition at <statements> <statements>
bottom of loop Loop Until <condition> Loop While <condition>
(always
executes at
least once)
Table 1. Possible Do…Loop syntax options.

See ExitLoop2 - Let’s look at the different ways that you can use a condition to exit a Do loop.
ExitLoop5 in
basLoop
First, you can use the Until statement at the beginning of a loop to loop until a

VBA Foundations for Microsoft Office 5-13


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Mastering VBA Control Structures

particular condition is True. In this case, we only enter the loop if the value of
the byt variable is not equal to 255, and loop until it equals 255.

Public Sub ExitLoop2()


Dim byt As Byte

Do Until byt = 255


byt = byt + 1
Debug.Print byt
Loop
End Sub

You can also use the While statement to check for the converse condition. In
this case, the loop also executes as long as the byt variable is not equal to 255.

In other words, it behaves identically to the previous example.

Public Sub ExitLoop3()


Dim byt As Byte

Do While byt <> 255


byt = byt + 1
Debug.Print byt
Loop
End Sub

Which one should you use? It really doesn’t matter. Consider the following:
Do you always want to execute the loop at least once? If so, you should place
the condition at the end of the loop, as in one of the following examples:

5-14 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Looping Structures

Public Sub ExitLoop4()


Dim byt As Byte

Do
byt = byt + 1
Debug.Print byt
Loop Until byt = 255
End Sub

' or

Public Sub ExitLoop5()


Dim byt As Byte

Do
byt = byt + 1
Debug.Print byt
Loop While byt <> 255
End Sub

Which Type of Loop is Best?


How do you decide which type of loop to use?

• If you want to execute the statements at least once, no matter how the
condition evaluates, place the condition after the Loop statement. You
might do this if, for example, you’re asking for a password. The code
inside the loop would prompt for the password, and If statement would
check it and exit the loop if the password is correct. If the password is
incorrect, the loop repeats.
• If the loop might never execute, place the condition at the top, next to
the Do statement. For example, if you are looping through a table and
the table might be empty, you can use the condition on the Do
statement to check for an empty table.
• Choose Until or While depending on the truth status of your condition:
∗ If you want to loop while your condition is True, use While.
∗ If you want to loop while your condition is False, use Until.

VBA Foundations for Microsoft Office 5-15


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Mastering VBA Control Structures

For...Next
If you want to execute a set of statements a fixed number of times, rather than
checking a condition, use the For...Next control structure. The For...Next
structure uses a counter variable whose value increases or decreases with each
repetition of the loop, automatically. You can set the size of the increment with
the Step directive.

For...Next Syntax

For variable = StartValue To EndValue [Step increment]


statement1
statement2

[Exit For]
statement N
Next [variable]

Here are the details:

• The counter is a variable you declare as a numeric or variant data type.


• You can replace StartValue and EndValue with constants, or with
numeric expressions. You can also use variables, so the endpoints
aren’t known until run time.
• If you omit the Step directive, the loop increments in steps of 1. If you
include it, increment can be any positive or negative number.
• If StartValue is greater than EndValue, two things can happen. If the
increment value is negative, the loop will run as expected. If the
increment value is omitted or is positive, the loop will never execute.
• You can exit the loop with Exit For, but we don’t recommend this,
unless it saves lots of redundant code.
• Although you are allowed to change the value of the variable from
within the code, effectively short-circuiting the loop, do not do this.
This is extremely poor coding style. Instead, use an If...Then construct
inside the loop, or use Exit For instead.
• The counter variable after the Next statement is optional. It’s best to
include it so that others reading your code can easily track the counter.
This is especially important if the For...Next structure is lengthy or
you nest multiple loops.

5-16 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Looping Structures

Using For...Next

See SimpleLoop in Here’s a simple procedure that demonstrates how the For…Next loop works.
basLoop

Public Sub SimpleLoop(lngNum As Long)


Dim lngI As Long

For lngI = 0 To lngNum


Debug.Print lngI * 100
Next lngI
End Sub

The number that you pass to the function becomes the upper limit for the loop,
and the loop executes lngNum + 1 times. The 1 is added because the loop
begins counting at 0.

The following function uses For...Next to calculate factorials of integers. (The


factorial of a number is the product of the number, and each of the numbers
smaller than it. Factorial(5) will return 5*4*3*2*1, or 120).

Try Factorial in The code uses For...Next to loop backwards, starting at the value you pass to
basLoop the function, accumulating the products. It stops when it gets to 2, because
there’s no need to multiply by 1. That would just be a waste of time.

VBA Foundations for Microsoft Office 5-17


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Mastering VBA Control Structures

Public Function Factorial(intNumber As Integer) _


As Variant
Dim intI As Integer
Dim varOut As Variant

' Better initialize varOut, because


' VBA initializes it to Empty!
varOut = 1

' No point looping back to 1 -- that's


' just a waste of time.
For intI = intNumber To 2 Step -1
varOut = varOut * intI
Next intI
Factorial = varOut
End Function

For Each...Next

There’s actually another control structure available to VBA programmers. For


Each...Next loops through each element of a collection, allowing you to work with
each item in the collection, one at a time. When collections are covered in more detail,
in a later chapter, you’ll learn about For Each...Next.

5-18 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Looping Structures

Summary
• Execute conditional statements by using the If...Then or the Select
Case statements.
• The Else clause in an If...Then...ElseIf...Else...End If statement, and
the Case Else clause in a Select Case statement handle the “under any
other condition” situation. Make sure that’s what you mean.
• Avoid the GoTo branching construct, for the most part. It can lead to
difficult-to-read code.
• A loop allows you to repeat blocks of statements while or until some
condition is True, or a set number of times.
• After a Do While...Loop construct, you can assert that the test
condition is False. After a Do Until...Loop, you can assert that the test
condition is True.
• You can use Exit Do to exit a Do loop.
• Use For...Next to execute a series of statements a fixed number of
times.

VBA Foundations for Microsoft Office 5-19


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Mastering VBA Control Structures

(Review questions and answers on the following pages.)

5-20 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Looping Structures

Questions
1. Write an If...Then statement that checks to see if one number is greater
than another (intItem1 and intItem2), and if so, displays a message box
saying “Number 1 is greater than Number 2.” Otherwise, display nothing.

2. Write a Do...Loop that loops from 10 back to 1 (use a variable named


intItem). Use Debug.Print to display the value of each number. Don’t
forget to initialize intItem to the correct starting value.

3. Write a For...Next loop that loops from 1 to 100, and prints only the value
50 to the Debug window, at the time when the loop counter becomes 50.

VBA Foundations for Microsoft Office 5-21


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Mastering VBA Control Structures

Answers
1. Write an If...Then statement that checks to see if one number is greater
than another (intItem1 and intItem2), and if so, displays a message box
saying “Number 1 is greater than Number 2.” Otherwise, display nothing.
If intItem1 > intItem2 Then
MsgBox “Number1 is greater than Number 2”
End If

2. Write a Do...Loop that loops from 10 back to 1 (use a variable named


intItem). Use Debug.Print to display the value of each number. Don’t
forget to initialize intItem to the correct starting value.
IntItem = 10
Do
Debug.Print intItem
intItem = intItem - 1
Loop Until intItem = 0
(There’s a zillion other possible solutions.)

3. Write a For...Next loop that loops from 1 to 100, and prints only the value
50 to the Debug window, at the time when the loop counter becomes 50.
For intI = 1 To 100
If intI = 50 Then
Debug.Print intI
End If
Next intI

5-22 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware, LLC. Reprinted with permission.
Lab 5:
Mastering VBA Control Structures

Lab 5:
Mastering VBA
Control Structures
TIP: Because this lab includes a great deal of typed code, we’ve tried to make it
simpler for you. You’ll find all the code in Mastering VBA Control
Structures.txt, in the same directory as the sample project. To avoid typing
the code, you can cut/paste it from the text file instead.

VBA Foundations for Microsoft Office 5-23


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware. Reprinted with permission.
Lab 5:
Mastering VBA Control Structures

Lab 5 Overview
In this lab you’ll learn about VBA control structures and how you can use
them to direct the flow of execution.

To complete this lab, you’ll need to work through four exercises:

• Use If…Then/Else…End If
• Use Select Case
• Use a Do…Loop
• Use a For…Next Loop
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 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware. Reprinted with permission.
Use If…Then/Else…End If

Use If…Then/Else…End If

Objective
In this exercise, you’ll write a function named Max that accepts two Variant
values and returns the value of the one that’s larger. When you test the
function from the Immediate window, it will look like Figure 2.

Figure 2. Your Max function will work with arguments of any type.

Additional Information
You can compare two of almost any data type to determine which is greater.
For this simple function, all you care about is the result of using the “>”
operator to compare two values.

When comparing values, as soon as you determine that the first value is not
greater than the second value, then you know that the second value is either
greater then or equal to the first value. This means that after you check the first
value, you don’t have to explicitly check the second value. If the first value is
not greater than the second value, then it’s safe to assume that you can return
the second value.

Step-by-Step Instructions
1. Open the Control Structures Lab.xls file.

2. Open the Visual Basic Editor.

VBA Foundations for Microsoft Office 5-25


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware. Reprinted with permission.
Lab 5:
Mastering VBA Control Structures
3. Select Insert|Module from the menu to add a new module to the project.
In the Properties window, change the Name property for the module to
basControl.

4. Type the following text:

Public Function Max(varValue1 As Variant, _


varValue2 As Variant) As Variant
' Return the larger of the two
' values passed in.
If varValue1 > varValue2 Then
Max = varValue1
Else
Max = varValue2
End If
End Function

5. Press CTRL+G to move focus to the Immediate window. Try the following
tests to make sure your function works correctly:

? Max(12, -1)
? Max(1, 2)
? Max("Hello", "There")

6. Save the workbook.

5-26 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware. Reprinted with permission.
Use Select Case

Use Select Case

Objective
In this exercise, you’ll create a sub procedure named TestSelect that displays a
message box with Abort, Retry, and Ignore buttons, and asks the user to select
one. Once the user has selected a value, the procedure should display a
message box indicating which item the user selected. Figure 3 shows how the
message box should look, and Figure 4 shows the response back to the user.

Figure 3. The message box displayed and awaiting a response.

Figure 4. Once you get a response, tell the user what happened.

Additional Information
The MsgBox function returns a value that indicates which button the user
selected. In previous exercises, you’ve ignored the return value. In this
exercise, however, you must store the return value in a variable and then
compare it to each of the possible values using Select Case.

Step-by-Step Instructions
1. Open the basControl module created in the previous step.

2. Add the following procedure:

VBA Foundations for Microsoft Office 5-27


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware. Reprinted with permission.
Lab 5:
Mastering VBA Control Structures

Public Sub TestSelect()


Dim intReturn As Integer

intReturn = MsgBox("Select a button", _


vbAbortRetryIgnore + vbExclamation, _
"Control Structures Lab")

Select Case intReturn


Case vbAbort
MsgBox "You chose to abort", , _
"Control Structures Lab"
Case vbRetry
MsgBox "You chose to retry", , _
"Control Structures Lab"
Case vbIgnore
MsgBox "You chose to ignore", , _
"Control Structures Lab"
End Select
End Sub

3. Press CTRL+G to move to the Immediate window. From the Immediate


window, call TestSelect as follows, repeating the test until you’re
convinced that it works:

Call TestSelect

4. Save the workbook.

5-28 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware. Reprinted with permission.
Use a Do…Loop

Use a Do…Loop

Objective
In this exercise, you’ll write a function named GetInput that prompts the user
to enter text into an input box until they cancel the input box. After the user
cancels, display a message box that shows all of the values the user typed.

Additional Information
As you saw in a previous lab, the InputBox function returns a string containing
the user’s input into the dialog box. If the user clicks the Cancel button, or
clicks OK without entering any text, then the InputBox function returns an
empty string.

You can use the InputBox function within a loop to get multiple inputs from
the user. The key is to create a loop that checks for the condition where the
InputBox function returns an empty string. Either a Do While loop or a Do
Until loop will work. When the user clicks Cancel, the loop finishes its current
execution and doesn’t execute again.

You want the loop to execute at least once, so that the user is prompted at least
once; therefore, you should place the condition at the end of the loop.

Within the loop, you can keep track of how many times the loop has executed
by incrementing a counter variable. That way, you can prompt the user to enter
item #1, item #2, and so forth.

The other thing you want to do within the loop is to keep track of all of the
user’s inputs. You can do this by concatenating them into a string. Each time
through the loop, the new input is added to the string. When the loop exits, you
can display this string in a message box to show the user all of their input
values.

Step-by-Step Instructions
1. Open the basControl module created in the previous exercise.

2. Add the following procedure. Keep in mind that you don’t have to type the
comments; they’re there to help you understand the code:

VBA Foundations for Microsoft Office 5-29


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware. Reprinted with permission.
Lab 5:
Mastering VBA Control Structures

Public Sub GetInput()


Dim strInput As String
Dim strList As String
Dim intCount As Integer

' Initialize counter variable.


' This isn't necessary, since an integer
' variable is initialized to 0, but it
' clarifies the code.
intCount = 0

' Execute loop at least once.


Do
' Increment counter variable
' each time through loop.
intCount = intCount + 1
' Prompt user for input.
strInput = InputBox("Enter Item #" _
& intCount & "; click Cancel to stop.")
' Concatenate this string to previous input.
strList = strList & strInput & vbCrLf
' Loop until the user cancels.
Loop Until Len(strInput) = 0

' Check whether string contains data.


' If user cancelled on first time through
' loop, strList will still contain the two
' carriage return/line feed characters.
If Len(strList) > 2 Then
MsgBox strList
End If
End Sub

3. Test GetInput by pressing F5 from within the procedure.

5-30 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware. Reprinted with permission.
Use a For…Next Loop

Use a For…Next Loop

Objective
In this exercise, you’ll write a function named MultiInput that uses a
For…Next loop to prompt the user for a set number of input items. The user is
first prompted for the number of input items, and then prompted for each input
item.

Additional Information
The For…Next loop is useful for repeating a group of statements when you
know exactly how many times you wish to repeat the statements. The loop
begins with a For statement that specifies the number of repetitions and ends
with a Next statement that causes the program to return to the beginning of the
loop until the specified number of repetitions has been completed. The For
statement includes a counter variable which is increased or decreased by a
specified increment with each repetition of the loop. If you do not specify an
increment, a default value of 1 is used.

Step-by-Step Instructions
1. Open the basControl module created in the previous step.

2. Add the following procedure:

VBA Foundations for Microsoft Office 5-31


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware. Reprinted with permission.
Lab 5:
Mastering VBA Control Structures

Public Sub MultiInput()


Dim intHowMany As Integer
Dim intCount As Integer
Dim strInput As String
Dim strList As String

' Prompt user for # of items.


intHowMany = InputBox("Enter # of items")
For intCount = 1 To intHowMany
' Prompt user for input.
strInput = InputBox("Enter Item #" _
& intCount & "; click Cancel to stop.")
' Concatenate this string to previous input.
strList = strList & strInput & vbCrLf
Next intCount

' vbCrLf = two characters


' (Carriage return + Line feed)
If Len(strList) > 2 Then
MsgBox strList
End If
End Sub

3. Run MultiInput by pressing F5 from within the procedure and respond to


the prompts accordingly.

Call MultiInput

4. Save the workbook.

5-32 VBA Foundations for Microsoft Office


Copyright © 2002 by Application Developers Training Company and AppDev Products, LLC
Licensed to IT Courseware. Reprinted with permission.

You might also like