Sei sulla pagina 1di 261

Professional Skills Development

Getting Started
with VBA

• Practical approach to skills development

• Nationally recognized developer-instructors

• Variety of classroom and self-study formats

www.appdev.com
7610 Executive Drive • Eden Prairie, MN 55344 • 800-578-2062
Table of Contents

Getting Started with VBA


Table of Contents

Introduction ...................................................................................................................I-1
A Few Words About This Courseware ...............................................................I-2
World-Class Courseware Taught by World-Class Instructors .................I-2
What We Expect of You .........................................................................I-2
What You’ll Get Out of this Class ...........................................................I-2
Courseware Conventions .......................................................................I-3
The Example Files.............................................................................................I-4
Getting Started with VBA..............................................................................................1-1
What Is VBA? ...................................................................................................1-2
Why Would You Want to Use VBA?......................................................1-2
VBA Host Implementations ...............................................................................1-4
Microsoft Office 2000 versus Microsoft Office 97 ..................................1-4
Who Has Licensed VBA? ......................................................................1-5
What Does a VBA Application Look Like? ........................................................1-6
A Familiar Application ...........................................................................1-6
Custom Dialog Boxes............................................................................1-6
Custom Toolbars and Menus ................................................................1-7
Buttons and Things ...............................................................................1-7
Behind-the-Scenes Operations .............................................................1-8
Code Underneath It All..........................................................................1-8
Working with VBA...........................................................................................1-10
Where Does VBA Code Live? .............................................................1-10
How Do You Make VBA Code Happen? .............................................1-11
Creating a Simple Procedure..........................................................................1-13
Understanding Functions ....................................................................1-13
Your First VBA Function (Try It Out!)...................................................1-14
Useful Concepts..................................................................................1-18
Running Your Function from Word ......................................................1-20
Creating a Simple Sub Procedure...................................................................1-22
Running a Sub Procedure ...................................................................1-22
Working with Variables.................................................................................................2-1
Introduction to Variables ...................................................................................2-2
What Is a Variable?...............................................................................2-2
An Example...........................................................................................2-2
Give Your Variables Meaningful Names................................................2-3

Getting Started with VBA TOC-1


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Table of Contents

Variables and Data Types ................................................................................2-4


Variable Types ......................................................................................2-4
Choosing a Data Type ..........................................................................2-4
Declaring Variables ...............................................................................2-5
Initializing Variables ..............................................................................2-8
The Variant Data Type ..........................................................................2-9
Implicit vs. Explicit Declarations ..........................................................2-11
Using Constants .............................................................................................2-14
Using the MsgBox Function ................................................................2-14
Creating Your Own Constants.............................................................2-17
Creating User Forms....................................................................................................3-1
Working with User Forms .................................................................................3-2
What Are User Forms? .........................................................................3-2
Creating a New User Form....................................................................3-2
Design Mode vs. Run Mode ..................................................................3-3
Adding Controls to a User Form .......................................................................3-5
What Are ActiveX Controls?..................................................................3-5
Introducing a Few ActiveX Controls ......................................................3-5
Manipulating Controls on a User Form .............................................................3-8
Selecting a Control................................................................................3-8
Moving a Control...................................................................................3-8
Resizing a Control.................................................................................3-8
Working with Multiple Controls ..............................................................3-9
Deleting Controls ..................................................................................3-9
Formatting Controls.............................................................................3-10
Setting Properties ...........................................................................................3-11
Working with the Properties Window...................................................3-11
A Few Common Properties .................................................................3-13
Designing a Simple Dialog Box.......................................................................3-16
Introducing Events..........................................................................................3-18
Event Procedures ...............................................................................3-18
Creating an Event Procedure ..............................................................3-19
The Click Event...................................................................................3-20
The Change Event ..............................................................................3-21
More Built-In Controls .....................................................................................3-23
Basic Data Entry Controls ...................................................................3-24
List and Combo Boxes ........................................................................3-25
SpinButton, ScrollBar, and Image Controls .........................................3-26
The MultiPage Control ........................................................................3-27

TOC-2 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Table of Contents

Creating and Running Procedures ...............................................................................4-1


Writing Procedures in the Visual Basic Editor ...................................................4-2
Creating a New Procedure ....................................................................4-2
Moving Code Around ............................................................................4-4
Saving and Printing Code......................................................................4-4
Viewing Multiple Procedures .................................................................4-5
Formatting Code ...................................................................................4-5
Commenting Out Code .........................................................................4-6
Setting a Bookmark...............................................................................4-6
Taking Advantage of IntelliSense......................................................................4-7
List Properties/Methods (CTRL+J) ..........................................................4-7
List Constants (CTRL+SHIFT+J) ..............................................................4-7
Parameter Info (CTRL+SHIFT+I) ..............................................................4-8
Word Completion ..................................................................................4-8
Using the Immediate Window .........................................................................4-10
The Immediate Window ......................................................................4-10
Writing Debug Information to the Immediate Window from VBA..........4-10
Calling Sub Procedures ......................................................................4-10
Calling Functions ................................................................................4-12
Investigating Built-In Functions .......................................................................4-13
VBA’s Built-In Functions......................................................................4-13
Strings.................................................................................................4-13
Dates and Times.................................................................................4-13
Conversion..........................................................................................4-14
Other...................................................................................................4-14
Other Functionality in VBA ..................................................................4-15
Optional and Named Arguments.....................................................................4-19
Introducing Named Arguments............................................................4-19
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-3
Select Case...........................................................................................5-5
GoTo.....................................................................................................5-8
Looping Structures ...........................................................................................5-9
What Is a Loop?....................................................................................5-9
Do...Loops ............................................................................................5-9
Do…Loop with Conditions...................................................................5-11

Getting Started with VBA TOC-3


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Table of Contents

For...Next ............................................................................................5-13
Understanding Events..................................................................................................6-1
Events and Event Procedures ..........................................................................6-2
What Did You Just Do?.........................................................................6-2
How Does frmLogEvents Work? ...........................................................6-3
Where To from Here? ...........................................................................6-5
Which Objects Have Events? ...........................................................................6-6
User Form Events.............................................................................................6-7
The UserForm Initialize Event ...............................................................6-7
The UserForm QueryClose Event .........................................................6-8
Event Procedure Arguments .................................................................6-9
Control Events ................................................................................................6-11
Keyboard Events.................................................................................6-11
Mouse Events .....................................................................................6-13
VBA Host-Specific Events ..............................................................................6-16
Word Document Events ......................................................................6-16
The Worksheet Change Event ............................................................6-18
Is There More? ...............................................................................................6-19
Other Events .......................................................................................6-19
Manipulating Form and Control Properties ...................................................................7-1
Setting Properties at Run Time.........................................................................7-2
Setting Property Values ........................................................................7-2
Retrieving Property Values....................................................................7-2
Setting Form Properties....................................................................................7-4
Changing the BackColor .......................................................................7-4
Changing a Form’s Mouse Cursor.........................................................7-5
Setting Control Properties.................................................................................7-7
Data Entry Controls...............................................................................7-7
Text Box Properties...............................................................................7-9
An Introduction to Objects ............................................................................................8-1
What Is an Object? ...........................................................................................8-2
Object Models .......................................................................................8-2
The Microsoft Excel Object Model.........................................................8-3
The Microsoft Forms Object Model .......................................................8-4
The Object Browser ..........................................................................................8-5
Opening the Object Browser .................................................................8-5
The Parts of the Object Browser ...........................................................8-5
Figuring Out the Object Hierarchy .........................................................8-7

TOC-4 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Table of Contents

Working with Objects in VBA ............................................................................8-8


Referring to Objects in Collections ........................................................8-8
Referring to Collections Within Objects .................................................8-9
Setting Properties on Objects..............................................................8-10
Taking Action: Methods.......................................................................8-11
Using Object Variables ...................................................................................8-13
Introducing Object Variables ...............................................................8-13
Using Object Variables........................................................................8-14
What About Uninitialized Object Variables? ........................................8-15
Special VBA Constructs for Objects................................................................8-16
Introducing For Each...Next.................................................................8-16
A Simple Example...............................................................................8-16
Differentiating Types of Controls .........................................................8-17
Referring to Objects on Forms ............................................................8-19
Using With...End With .........................................................................8-19
Programming Word and Excel......................................................................................9-1
The Excel Object Model....................................................................................9-2
Microsoft Excel’s Top-Level Objects .................................................................9-3
The Application Object ..........................................................................9-3
The Workbook Object ...........................................................................9-3
The Worksheet Object ..........................................................................9-5
The Range Object ............................................................................................9-6
Referring to a Range.............................................................................9-6
The Word Object Model....................................................................................9-9
Word’s Top-Level Objects ..............................................................................9-10
The Application Object ........................................................................9-10
The Document Object .........................................................................9-10
The Selection Object...........................................................................9-12
Manipulating Text with the Range Object........................................................9-13
What’s a Range? ................................................................................9-13
Referring to a Range...........................................................................9-13
Inserting Text ......................................................................................9-14
Creating Integrated Applications with Automation ......................................................10-1
Expanding Your Horizons Using Automation ..................................................10-2
Getting to the Object Model ............................................................................10-3
Setting References..............................................................................10-3
Viewing Other Applications’ Objects....................................................10-4
Creating an Instance of the Application ...............................................10-5

Getting Started with VBA TOC-5


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Table of Contents

A Simple Automation Example ............................................................10-7


Are All Applications the Same? ...........................................................10-8
Example: Building an Excel Chart................................................................. 10-10
Creating a New Workbook ................................................................ 10-10
Transferring Data .............................................................................. 10-12
Creating the Chart............................................................................. 10-13
Complete Procedure Listing .............................................................. 10-15
Appendix A: The Reddick VBA Naming Conventions .................................................. A-1
Changes to the Conventions............................................................................ A-3
An Introduction to Hungarian ........................................................................... A-4
Tags ................................................................................................................ A-5
Variable Tags....................................................................................... A-5
Constant Tags...................................................................................... A-6
Tags for User-Defined Types and Classes........................................... A-6
Collection Tags .................................................................................... A-6
Constructing Procedures ................................................................................. A-7
Constructing Procedure Names ........................................................... A-7
Naming Parameters ............................................................................. A-7
Prefixes ........................................................................................................... A-8
Arrays of Objects Prefix ....................................................................... A-8
Index Prefix.......................................................................................... A-8
Prefixes for Scope and Lifetime............................................................ A-8
Other Prefixes ...................................................................................... A-9
Suffixes.......................................................................................................... A-10
Host Application and Component Extensions to the Conventions.................. A-11
Microsoft Access 97, Version 8.0 Objects .......................................... A-11
DAO 3.5 Objects ................................................................................ A-13
Microsoft Office 8.0 Objects ............................................................... A-16
Index ..................................................................................................................... Index-1

TOC-6 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Introduction

Introduction

Getting Started with VBA Intro-1


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Introduction

A Few Words About This Courseware


World-Class Courseware Taught by
World-Class Instructors
We have worked very hard to bring you what we think are the best VBA
training materials in the world!
Just about everything covered in this class is included in this book and in the
sample files found on the accompanying disk. Thus, you can keep your note
taking to a minimum, while still gaining the maximum benefit from the class.
Every AppDev instructor is both an experienced trainer and a working
developer. Our instructors are among the most knowledgeable and talented
professional developers in the world. Many spend a good deal of their time
creating applications for corporations and government institutions using Visual
Basic and other development tools. Many of our instructors also write articles
and books on software development and are invited speakers at both national
and international development conferences.

What We Expect of You


This class doesn't start at the beginning. To get the most out of this class, you'll
need:
• A basic familiarity with PCs and Windows 95, 98 or NT.
• A basic understanding of how Windows works.
• Some familiarity with programming concepts – although we cover the
basics of programming in VBA, there are many details of
programming, in general, that we can’t teach here.
• The desire to learn.

What You’ll Get Out of this Class


Think of this class as a jump-start to VBA development. After taking this class
you'll:
• Be able to create simple applications using VBA.
• Understand how to create forms, and how to react to events of objects
on forms so that you can “make things happen” in VBA.
• Be familiar with the details of writing VBA code.
• Understand the use of variables, constants, built-in functions, and
control structures in VBA.

Intro-2 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
A Few Words About This Courseware

• Be able to dig into object models of various applications, and be able


to take advantage of these objects from within your VBA applications.

Courseware Conventions
We've followed several conventions to make this courseware easy to follow:
• Each chapter is numbered separately to make it easy to find your
place.
• All examples can be found in the Disk directory on the CD. Follow the
directions in the next section to copy the example files to your hard
disk.
• Examples are noted in the left-hand column.
• The index in the back of the book makes it possible to find specific
sections, after the class is over.

Getting Started with VBA Intro-3


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Introduction

The Example Files


To use the example files, run the Getting Started Examples.exe program
located in the Disk directory on the CD. The examples will be copied onto
your hard disk. They are arranged in folders by chapter. That is, the folder
whose name begins with Ch02 contains all of the samples for chapter 2.

Intro-4 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA

Getting Started
with VBA
Objectives
• Understand what Microsoft Visual Basic for Applications is and why
you might want to use it.
• Learn about different applications that include VBA.
• Learn what kinds of components make up a VBA application.
• Understand where VBA code is contained.
• Create a simple function in Excel and run the same function in Word.
• Create a simple sub procedure.

Getting Started with VBA 1-1


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA

What Is VBA?
Microsoft Visual Basic for Applications (VBA) is a cross-product language
that allows you to automate tasks and create complex, fully functional
applications that take advantage of the Windows environment. VBA is the
programming language for Microsoft Visual Basic and for the Microsoft
Office applications: Microsoft Excel, Access, Word, PowerPoint, Outlook,
FrontPage, and Project.
VBA is one of the most powerful and productive programming languages
available today. Because Microsoft has made VBA licenses available to other
companies, it serves as the programming language for an increasing number of
desktop applications on the market today.
What’s the difference between Microsoft Visual Basic and VBA? Microsoft
Visual Basic is a complete programming environment. It contains many tools
that are necessary for developing a standalone application. VBA is the
language that you use to program in Visual Basic and other applications. Don’t
be confused when you hear programmers refer to VBA as Visual Basic or
VB—the terms are often used interchangeably.
The Microsoft Office applications (and the software products from other
companies that feature VBA) are VBA host applications. They include VBA
along with their own programming environment, which is similar to the one
found in Visual Basic. However, you don’t create standalone applications in a
VBA host application. Instead, you can use VBA to extend and customize the
host application.

Why Would You Want to Use VBA?


Why all the fuss about VBA? VBA brings desktop application development to
a new level. VBA lets you:
• Extend and customize: You can start with a product you’re
accustomed to, and then add new dialog boxes, toolbar buttons, and
menus to the user interface. Behind the scenes you can make the
product perform in the manner that you want it to, and make it appear
seamless to your user.
• Automate common tasks: You can write VBA code to automate
tasks that you would otherwise point and click your way through, over
and over.
• Capitalize on existing applications: Rather than writing an
application from scratch, you can take advantage of the features in
existing products, or even components of products, that Microsoft and
other software companies have spent years designing, developing, and
testing.
• Take advantage of your existing knowledge: If you are already
skilled in using a particular host product (such as Excel), you have a
head start. Once you learn the basics of VBA, you’ll quickly figure

1-2 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA: What Is VBA?

out how to take advantage of it to speed up and enhance operations


you’ve already been performing in the host product.
• Reduce training and support requirements: If your users are
already familiar with a VBA host product, they’ll require less training
and support than if you were introducing them to a new product
created from scratch.
• Capitalize on your programming skills: Since VBA is a common
programming language, the skills you learn while programming in one
product are also applicable to any other product that includes VBA.
• Run the same code in different products: Code that you write in one
product can run in another product. You only need to make
modifications when the code performs operations in one product that
can’t be performed in the other.
• Control another product: You can use VBA to control one host
product from another host product. This effectively combines the
power of both products. For example, you can use Microsoft Excel’s
calculation engine to perform calculations that aren’t available in
Microsoft Access.

Getting Started with VBA 1-3


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA

VBA Host Implementations


Although VBA is a common programming language, different host
applications implement it somewhat differently. The differences between VBA
in the Microsoft Office versions and applications will be briefly discussed
here, and then touched on in later chapters as needed.

Microsoft Office 2000 versus Microsoft


Office 97
VBA has gradually been incorporated into the various Office applications over
the course of several years. The products in Microsoft Office 2000 all include
VBA: Access, Excel, FrontPage, Outlook, PowerPoint, and Word. Each of
these products also includes the standard Visual Basic Editor, which you’ll see
shortly.
Microsoft Office 97 included VBA in Access, Excel, PowerPoint, and Word.
Microsoft Outlook 97/98 supported (and Outlook 2000 still supports)
VBScript, a subset of VBA. Microsoft FrontPage was not part of the Office 97
suite.
The version of VBA used in Office 2000 is VBA 6.0. Office 97 uses VBA 5.0.
Some of the differences between these two versions of the language will be
pointed out throughout the course.

The Visual Basic Editor


If you’re familiar with VBA in Microsoft Visual Basic or in Microsoft Access
97, you’ll find that the Visual Basic Editor is a little different than what you’re
accustomed to. The Visual Basic Editor opens in a separate window, as though
it were its own application. It is dependent on the host application from which
you opened it, however. When you close the application, the Visual Basic
Editor closes as well. Figure 1 shows how Excel and the Visual Basic Editor
might look together on your computer. If the Visual Basic Editor looks foreign
to you, don’t worry—you’ll be quite familiar with it by the time you’ve
completed this course.

1-4 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA: VBA Host Implementations

The Visual
Basic Editor

Figure 1. Microsoft Excel and the Visual Basic Editor appear in separate
application windows.

A Note about Microsoft Access


Microsoft Access has incorporated VBA since the Office 95 version. However,
Microsoft Access 2000 is the first to include the standard Visual Basic Editor.
Previous versions of Microsoft Access integrated VBA directly into their own
user interfaces. If you have only used VBA with an older version of Microsoft
Access, take heart! You will soon see that the language itself is the same—
older versions simply supply a different interface for writing the code.

Who Has Licensed VBA?


Already, well over one hundred companies have licensed VBA to use in their
own products. The applications that will eventually incorporate VBA span an
array of markets, from health care, to financial services, to information
management, to manufacturing. Some of the companies that have licensed
VBA and incorporated it into one or more of their products include
MicroGrafx, Visio, Autodesk, Great Plains Software, Macola, Dow Jones, and
ESRI.
If you want to see a complete list, or you want information about licensing
VBA, check out Microsoft’s VBA Web site, at http://msdn.microsoft.com/vba.

Getting Started with VBA 1-5


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA

What Does a VBA Application Look


Like?
You can do a lot with VBA to extend and customize your application. In
general, you’ll be working with the components that are outlined in this
section. If you’re confused, don’t worry; everything will be explained in more
detail as the course goes on. This section will just give you an idea of the kind
of application you can create, and what it will look like to your users.
This section shows an example in Excel, but you can use the same techniques
in other VBA host applications.

A Familiar Application
A custom VBA application starts with a familiar application, like Word or
Excel. You can add components and write VBA code to make the application
perform the tasks that you need it to. Underneath, it’s still the same application
that you and your users are familiar with.

Custom Dialog Boxes


You can create custom dialog boxes that help the user perform tasks, or that
gather data from the user. Figure 2 shows a custom dialog box in Excel. Notice
that it looks a lot like the dialog boxes you’re probably used to working with,
but perhaps somewhat simpler.

1-6 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA: What Does a VBA Application Look Like?

Figure 2. A custom dialog box running in Excel.

Custom Toolbars and Menus


You can add custom toolbars and menu items, and integrate them with the
components that you add to your application. For example, in the application
in Figure 2, the user opens the form by clicking on the Go To Product button
on the custom toolbar.

NOTE You can create custom toolbars and menus in the Office products,
but not all VBA host products support them.

Buttons and Things


You can add buttons and other user interface elements directly to your
document. The user can click a button, for example, to bring up a dialog box or
to perform a task. Figure 3 shows how a custom button might look on a Excel
worksheet.

Getting Started with VBA 1-7


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA

Figure 3. You can add a custom button to a document.

Behind-the-Scenes Operations
You can add code that will execute when the user performs a particular action,
without the user knowing anything different has happened. For example, you
can write code that saves a document to a server to back it up whenever the
user saves the document to his or her hard drive. Or, you can write code that
opens a custom dialog box whenever a user enters invalid data into a
document.

Code Underneath It All


All of the things you just read about are driven by VBA code. During this
course, you’ll learn how to program in VBA, and how to integrate your code
with documents in order to create full-featured applications.

Try It Out!
Try playing around with the very simple VBA application that you’ve created
Open Ch01.xls in Excel.

1. Open Ch01.xls.

1-8 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA: What Does a VBA Application Look Like?

2. On the Products worksheet, click the Go To Product button on the custom


toolbar.
3. On the form, choose a product from the drop-down list and press the
ENTER key to move to that product. Try different products.
4. Click the Sort button on the Customers worksheet to sort by company
name or by contact name.

Getting Started with VBA 1-9


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA

Working with VBA


Before diving into the course, the rest of this chapter will give you an overview
of VBA and how you can use it from within a host application. A few concepts
will be briefly introduced here and then covered in greater detail later. You
don’t need to learn everything in these first minutes, but by taking an overall
look you will get a better idea of what this course will cover.

Where Does VBA Code Live?


If you’re going to use VBA, you must know where it “lives.” That is, where do
you put the code? How do you make it happen? How do you hook it up? Every
programmer beginning to learn a new development environment must face
these types of questions.
You’ve already learned that you use the Visual Basic Editor to write VBA
code and develop your VBA applications. Within the Visual Basic Editor, you
write code in modules. And within a module, you divide your code into
procedures. Modules and the procedures in them, together with any forms that
your application contains, make up a VBA project.

Key Terms

Module A container for VBA code. Three types of modules are


available: standard modules, form modules, and class modules.
All of these modules appear in the Project Explorer window in
the Visual Basic Editor.

Procedure A self-contained block of VBA code that performs a task or


returns a value. Every procedure has a name and, though that
name may not be unique through an entire application, it must
be unique in its own module.

Project A VBA project stores all of the code that you write and any
components that you add. For the Office applications, each
document has its own VBA project.

Figure 4 shows a module with a simple procedure from an Excel project. You
can tell that it’s an Excel project by the “Book 1” reference in the upper left
corner of the module. This module belongs to Book 1, an Excel workbook.

1-10 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA: Working with VBA

Figure 4. A module with a simple procedure from an Excel project.

How Do You Make VBA Code Happen?


Events
You may be wondering how your VBA code integrates with your application.
The answer is that you write VBA code to react to events. Events occur while
your program is running, and your VBA code can react to them. For example,
when a user clicks a button, your code can run in response to that action. You
can also use events for the “behind-the-scenes” operations described earlier.
The example shown earlier in this chapter used events. When you clicked on
the OK button on the dialog box, an event occurred, and the code associated
with the event ran.

Key Term

Event Something that happens while an application is running that


your code can react to. A mouse click, a timer going off, the
user pressing a key or clicking a button—these are all events to
which your code can react.

The starting point for your code is always an event. The code you write to
respond to an event lives in a special procedure called an event procedure.
When an event occurs that VBA knows about, the code in the corresponding
event procedure runs. This code can then run code in other procedures, and
those procedures can in turn run code in still other procedures.
What kind of events does VBA know about? It recognizes events that occur for
forms in your application, and for controls, which are the components that live
on a form or a document. It also recognizes events that occur for certain
objects in your host application. For example, a Microsoft Excel workbook has
events, and so does a Microsoft Excel spreadsheet. Using a workbook event,
you can write code to perform a certain task when the user opens the
workbook.
Not all code lives in event procedures, of course; they’re just the starting point
for your application. The people using your application will perform actions

Getting Started with VBA 1-11


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA

they’re familiar with, like clicking a button or dropping down a combo box, to
run your code.

The Immediate Window


While you’re developing your application in the Visual Basic Editor, you can
run your code from events, like your end user. If you want to test some code
quickly, however, you can do so in the Immediate window (also sometimes
referred to as the Debug window). This special window, shown in Figure 5,
allows you to try out expressions, execute code, change values, and, of course,
debug your applications. You’ll use the Immediate window throughout this
section, and throughout the entire course.

Figure 5. Use the Immediate window to calculate expressions, run code, and
debug your applications.

TIP: Press CTRL+G at almost any time within the Visual Basic Editor, and you’ll
find the Immediate window available for your use. It’s one of the best tools
for determining why your application isn’t working correctly. Take the time
to get to know the Immediate window. It can save you hours of work, once
you learn how to use it.

1-12 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA: Creating a Simple Procedure

Creating a Simple Procedure


A procedure is a discrete unit of code that performs a specific task. All of the
VBA code that you write will be contained in procedures.
There are two types of procedures that you need to be concerned about as
you’re learning VBA: Function procedures and sub procedures (also known as
subroutines). A function is a procedure that performs an operation and returns
a value. A sub procedure also performs an operation, but it doesn’t return a
value.
When you create your own procedures, you’ll most often create functions.
Think of it this way—even if you’re only executing an action, you’ll often
want to return a success code back to the code that called the procedure, so that
your code can proceed knowing whether the procedure succeeded or failed.
You’ll still work frequently with sub procedures, however. Procedures that
VBA creates for you to respond to events are created as sub procedures. You
can also use a sub procedure when you’re executing an operation that is not
too complicated and is unlikely to fail.

Understanding Functions
Think of a function as a black box; it might take some values as input, and
return a value based on whatever it’s been programmed to do. Figure 6
diagrams a simple function, DoSomething(), that accepts two input values, and
returns a single output value.

Inpu
t Va
lue

Function DoSomething() Output Value

e
Valu
Input

Figure 6. Function DoSomething() accepts two values in, and returns a single
value.

If you’ve ever used a spreadsheet, or a scientific calculator, you’ve used


functions. A simple example is the SUM function in Excel. This function takes
as its input numeric values in a set of cells, and returns the sum of these values,
outputting it to another cell.
VBA includes a number of built-in functions that you’ll want to be familiar
with. You can try these out from the Immediate window. First, however, you
have to know how to call a function from the Immediate window.
Figure 7 shows what it might look like to call a built-in function called the
Format function from the Immediate Window. The Format function takes a

Getting Started with VBA 1-13


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA

date and a specific format string as its input. It returns the date in the format
specified by the format string. The return value is printed on the next line of
the Immediate window.
Function Name First Argument Second Argument

Return value (Visual Basic types this)

Figure 7. Call a function in the Immediate Window, and VBA responds with the
results.

Key Terms

Argument A value you pass to a procedure. Procedures can accept none,


one, or more arguments. Order matters, as does the number of
arguments. If a procedure expects a specific number of values to
be passed to it, it won’t, in general, accept more or less.

Parameter A value received by a procedure. Most people use these two key
words (argument and parameter) interchangeably, and most
likely, your instructor will as well. We’ve presented them both
here just to be completely correct.

NOTE If you’re not going to send any values to the function, you don’t
need to include the empty parentheses; they’re optional.

In the Immediate window, the “?” in the previous example is equivalent to


saying “Please print out the value of the expression that follows.” The single
question mark at the beginning of the line actually stands for the keyword
“Print.” You can use this “?” shortcut from the Immediate window only; you
can’t use it within VBA code in a module.

Your First VBA Function (Try It Out!)


Look at the module basCSZ in Excel, or import CSZ.bas into your
Module basCSZ application.
The scenario: As part of an application you’re writing, you need to take three
pieces of an address (City, State, and Zip), and format them correctly for bulk

1-14 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA: Creating a Simple Procedure

mailing. The Post Office wants these displayed in upper case, with one space
between each portion, and with no punctuation. You could, every time you
need to print an address, do the tiny bit of work necessary to create the
CityStateZip value by hand. But this is a perfect place for a simple function:
• What goes in: the three pieces of information, which are City, State,
and Zip.
• What comes out: the formatted CityStateZip value.
To create a VBA function, you’ll need to open the Visual Basic Editor and
create a module in which to put it, you’ll need to enter the VBA code, and
you’ll need to try it out.
Follow these steps to create your first function:
1. Start Excel.
This example will use Microsoft Excel, but feel free to use a different
application, because this code will run from any VBA host.
2. Create a new workbook in Excel, if one hasn’t been created for you
already.
3. Open the Visual Basic Editor by choosing Tools|Macro|Visual Basic
Editor from the Excel menu.
4. In the Project Explorer, select the project that corresponds to the new
workbook.
5. In the Visual Basic Editor, click the Insert menu, and then choose
Module. This creates a new code module (see Figure 8).

Getting Started with VBA 1-15


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA

Figure 8. A new module in the Visual Basic Editor.

6. Select Insert|Procedure from the menu to bring up the Add Procedure


dialog box (see Figure 9). Enter the name of the new procedure
(BuildCSZ, in this case) and make sure that the Function option button
has been selected. Click OK when you’re ready.

Figure 9. The Add Procedure dialog box is one of many ways you can create a
new procedure.

7. VBA will create the stub of the procedure for you, waiting for you to
enter the code that will do the work. Note that because it cannot guess

1-16 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA: Creating a Simple Procedure

what values you will be sending to the procedure, it allows you to


provide those values yourself.

Public Function BuildCSZ()

End Function

NOTE The “Public” keyword indicates that any other procedure,


anywhere, can call this function. More about Public (and its
opposite, “Private”) will be discussed later in the course.

8. Enter the three parameters for your function, indicating that you’ll be
passing values for City, State, and Zip. These parameters act like
placeholders for the values you’ll give the function when you run it.

Public Function BuildCSZ(City, State, Zip)

End Function

9. Supply the code that does the work inside the function (don’t worry;
the new ideas will be covered in just a minute).

Public Function BuildCSZ(City, State, Zip)


' Convert the separate City, State, and Zip
' fields into a single formatted string.

BuildCSZ = UCase(City & " " & State & " " & Zip)
End Function

10. Give it a try. In the Immediate window, type:

? BuildCSZ("Houston", "TX", 77024)

VBA responds with this text:

HOUSTON TX 77024

Getting Started with VBA 1-17


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA

Congratulations! You’ve written your first VBA function. But what were all
those new words?
• What’s the single quote character (') for? The single quote character
denotes a comment. A comment has no effect when your code runs;
it’s simply for making notes to yourself while you’re developing. You
can (and should) use comments in your code to make notes for
yourself and for other programmers who might need to use your code
someday.
• What’s UCase? The UCase function, built into VBA, converts text to
UPPER CASE.
• Why use “&”? The “&” operator concatenates text together, leaving
no spaces between the two pieces of text. If you had left this out, you
would have gotten an error, because VBA expects an operator to tell it
what to do with the two text strings.
• What’s the " " for? As mentioned in the previous point, the “&”
operator concatenates text with no spaces. If you want an added space
between two pieces of text, you must insert it yourself, using a string
that represents a single space character (" ").
If you had left this out, your function would have returned:

HOUSTONTX77024

This is not exactly what the Post Office wants. Watch out for this in
your code when you’re working with strings; it’s easy to concatenate a
string incorrectly.
• How do you return a value from the function? By assigning a value
to the name of the function itself, VBA knows to send the assigned
value back as the return value of the function. If you don’t take this
step, the function won’t return a value. In this case, you use this
expression to cause BuildCSZ to return the correct value:

BuildCSZ = UCase(City & " " & State & " " & Zip)

NOTE Some of the concepts used to create this sample function weren’t
explained, such as data types for the arguments or the return value
of the function. This was just a simple example to get you started;
these other issues will be discussed in more detail later in the
course.

Useful Concepts
This section will introduce some concepts that will be useful throughout the
course.

1-18 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA: Creating a Simple Procedure

The Line Continuation Character


The line continuation character allows you to continue a line of code on the
following line. This way, you can view all of the code in a procedure without
having to scroll horizontally.
The line continuation character consists of the underscore character (“_”)
preceded by a space. When you type this combination, then hit the ENTER
key, you can continue your code on the next line. Here’s how it looks, using
the previous example:

Public Function BuildCSZ(City, State, Zip)


' Convert the separate City, State, and Zip
' fields into a single formatted string.

BuildCSZ = UCase(City & " " & State _


& " " & Zip)
End Function

If you don’t type the line continuation character correctly, VBA will turn the
line red and notify you that the syntax is incorrect.

Breakpoints
You can use a breakpoint to cause your code to pause at a certain line while
it’s running. At that point, you can examine values in your executing code, or
run the code one line at a time.
To set a breakpoint, choose the Debug|Toggle Breakpoint command from the
menu in the Visual Basic Editor. You can remove a breakpoint using the same
command. A breakpoint in your code appears as shown in Figure 10:

Figure 10. A breakpoint set in code.

Getting Started with VBA 1-19


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA

Printing to the Immediate Window


When you need to know what a particular value is while your code is running,
you can print that value to the Immediate window using the Debug.Print
statement. For example, if you want to know what the value of the City
argument is while BuildCSZ is running, add the following statement to the
BuildCSZ function:

Debug.Print City

Running Your Function from Word


Since VBA is a cross-product language, your VBA code will run in any VBA
host application. Let’s take the function you just created, and run it in Word.

NOTE Keep in mind that when we say your code will run in any host
application, we’re referring to generic code. Code that takes
advantage of a particular application’s functionality may not run in
another application. For example, if you write code that formats a
Microsoft Excel spreadsheet, you’ll have to modify it before you
can use it to format a Word document.

One easy way to share code is to simply drag and drop it into another
application. To drag and drop the basCSZ module into Word, follow these
steps:
1. Start Word and create a new document.
This example will use Word, but feel free to try this with any host
application.
2. Choose Tools|Macro|Visual Basic Editor from the menu to open the
Visual Basic Editor from Word.
3. Notice that when you open the Visual Basic Editor from Word, it
opens in a separate window, just like it did from Excel. Now you may
have both Word and Excel open, and both of their Visual Basic Editors
open as well.
4. Arrange both Visual Basic Editor windows so that you can see them
on the screen at the same time.
5. Select the basCSZ module from the Excel Visual Basic Editor and
drag it to the Word Visual Basic Editor, dropping it onto the entry for
“Project” in the Word Visual Basic Editor Project Explorer. Word
creates a new module in the Word project.
6. You can test the function in Word in the Immediate window, the same
way that you did in Excel:

1-20 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA: Creating a Simple Procedure

? BuildCSZ("Houston", "TX", 77024)

The function works exactly the same as it did in Microsoft Excel.

Getting Started with VBA 1-21


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA

Creating a Simple Sub Procedure


Look at the module basShowDate.
Module
basShowDate As noted earlier, you’ll want to use functions in most cases, but you can use a
sub procedure to perform a simple task when you don’t need to return a value.
Event procedures are a type of sub procedure, and you’ll learn more about
these shortly.
To create and run a sub procedure:
1. Create a new standard module in the Visual Basic Editor.
2. Add the following procedure to the module. You can select
Insert|Procedure from the menu to bring up the Add Procedure dialog
box, or you can just type the procedure into the module.

Public Sub DisplayDate()


' This procedure displays the current date
' in a dialog box.

MsgBox "Today's date is " & Date


End Sub

3. To run the sub procedure, place the cursor within the procedure and click
the Run Sub/UserForm button on the toolbar.
VBA displays a dialog box with the current date. The MsgBox function, which
will be discussed again shortly, displays the dialog box.

Running a Sub Procedure


There are several different ways to run a sub procedure:
• If the sub procedure does not have arguments, you can place the cursor
inside the procedure and click the Run Sub/UserForm button on the
toolbar, or press F5.
• You can call the sub procedure from the Immediate window. Since the
sub procedure doesn’t return a value, you don’t need to include the
“?”; you can just call the sub procedure like this:

DisplayDate

1-22 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA: Creating a Simple Sub Procedure

• You can call the sub procedure from the Immediate window using the
Call keyword. The Call keyword makes it clear that you’re calling a
sub procedure rather than a function.

Call DisplayDate

Getting Started with VBA 1-23


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA

Summary
• VBA is the common programming language available to you in Visual
Basic, Word, Excel, Access, PowerPoint, Project, Outlook 2000, and
in products developed by companies who’ve licensed VBA.
• Using VBA, you can extend and customize products with which
you’re already familiar, and automate common tasks within those
applications.
• When you learn to program in VBA within one application, you can
use your programming skills with any other application that contains
VBA.
• All VBA modules are contained in a VBA project. Modules contain
sub and function procedures.
• A function procedure performs an operation and returns a value.
• A sub procedure performs an operation but doesn’t return a value.
• Events occur when the user interacts with your application. You can
write code in response to events.
• Generic procedures that you create in one VBA host application can be
run as-is from another.

1-24 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA: Creating a Simple Sub Procedure

Questions
1. In what type of container will you find VBA code?
2. Can you have more than one procedure in a given module?
3. What kinds of things can you add to the user interface to customize
your VBA application?
4. What keystroke should you press to bring up the Immediate window?
5. What’s the main difference between a function procedure and a sub
procedure?
6. What does the “&” operator do?

Getting Started with VBA 1-25


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with VBA

Answers
1. In what type of container will you find VBA code?
A module
2. Can you have more than one procedure in a given module?
Absolutely
3. What kinds of things can you add to the user interface to customize
your VBA application?
Forms/custom dialog boxes, toolbar buttons, buttons and
other controls on documents
4. What keystroke should you press to bring up the Immediate window?
Ctrl-G or Alt-V-D, when a module window is active
5. What’s the main difference between a function procedure and a sub
procedure?
A function procedure returns a value, a sub procedure does
not.
6. What does the “&” operator do?
Concatenates two values together, converting them both to
text along the way

1-26 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables

Working with
Variables
Objectives
• Understand what variables are, and how to use them.
• Learn about the different data types in VBA.
• Declare and name variables.
• Understand the variant data type.
• Use built-in constants with VBA functions.
• Create your own constants.

NOTE None of the samples in this chapter run from forms. To try each
sample procedure in this chapter, open the Visual Basic Editor
(VBE), and call the procedure from the Immediate window. You
may find it useful to set a breakpoint on the first line of the
procedure, so you can step through the code. (Click in the left
margin next to an executable line of code to set a breakpoint.)

Getting Started with VBA 2-1


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables

Introduction to Variables
What Is a Variable?
During the execution of program code, you will often have a need to store a
value, temporarily, for later use. You may need to refer to an intermediate step
in a calculation, the result of a calculation, or a specific value. You can supply
your own name for these values, and by doing so you’ve created a variable.
In simple technical terms, a variable is a named memory location.

Key Term

Variable A chunk of memory, set aside by your program, with a specific


name that you supply. You can store and retrieve a value in the
location. You can change the value in your application, as well.

An Example
As part of an application, you’d like to write a little function that takes a first
name and a last name, and returns the name in the format:

LASTNAME, FIRSTNAME

The following example shows a possible solution, but do not consider it final;
there are several issues to cover before finalizing things.

Public Function FixName1(x, y)


' Convert the separate Firstname and LastName
' fields into a single string formatted as
' "LastName, FirstName"
z = Ucase(y & ", " & x)
' Remember, to return a value from a function,
' assign the value to the name of the function.
FixName1 = z
End Function

Try running the function from the Immediate window. Yes, it works, but it has
some serious flaws:

2-2 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables: Introduction to Variables

• What do “x,” “y,” and “z” stand for? That is, what do they mean in the
context of the solution?
• What would happen if you happened to type “x” where you meant to
type “y”?
• How can you tell in what order to use “x” and “y”?
• What kind of data can you store in “z”?

Give Your Variables Meaningful Names


The solution to the first problem mentioned above is simple; give your
variables meaningful names. This allows both you and other programmers to
easily read and understand your code. Keep the following points in mind:
• Variable names can be up to 200 characters long.
• Variable names must begin with a letter.
• Variable names can contain only letters, numbers, and the underscore
character; punctuation characters and spaces are not allowed.
• Variable names cannot be the same as a reserved word.

NOTE A reserved word is a word that VBA uses as part of its own
syntax. These include the names of predefined statements (such as
For and Next), function names (such as Date, or Now), and
operators (such as Or, And, or Mod). You can’t use any of these as
variable names.

Let’s revisit the previous example. This time, you’ll use reasonably named
variables (and parameters, which are treated like variables) rather than just
single letters.

Public Function FixName2(FirstName, LastName)


' Convert the separate Firstname and LastName
' fields into a single string formatted as
' "LastName, FirstName"
FullName = UCase(LastName & ", " & FirstName)
FixName2 = FullName
End Function

Getting Started with VBA 2-3


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables

Variables and Data Types


Variable Types
When using variables in your code, you have the option to declare them to be
of a specific data type, depending upon the nature of the data you expect them
to hold. Table 1 shows the fundamental variable types in VBA.

Data Type Value Range Comment

Byte 0 to 255 Small positive integers.


Boolean -1 or 0 Yes or No values.
Integer -32768 to 32767 Small whole numbers, positive
and negative.
Long -2,147,483,648 to Large whole numbers, positive
2,147,483,647 and negative.
Single approximately 1.4E-45 to Single-precision floating point.
3.4E48 32 bits worth of precision.
Double approximately 4.94E-324 to Double-precision floating point.
1.8E308 64 bits of precision.
Currency -922,337,203,685,477.5808 Calculations involving money,
to 922,337,203,685,477.5807 or where accuracy is very
important. Up to 15-digits to
the left of the decimal, and up
to 4 to the right.
Decimal +/- Variant subtype that stores 96-
79,228,162,514,264,337,593, bit unsigned integers scaleable
543,950,335 by a power of 10. Up to 28
decimal places.
Date January 1, 100 to December Date and time information.
31, 9999
String 0 to 2 billion (or so) Text information.
characters
Variant Can contain any other type, The default data type, if you
Empty, or Null don’t specify one. Can hold
data of any data type.
Table 1. VBA provides these data types for variables.

Choosing a Data Type


Many variable data types in VBA are analogous to the data types available for
field definitions in tables. The main exception is the Variant data type.
• Use Boolean variables to hold values that can only be True or False.

2-4 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables: Variables and Data Types

• Use Byte, Integer, Long, Single, and Double variables to work with
numbers of varying size and precision. Remember that the greater
precision you request, the larger (and slower) the variable. If you only
need to store numbers up to 100, using a Double variable will waste a
lot of processor cycles. You should use an Integer variable instead.
• Use the Currency data type to work with values for which you don’t
need as much precision as you might for a Double variable, but you do
need greater accuracy. Because the other numeric types are converted
back and forth to binary (base 2) as they’re stored and used, there’s
inherently some round-off error as the fractional portion of the number
gets converted. Currency variables are never converted to binary, so
they don’t face the round-off issues.
• Use String variables to hold text. By default, VBA strings are of
variable length—they grow and shrink as necessary based on what you
put in them.

Declaring Variables
You can declare variables in one of two places in a module:
• In a particular procedure.
• In the module’s Declarations section (the area at the very top of the
module).
You have four choices as to the method you use to declare your variable,
summarized in Table 2. These keywords indicate, for a procedure variable,
how long it keeps its value (that is, its lifetime). For a module variable, the
keywords indicate the availability (scope) of the variable.

Keyword Location Functionality

Dim Procedure Variable is available to the procedure in which it is


declared only, and is reinitialized each time the
procedure is called (that is, the variable “dies”
when you leave the procedure). NOTE: This is the
only declaration mechanism that causes variable
values to reset after leaving a procedure.
Static Procedure Variable is kept intact over multiple procedure calls
(that is, the variable maintains its value as long as
the application is running), but is available to the
procedure in which it is declared only.
Private Module Variable is available to all procedures within the
current module, and keeps its value as long as the
application is running.
Public Module Variable is available to any procedure within the
project, and keeps its value as long as the
application is running.
Table 2. Scope and lifetime are dictated by the location of the declaration and the
keyword used.

Getting Started with VBA 2-5


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables

Variables declared within a procedure are called procedure-level variables.


They can be used only by the procedure in which they are declared. To declare
an integer variable within a procedure, you could write code such as this:

Function ShowVariableDeclaration()
Dim intValue As Integer
' or
Static sintValue As Integer
' Code does something here…
End Function

Variables that are declared in a module rather than in a procedure are called
module-level variables, and you declare them in a module’s Declarations
section, at the top of the module (see Figure 1).

Figure 1. Declare module-level variables in the Declarations section.

A private module-level variable is available to all procedures within the


module in which it is declared. A public module-level variable is available to
all procedures in the project. The following lines of code use the Public and
Private keywords to declare variables:

Public mstrName As String


or
Private mstrName As String

2-6 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables: Variables and Data Types

TIP: Although VBA allows you to use the Dim keyword to declare a module-level
variable, don’t. It’s not clear to someone reading your code whether a
variable declared with Dim is Public or Private unless you explicitly say so,
so make things clear by using Public or Private for module variables.

One More Pass


Using this information, let’s make another pass at the FixName function.
Here’s a better solution:

Public Function FixName3( _


FirstName As String, LastName As String) As String
Dim FullName As String
' Convert the separate Firstname and LastName
' fields into a single string formatted as
' "LastName, FirstName"
FullName = UCase(LastName & ", " & FirstName)
FixName3 = FullName
End Function

Getting Started with VBA 2-7


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables

Naming Conventions

If you want to make your code more easily understood by your coworkers, and if you
want to be able to refer back to existing code more than 20 minutes after you wrote it,
we suggest that you adopt a naming standard for your variables. By choosing a naming
standard and sticking with it, other programmers who use the same naming standard
will find it easy to pick up your code and figure out what you were intending to do
when you wrote it. The extra time you may spend typing in slightly longer variable
names will be worthwhile when you need to look back at your code and figure out
what it does.

Though we cannot give you any hard and fast rules, the programmers working on this
course material, and many other programmers working with VBA, have adopted a
coding standard proposed by Gregory Reddick. You’ll find the full discussion of this
standard in Appendix A.

In general, this naming standard proposes that you add a prefix to the base name of a
variable indicating the data type of the variable (more on data types later in the
chapter), with an optional suffix indicating the usage. For example, to create an integer
variable holding a salary, you might use:

Dim intSalary As Integer

You’ll see that this sort of naming has been used throughout this course.

The exact naming standard you use is, of course, up to you. You’ll find that a lot of
VBA programmers use a standard similar to what you’ll see in this course, but feel
free to find the style that fits your needs best. Whatever you do, find a naming standard
and stick with it.

Initializing Variables
If you don’t supply a value for a variable, VBA will supply one for you, when
the variable first comes “into being.” That is, as soon as the variable is created
in memory, it has a default value.
If your variable is a procedure-level variable, it is initialized as soon as the
procedure begins running. This means that the variable will have an initial
value until your code assigns a different value to it.
Table 3 describes the initial values for some different data types:

2-8 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables: Variables and Data Types

Data Type Initialized Value

Numeric data types 0


Strings "" (zero-length string)
Dates 12/30/1899 12:00:00 AM
Boolean False
Variants Empty (A built-in value. Check for this with IsEmpty.)
Table 3. Every variable begins its life with a certain initial value.

The Variant Data Type


The Variant data type is special; it’s large enough to hold data of any of the
other data types. You can assign data of any type into a Variant variable.
Consequently, a Variant-type variable is generally slower and bulkier than
other variable types. On the other hand, its availability in VBA is one of the
strongest features of the language. For the advanced developer, the Variant
type adds a world of possibilities.
You should use the Variant data type when:
• You need to mix data types or write a generic procedure that handles
multiple data types.
• You need to handle null values. VBA does not allow any other data
type to contain the special Null value. (Null values are commonly
found in data read in from database records.)
• You need to be able to tell whether a variable has been initialized. A
Variant that has been initialized contains the special Empty value, and
no other type can contain that value.
• You need to work with data from tables in VBA. Because the Jet
engine (and many other database engines) returns all data to VBA in
variants, converting it to a specific data type wastes time and effort. In
addition, because table data might be Null, and only Variant variables
can contain a null value, you should always use a Variant variable
when working with table data.

TIP: If you have a value in a Variant and need to determine its data type (string,
double, and so forth), you can use the built-in VarType function. Pass
VarType your Variant variable, and it’ll return a value indicating the type of
value in the variable. Check out VarType in online Help for more
information.

Getting Started with VBA 2-9


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables

Two Special Values


Variant variables can contain two special values that no other variables can
See TestEmpty and contain: Null and Empty. Table 4 summarizes their behaviors.
TestNull in
basVariants

Value How Can it Happen? How to Example


Test?

Null Empty fields in tables, IsNull If IsNull(varItem) Then…


or explicitly set using function
varItem = Null. May
also be the value of an
ActiveX control.
Empty Variant that’s never IsEmpty If IsEmpty(varItem) Then…
contained a value, or function
has been reset to
Empty using varItem
= Empty. Generally
only useful with Static
variables (or module-
level variables).
Table 4. The Null and Empty values are similar, but not the same.

Most likely, you’ll use IsNull when working with data from a database, or with
ActiveX controls that usually contain a numeric value. You’ll typically use
IsEmpty only when working with Static variables. IsEmpty provides a way for
you to test whether a variable has been initialized yet.

Too Many Things Sound Alike


In VBA, there are four very “similar-sounding” constructs that are used with
variables. These can be very confusing until you’ve had a reason to use each of
them in code. The constructs are presented in Table 5 as a reference:

Description Variable Contents How it Occurs


Type

Zero-length string String "" A string that contains no


characters. Its length is 0. You can
use the Len function to determine
this: (Len(strItem) = 0).
The value Empty Variant Empty A Variant that has not been
initialized.
The value Null Variant Null A Variant that is initialized but
doesn’t contain a valid value.
The value Nothing Object Nothing An object variable that doesn’t
refer to a real object.
Table 5. You will eventually find a use for each of these similar-sounding values.

2-10 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables: Variables and Data Types

Implicit vs. Explicit Declarations


In many programming languages, such as Pascal and C, you must declare
variables before you use them. This means that you must specifically state the
variable’s name and what type of data it will hold (text, integers, floating-point
numbers, etc.). Although it is a good idea to declare variables and their types
before you use them, VBA does not require this.

Implicit Declaration
If you use a variable you have not declared, VBA creates a variable for you.
When you do not explicitly indicate what type of data you want your variable
to hold, VBA creates a Variant variable, which is initially Empty.
As you might have guessed, this is not considered good programming style.

Explicit Declaration
You’re far better off if you explicitly declare all variables that you use. That
way, your data type intentions will be clear, and VBA will be able to save time
by using just enough space for the variable you’ve declared (rather than using
a Variant).

Option Explicit
If you want to avoid the declaration problem, add the following setting to the
Declarations section of each module:

Option Explicit

This statement tells VBA that you want it to enforce explicit declarations of
each and every variable that you use. Once you’ve added that statement to
your module, you will not be able to use a variable unless you’ve explicitly
declared it.

TIP: You couldn’t possibly overestimate the importance of using Option Explicit
in your modules. It will save you many hours of debugging pain. Do not even
consider working without Option Explicit—any apparent gain in ease of
programming will be far outweighed by the problems it causes when you
have to use that code later.

Setting Option Explicit by Default


You can instruct VBA to insert Option Explicit in each and every module you
create, so you don’t have to remember to do this. To do so, select
Tools|Options from the menu and select the “Require Variable Declaration”
option (see Figure 2) in the Options dialog box.

Getting Started with VBA 2-11


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables

Once you’ve set this option, VBA will place “Option Explicit” into each new
module you create. Your best bet is to set this option and leave it on forever.

Figure 2. Always make sure that the Require Variable Declaration option is
selected.

WARNING! Setting the option in the Options dialog box to require variable
declaration only inserts Option Explicit into new modules. For
existing modules that were created before you told the Visual Basic
Editor to require the variable declaration option, you’ll have to check
for the existence of Option Explicit manually.

One More Visit


For your final visit with FixNames, you’ll add proper declarations with a
naming convention, just to see how it’s done.
Just as you do with variables and parameters, you should declare the return
type of a function, even if it returns the Variant type. This makes your code
easier to read, debug, share, and maintain. It may even help make the code run
faster, because VBA won’t be using Variants unless you specify that it should.

2-12 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables: Variables and Data Types

Public Function FixName4( _


strFirstName As String, strLastName As String) _
As String
Dim strFullName As String
' Convert the separate Firstname and LastName
' fields into a single string formatted as
' "LastName, FirstName"
strFullName = _
UCase(strLastName & ", " & strFirstName)
FixName4 = strFullName
End Function

Getting Started with VBA 2-13


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables

Using Constants
A constant represents a numeric or string value that can’t change. You can use
constants to improve the readability of your VBA code and to make your code
easier to maintain. Rather than sprinkling explicit values all over your code,
you can create a constant that represents that value. That way, if the value must
change at some point, you can just change the constant declaration, rather than
changing every reference in your code. When you use the constant, you don’t
have to think about what its value actually is.
Microsoft provides a number of built-in, intrinsic constants that work
essentially the same way. Most of the time you can work with these constants
in your code without worrying about the actual value that they represent. Many
functions take constant values as arguments.
Microsoft’s intrinsic constants begin with a special two-letter prefix, indicating
their source. For example, constants relating to the Jet engine begin with “db.”
Those that are part of Access begin with “ac,” those that are part of VBA begin
with “vb,” and for Microsoft Office, “mso.” Using intrinsic constants ensures
that your code will continue to work even if the underlying values that the
constants represent are changed in later releases of VBA.

Using the MsgBox Function


The MsgBox function is a simple and useful way to display information, and
possibly retrieve information back from your users. It posts a dialog box with a
message, and the user has to click a button to dismiss it. The next few
paragraphs explain the MsgBox function and provide examples of how you use
intrinsic constants when calling functions.
VBA returns a number value indicating which button the user has clicked. The
simplest way to use the MsgBox function is to ignore the number that VBA
returns, as shown in the following example:

MsgBox "It's a nice day!", vbOkOnly, _


"Cheerful Greeting"

The vbOKOnly constant specifies that only the OK button will appear. In this
case the user has no choice—they have to click OK in order to continue
running the program. When the code runs, the message box appears as in
Figure 3:

2-14 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables: Using Constants

Figure 3. The MsgBox function called with the vbOkOnly button constant.

Suppose, however, that you do want to give the user a choice about how they
respond to the message box, and you want to know how they responded. You
can get the value that VBA returns. Compare the following example to the
previous one:

Dim intReturn As Integer


intReturn = MsgBox("It's a nice day!", vbYesNo, _
"Cheerful Greeting")

If the user agrees with your statement about it being a nice day and clicks Yes,
then intReturn will contain the value of another constant, vbYes. The constant
vbYes represents an integer, but you don’t need to know what the integer is—
you only need to know that the user clicked the Yes button. If the user
disagrees with your statement and clicks the No button, intReturn will contain
the value of the constant vbNo—another integer indicating that the user
clicked the No button.
You can use the value of intReturn to make a decision based on the user’s
choice. You may want to perform one action if the user clicks Yes, and another
action if the user clicks No. The following code demonstrates this decision-
making process using the If…End If construct, which will be explained in
more detail in the next chapter.

Dim intReturn As Integer


' Display a message box with Yes and No buttons.
intReturn = MsgBox("It's a nice day!", vbYesNo, _
"Overly Cheerful Greeting")
If intReturn = vbNo Then
' Display another message box with an icon.
MsgBox "Too bad!", vbOKOnly + vbExclamation
End If

The following list describes the first three arguments for the MsgBox function
in more detail (there are more arguments that you can find out about in Help):

Getting Started with VBA 2-15


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables

• Prompt: A string expression displayed as the message in the message


box. If you require more than one physical line, use the vbCrLf
constant concatenated with the lines of text. The prompt can be up to
about 1,000 characters long.
• Buttons: A composite numeric value, comprised of one or more
constants from Table 6 below. You may choose one of the constants
from each part of the table—Buttons, Icons, and Default Button—that
match your needs. Add the constants together to create the final value.
(If you don’t specify this parameter, VBA uses vbOkOnly.)
• Title: A string expression displayed in the title bar. If you don’t
specify a value, MsgBox will use the name of your project.

Topic Constant Description

Buttons VbOKOnly Display OK button only.


vbOKCancel Display OK and Cancel buttons.
vbAbortRetryIgnore Display Abort, Retry, and Ignore buttons.
vbYesNoCancel Display Yes, No, and Cancel buttons.
VbYesNo Display Yes and No buttons.
vbRetryCancel Display Retry and Cancel buttons.

Icons VbCritical Display Critical Message icon.


VbQuestion Display Warning Query icon.
vbExclamation Display Warning Message icon.
vbInformation Display Information Message icon.

Default vbDefaultButton1 First button is default.


Button
vbDefaultButton2 Second button is default.
vbDefaultButton3 Third button is default.
Table 6. Constant values available for the buttons parameter for MsgBox.

Depending on the value of the buttons argument, the MsgBox function returns
one of the values from Table 7, indicating which button the user pressed to
dismiss the message box.

2-16 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables: Using Constants

Constant Button Chosen

vbOK OK
vbCancel Cancel
vbAbort Abort
vbRetry Retry
vbIgnore Ignore
vbYes Yes
vbNo No
Table 7. Constants representing the possible return values from MsgBox.

Creating Your Own Constants


In addition to using intrinsic (built-in) constants, you can define your own
constants. Often, you’ll need to use the same value repeatedly throughout your
code, and that’s a perfect reason to use a constant.
The advantage to using a constant is that you can define it once, in one place,
and use it over and over again in your code. When you need to change the
value, you only have to change it in one place.
Constants, like variables, can be declared either within a procedure or at the
module level, in a module’s Declarations section. Module-level constants, like
module-level variables, can be public or private.
Here are some examples of constant declarations:

Const conPi = 3.14


Private Const conAddress = "632 Broadway Avenue"

If you know the data type for your constant, you can speed VBA’s processing
of expressions involving it by specifying the data type when you create it. You
can declare a constant as any of the following types: Byte, Boolean, Integer,
Long, Single, Double, Currency, Date, String, or Variant. If you don’t specify
a type, VBA will choose the data type that seems most appropriate for the
value you’ve provided.
For example, either of the following are valid declarations:

Const conCentimetersPerInch = 2.54


' or
Const conCentimetersPerInch As Single = 2.54

The second declaration is just a bit more clear.

Getting Started with VBA 2-17


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables

The official syntax for creating a constant is:

[Public|Private] Const constname [As type] = expression

The name of the constant (constname) must be a valid name (see the “Give
Your Variables Meaningful Names” section for naming rules). The expression
portion must be composed of numeric or string constants and operators.

2-18 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables: Using Constants

Summary
• Variables provide named storage for temporary data.
• Give your variables meaningful names so that you and other
programmers can refer to your code and more easily understand the
flow of your logic.
• When using variables in your code, you should explicitly declare what
data type you want each variable to hold.
• A Variant is a chameleon variable type that can hold any data type.
Use variants when you are working with data from tables, or when
writing code that must work with different data types. If you fail to
declare a variable’s type using the “As Type” clause, VBA assigns it
the Variant data type.
• You should specifically declare each variable and its type before you
use it in your code.
• You should use Option Explicit in the Declarations section of each
module to ensure that all variables have been correctly declared.
• Intrinsic constants are predefined values provided by VBA for use in
your code. They ensure your codes’ readability and its portability to
future versions of VBA.
• You can create your own constants for repeated use of a value within
your code.

Getting Started with VBA 2-19


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables

Questions
1. Can a string variable be null? Can it be equal to a zero-length string?
2. How do you indicate to VBA that you want it to require explicit
variable declarations?
3. Which data type should you use to store data copied from a text field
in a database table?
4. Declare a variable of type Integer and set it equal to the value 7.
5. Write a statement that uses the MsgBox function to display a dialog
box with the Yes and No buttons.
6. Create a constant that’s equal to the string “Microsoft.”

2-20 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Variables: Using Constants

Answers
1. Can a string variable be null? Can it be equal to a zero-length string?
No, Yes
2. How do you indicate to VBA that you want it to require explicit
variable declarations?
Add the Option Explicit statement to the module’s
Declarations area.
3. Which data type should you use to store data copied from a text field
in a database table?
Variant
4. Declare a variable of type Integer and set it equal to the value 7.
Dim x as Integer, x = 7
5. Write a statement that uses the MsgBox function to display a dialog
box with the Yes and No buttons.
MsgBox "SomeString", vbYesNo
6. Create a constant that’s equal to the string “Microsoft.”
Const x As String = “Microsoft”

Getting Started with VBA 2-21


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms

Creating User
Forms
Objectives
• Design a custom dialog box with a user form.
• Understand the difference between design mode and run mode.
• Add controls to a user form and set their properties.
• Understand events and event procedures.
• Explore the controls in the Control Toolbox.

Getting Started with VBA 3-1


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms

Working with User Forms


What Are User Forms?
User forms are the templates you can use to create your own custom dialog
boxes. You can incorporate your dialog boxes into the user interface of the
VBA host application. To users, your dialog boxes will be similar to the dialog
boxes they’re accustomed to working with.

NOTE User forms are somewhat confusingly named. They’re called user
forms in order to distinguish them from the forms that you work
with in Visual Basic, which are saved in a different format. You
will also see user forms referred to as Microsoft Forms. In this
course, they’ll be referred to either as forms or user forms.

User forms are containers for ActiveX controls. You use ActiveX controls to
design the elements of your interface that the user interacts with: buttons, lists,
drop-downs, and so on.
When you design a user form, you add ActiveX controls to it. Once you’ve
designed the “look and feel” of your form, you write code to make the form
and the controls it contains respond to the user’s actions.

NOTE In Office 2000, all the products except Access provide user forms.
Other VBA host applications may not provide user forms, or may
provide a different type of form. For example, Microsoft Access
provides its own forms. They can be made to function like user
forms, but they are inherently quite different.

Creating a New User Form


To create a new user form, follow these steps:
1. In the Project Explorer, select the project to which you want to add the
user form.
2. From the Insert menu, choose Userform.
A new user form appears as shown in Figure 1. Notice that another window,
the Control Toolbox, appears with the user form. The Control Toolbox
contains the built-in ActiveX controls that you can add to the form.

3-2 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms: Working with User Forms

Figure 1. A blank user form and the Control Toolbox.

Design Mode vs. Run Mode


When you create a user form in the Visual Basic Editor, you’re working in
design mode. In design mode you can add ActiveX controls to a form, add
code to the form’s module, and specify the characteristics that you want the
form and its controls to have. There’s no interaction between the user form and
the user interface of the host application in design mode.
In run mode, VBA displays the form in the user interface, so that the user can
interact with it while they’re performing their normal tasks. The user form
you’ve just created doesn’t do anything yet, but you can get an idea as to how
it’s going to work in the user interface:
1. Click the user form so that it is the active form in the Visual Basic Editor.
2. From the Run menu, choose Run Sub/User Form, or press F5.
The user form appears on top of the host application’s user interface. Figure 2
shows the new form at run time in Excel.

Getting Started with VBA 3-3


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms

Figure 2. A blank user form running in Microsoft Excel.

Notice that you can’t perform any other actions in the user interface while the
user form is showing. User forms are modal by default, which means that the
user must close the form before they can perform any other action in the
application. Many of the built-in dialog boxes in your VBA host application
probably function in the same way.

NOTE In VBA 6.0, it is possible to change a user form’s behavior to


make it modeless. VBA 5.0 user forms can only be modal.

To close the user form and return to the Visual Basic Editor, click the
Windows Close button in the upper-right hand corner of the user form.

TIP: If the Macros dialog box appeared when you pressed F5 to run the form, then
the form wasn’t the active window in the Visual Basic Editor, even if it
appeared to be. The Macros dialog box appears when VBA doesn’t know
what code you want to run. This can be frustrating, so your best bet is to
always click a blank area of the form once before you run it, to guarantee that
it’s the active window.

3-4 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms: Adding Controls to a User Form

Adding Controls to a User Form


The user form that you just saw was somewhat bland. You can make it more
interesting by adding a few ActiveX controls.

What Are ActiveX Controls?


ActiveX Controls are components that you create on a user form that have
some type of graphical representation. When the user form is in run mode, the
user interacts with controls on the form to enter data or perform an operation.
Different controls have different functions in run mode. A control’s function
may be a simple one, such as displaying text on the user form, or a more
complex one, such as drawing a complete calendar inside a box.

Key Term

ActiveX Control A graphical object you can create on the surface of a form that
exhibits a behavior when you run your application.

Introducing a Few ActiveX Controls


The CommandButton Control
The CommandButton control is a control that you’ll use frequently. You’re
already familiar with command buttons in Microsoft Windows software; every
OK button you’ve ever clicked is a command button.
To add a new CommandButton control to your user form:
1. Select the CommandButton control in the Control Toolbox.
2. Move the mouse over the user form.
3. Click the form, drag, and release the mouse button. The size of your
resulting command button depends on how far you drag the mouse.
Figure 3 shows a form with a command button.

Getting Started with VBA 3-5


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms

Figure 3. A user form with a command button.

There are a few other techniques that you can use to add a control to a form,
for example you can:
• Select the CommandButton control in the Control Toolbox, position
the mouse over the user form, and simply click the form.
• Double-click the CommandButton control in the Control Toolbox,
position the mouse over the user form, and click the form. Move to
another position on the form, and click again. Another command
button appears.
Double-clicking the CommandButton control in the Control Toolbox makes
the CommandButton control the default control, so that you can create
multiple command buttons at one time.

TIP: When you’re tired of creating command buttons, select the Select Objects
pointer in the Control Toolbox (looks like the tip of an arrow, pointing to the
upper left), so that the CommandButton control is no longer the default
control.

The TextBox Control


The TextBox control provides a place on the form where you can display text
to the user, or where the user can type text for your application to use. Text
boxes make it easy to collect information from the user.
Figure 4 shows a TextBox control selected on the form.

3-6 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms: Adding Controls to a User Form

Figure 4. A text box and a command button on a user form.

The Label Control


The Label control is similar to the TextBox control in that it displays text.
However, the user can’t type text into it. You can change the text in a label
when you’re designing a form, or your code can change it while the form is
running, but the user can never change it. Label controls are useful for giving
instructions to the user or for identifying the purpose of another control.
Figure 5 shows a label on a form.

Figure 5. The user form with a label, text box, and command button.

More controls will be introduced as you go along, but you can get started with
these.

Getting Started with VBA 3-7


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms

Manipulating Controls on a User Form


Once you’ve drawn a control on a user form, you can select it to move it or
resize it. You can also select multiple controls, and move or resize several at
once.

Selecting a Control
To work with a control on a form, you must first select it by clicking it. When
you select a control, its border is highlighted, as shown for the Label1 control
in Figure 5.

Moving a Control
To move a control, you simply select it and drag it to its new position on the
form (see Figure 6).

Figure 6. Click and drag to move a control.

Resizing a Control
To resize a control, first click the control once to select it. Small sizing handles
appear on the control’s perimeter. To resize the control, place the mouse over
one of the sizing handles, click, drag, and release (see Figure 7).

3-8 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms: Manipulating Controls on a User Form

Figure 7. To resize a form, drag one of the sizing handles.

Working with Multiple Controls


To manipulate multiple controls at once, select the controls you want to work
with. You can do this in one of two ways:
1. Click on the form background with the selection tool and drag the
bounding rectangle until it touches the controls.
2. Click on each control while holding down the CTRL key.
Once you’ve selected multiple controls, you can move or resize them as a
group (see Figure 8).

Figure 8. You can resize multiple controls at the same time.

Deleting Controls
To delete a control, select the control and press DELETE.

Getting Started with VBA 3-9


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms

Formatting Controls
The Visual Basic Editor provides a number of commands to help you lay out
your controls nicely, and save you time and effort in the process.
• To align multiple controls, select the controls and choose
Format|Align. You can choose to align controls by their left, right, or
center positions, by their tops, bottoms, or middles, or to the form’s
grid.
• To make two or more controls the same size, select them and choose
Format|Make Same Size. You can choose to make them the same
width, the same height, or both.
• To change the horizontal or vertical spacing of a set of controls, select
the controls and choose Format|Horizontal Spacing or
Format|Vertical Spacing. You can choose to increase, decrease, or
remove spacing, or to make it equal for all controls.

Try It Out!
Try drawing several command buttons of different shapes and sizes on a form.
Use the formatting commands to make them the same size, align them, and
make the spacing between them equal.

3-10 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms: Setting Properties

Setting Properties
You can customize user forms and ActiveX controls at design time by setting
properties. A property is a characteristic attribute, such as size, shape, or color,
which describes an object. By setting an object’s properties, you can control
how an object appears to the user and how the user interacts with it.

Key Term

Property A characteristic that describes an object. You can set a property


to give it a new value. You can also retrieve the current value of
a property.

To set properties at design time, you use the Properties window. You can also
set properties at run time, but you’ll learn about that later.

Working with the Properties Window


To view the Properties window if it’s not already visible, press F4, or choose
View|Properties window from the menu (see Figure 9).

Getting Started with VBA 3-11


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms

Figure 9. Properties window for a command button.


To change a property value, first click on the form or control that you want to
set a property for. Its properties will appear in the Properties window.
Alternatively, you can choose an object from the drop-down list at the top of
the Properties window. Either way, you can check the drop-down list to make
sure you’re setting properties for the correct object.
Next, click on the name or value of the property in the Properties window with
the mouse. Depending on the type of property, you can then do one of the
following:
• Enter a new value for the property using the keyboard.
• Select from a drop-down list of values.
• Double-click the property name or value to cycle through a list of
values.
• Click a build button ( ) to open a custom property dialog box.

3-12 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms: Setting Properties

TIP: If it makes it easier for you to find particular properties in the Properties
window, you can click the Categorized tab. On the Categorized tab,
properties are organized into groups according to their function, rather than
alphabetically.

A Few Common Properties


The Name Property
Just about every object that you work with has a Name property. The Name
property (which appears in the property sheet as “(Name)”) specifies the name
that you use to refer to an object from Visual Basic.
When you create an object, Visual Basic assigns it a default name. For
example, the first command button you create on a form is named
CommandButton1, the second is CommandButton2, and so on.
You can use the default name for an object, but it’s a good idea to change the
name to something that suggests the object’s purpose. For example, you might
change the name of a command button to “cmdOK” to indicate that this button
will be the OK button on the form.

NOTE The “cmd” prefix is a naming convention that specifies that the
control is a command button. You don’t have to use a naming
convention like this one, but it does help to keep track of what
type of control you’re working with. For more information on the
naming conventions used in this course, see Appendix A.

Why does the Name property have parentheses around it in the property sheet?
The primary reason is so that it will appear at the top of the Properties window,
since it’s likely that you’ll change it for most controls.

NOTE Some objects, such as an Excel worksheet, have two Name


properties. The (Name) property is the name you give to the object
to refer to it from code. The Name property, on the other hand, is
the name that you give to the object in the user interface. For a
worksheet, that would be the name on the worksheet’s tab. It’s a
confusing syntax, but fortunately you only have to worry about it
for a few objects.

The Caption Property


The Caption property specifies the static text that appears in some controls,
like a command button or a label. You as the developer can change this text,
but the user can’t change it.

Getting Started with VBA 3-13


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms

For some controls, you can enter the value for the Caption property in the
Properties window, or you can enter it directly into the control itself. Click the
control once to select it, pause, and then click it again to enable editing. You
can then select the existing text, delete it, and type in your own text. Figure 10
shows a button’s caption being changed on the form.

Figure 10. Changing a button’s caption on the form.

NOTE If you double-click the control, the user form’s module opens. If
this happens, close the module and try pausing between clicks on
the control.

Don’t confuse the Name and Caption properties, even though VBA initially
uses the same values for both properties. All controls have a Name property,
which is what you use to refer to the control. Some controls also have a
Caption property that affects the label displayed by the control.

Other Common Control Properties


Each control has a different set of properties based on its purpose. Many
controls do share a common set of properties, however. Table 1 lists some of
these:

3-14 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms: Setting Properties

Property Remarks

Text For controls that can store text data (text boxes, combo boxes, and
list boxes), the Text property determines the text that is stored.
Value For controls that can store nontext data (check boxes, option
buttons, and scroll bars), the Value property determines the data that
is stored.
Height Specifies the height of a control in points. A point is 1/72nd of an inch.
Width Specifies the width of a control in points.
Visible Determines if the control displays on the form at run time.
Font Sets the font characteristics of the control.
Enabled Specifies whether a control can receive the focus. If False, any text in
the control appears grayed out.
TabStop Indicates whether the control receives the focus when the user presses
the Tab key to move from one control to another on the form.
TabIndex Indicates the order in which controls will receive the focus when the
user tabs across the form.
Table 1. Different types of controls have many properties in common.

Getting Started with VBA 3-15


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms

Designing a Simple Dialog Box


Now that you’re familiar with creating user forms and adding controls, you’ll
begin designing a simple dialog box in Excel. As you design the form, use the
formatting commands to lay the form out nicely.
1. Create a new user form.
2. Add a command button, a label, and a text box to the user form. Don’t
worry about where the controls are placed; you’ll fix that in a minute.
3. Set the properties of the controls and the form as shown in Table 2.

Object Property Property Setting

UserForm1 Name FrmChangeCaption


Caption Change Caption
TextBox1 Name TxtInput
CommandButton1 Name CmdClose
Caption Close
Label1 Name LblInstructions
Caption Enter text for caption:
Table 2. Property settings for the example.

4. Size the form to about 250 points wide by 110 points tall. To make the
form this size, type these values into the Width and Height properties for
the form in the Properties window.

TIP: A point is equivalent to 1/72nd of an inch.

5. Align the controls so that your form looks something like Figure 10.

Figure 11. The Layout for the Change Caption dialog box.

You can click the Run Sub/UserForm button to display this form in run mode
in the user interface. Then you can type in the text box and click the Close
button. However, the form won’t react to your actions, because you haven’t yet

3-16 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms: Designing a Simple Dialog Box

attached code to the form’s and controls’ events. Events will be discussed in
the following section.

Getting Started with VBA 3-17


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms

Introducing Events
Now that you’ve created a form, how can you make it do something
interesting? The answer is to use events.
An event is something that happens in your application. For example, the user
may click a button, change some text, or close a user form. If you’ve written
code to respond to an action, then that code runs when the user performs that
action.
In VBA, you can write code that can react to each event as it occurs. You’ll
seldom, if ever, write code that handles every possible event, but it’s possible.
VBA provides many events to which you can respond. Your applications
spend most of their time reacting to events, whether a user, another program,
or the computer itself triggers them.
Think of VBA events as a series of messages that are sent, by VBA, to your
application. You can intercept any of these messages and use it as an
indication that it’s time for your application to do something.

Event Procedures
An event procedure is a hook VBA gives you in order to react to a specific
event. An event procedure can be as simple as a single line of code, or it can be
quite complex.
Lots of events can occur on a form. You can write code to react to some of
them and not to others. The way you handle a particular event is to write an
event procedure for it. Most of the time, you will write code to react to a small
subset of all the possible events a form and its controls expose to you.
For example, every command button has a Click event. If you’ve created an
event procedure for a command button’s Click event, then every time a user
clicks the button, the code in the Click event procedure will run.

Where Do You Put Event Procedures?


When you create an event procedure, you do so in the module attached to a
form. In fact, event procedures are the main reason that forms have modules.
When an event occurs on a form, VBA looks for an event procedure to go with
it. That is, given the name of the object and the name of the event, VBA looks
in the form’s module for:

Private Sub ObjectName_EventName()

Some important things for you to consider are:


• If you change the name of a control, you must also change the name of
any event procedures that apply to the control. It’s the procedure name

3-18 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms: Introducing Events

that links an event procedure with an object and an event. (You don’t
have to worry about this issue for event procedures that apply to the
form itself as opposed to its controls. VBA uses “Form” instead of the
form’s name, as in Form_EventName.)
• An easy way to enter an event procedure is to double-click on the
object when you’re designing the form. VBA will create an event
procedure stub for the default event of the object (every object has a
default event). For a command button, this will be the Click event, and
for a text box, the Change event.
• Event procedures can only exist in the module attached to the form.
From within the event procedure, you can call code that exists in any
module, but the event procedure itself must be in the form’s module.

Creating an Event Procedure


In an earlier chapter, you were introduced to the two drop-down lists at the top
of the module (see Figure 12). You can use these lists to assist you in creating
event procedures.

Object list
Procedure
list

Click event
procedure

Figure 12. The code module for a form, displaying the Click event procedure for
CommandButton1.

To create an event procedure for a user form or a control on a form, follow


these steps:
1. Open the user form’s module by right-clicking on the user form in the
Project Explorer and choosing View Code from the shortcut menu.
2. From the Object list, you should choose the object for which you wish to
create an event procedure. Visual Basic for Applications will insert the
procedure definition for the object’s default event.
3. If you want to create a procedure for an event other than the default event,
choose that event from the Procedure list.
Once VBA has created the event procedure stub, you can enter the code that
you want to run when the event occurs.

Getting Started with VBA 3-19


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms

The Click Event


The Click event is one of the events you’ll use most frequently. It occurs when
the user clicks the mouse. Most of the built-in controls in the Control Toolbox
have a Click event, as does the form itself.

Try It Out!
Look at Follow these steps to create a simple event procedure:
frmChangeCaption

1. Open frmChangeCaption.
2. Double-click the Close command button.
This is a shortcut for creating a control’s default event procedure. VBA
opens the form’s module and creates an event procedure stub for the
command button’s Click event. The event procedure stub is just the
skeleton of the event procedure that VBA creates for you, so that you can
fill in the code. The event procedure stub looks like this:

Private Sub cmdClose_Click()

End Sub

Notice that the event procedure stub looks similar to the other Sub
procedures you’ve seen. The only difference is that the name of the event
is included in the procedure’s name. The underscore character always
precedes the event name.
3. Add the following code to the event procedure stub:

Unload Me

The Unload statement unloads the form.


4. Choose Run|Run Sub/User Form from the menu to show the form in the
user interface.
5. Click the command button to try closing the form.
When you click the command button, VBA runs the event procedure and
displays the message box.

3-20 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms: Introducing Events

The Change Event


Another common event for controls is the Change event. The Change event
occurs every time you change the value of, for example, a text box. Each
character that you type into a text box triggers the Change event.

Try It Out!
The goal of the example is to change the caption to match the text that the user
Look at has typed into the text box. In order to do this, you need to add code to the text
frmChangeCaption box’s Change event. You’ll also add code to the cmdClose button’s Click
event so that when the user clicks the button, the form closes.
Follow these steps to add event procedures to the form:
1. Open the form in the Visual Basic Editor.
2. Open the form’s module.
3. In the module, click the Object drop-down and choose txtInput. VBA will
create the following procedure stub for the Change event:

Private Sub txtInput_Change()

End Sub

4. Add the following code to the event procedure:

Me.Caption = txtInput.Text

5. Press F5 to run, or choose Run|Run Sub/UserForm from the menu. Try


typing text into the text box.
That was pretty cool, but what exactly did you do inside those event
procedures? Let’s dissect them now and introduce a few new concepts.

Me
First of all, what’s Me? Me is just a shorthand way to refer to the form in
which this code is running, namely frmChangeCaption. The nice thing about
using Me is that if you change the name of the form, you don’t have to change
the code.
The example shows Me in two contexts. In the Change event procedure,
Me.Caption refers to the form’s Caption property. In the Close event
procedure, the Unload statement is used to unload the form. The Unload
statement takes a form as an argument in this case. You can use Me because
it’s shorthand for the current form.

Getting Started with VBA 3-21


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms

Properties in Code
Remember that you can set properties in code, as well as in the Properties
window. That’s what this line of code does:

Me.Caption = txtInput.Text

It sets the Caption property of the form to the Text property of the txtInput text
box. The Text property of the text box contains the text that’s currently in the
text box. So each time you type a character in the text box, the text box’s
Change event fires, and the Caption property of the form is updated.

3-22 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms: More Built-In Controls

More Built-In Controls


Now that you’re familiar with a few controls, and you’ve been introduced to
events and to setting properties from code, you’ll explore some of the other
controls in the Control Toolbox.
There are fifteen built-in controls that you can use for designing user forms.
Each control is summarized Table 3 alongside a picture of its toolbox icon,
including the ones already discussed:

Selection Not actually a control. This tool allows you to select an


Tool existing control (or controls) on a form so you can
change their properties.
Label Adds static text to a form. You normally use labels to
identify an edit control or to provide information or
feedback to the user.
Text Box Adds user-editable, data entry fields to a form. A text
box can be either single-line or multi-line and can have
a vertical scroll bar.
Combo Box Displays a compact, finite list of items as text. You can
also allow users to type directly into the control as if it
was a text box.
List Box Displays a finite list of items. Users can select items
from the list but cannot type in new items.
Check Box Stores a binary, yes/no value. You can also use a check
box to represent an unknown state by making it “gray.”
Option Can be used to select one from a group of options.
Button Only one option button within an option group can be
selected at any given time.
Toggle Indicates state. You can use the toggle button to allow
Button the user to choose Yes/No or On/Off conditions.

Frame Surrounds a group of option buttons to restrict them to


a single selection. You can also use an option group as
a container for other controls. The border acts as a
visual separator between control groups.
Command Initiates an action. Probably the control most often
Button used to run code.

TabStrip Displays the same set of controls on multiple pages.


You can use it to group small sets of data.
MultiPage Displays different sets of controls on multiple pages.
You can use it to present different groups of options.
Scroll Bar Displays a vertical or horizontal scroll bar. You can set
minimum and maximum integer values.

Getting Started with VBA 3-23


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms

SpinButton Increases or decreases values by a defined increment.


You can use it to scroll quickly through a set of values.
Image Displays images.

Table 3. VBA supports many different types of controls.

Basic Data Entry Controls


To test the sample, look at frmDataEntry in Ch03.xls, or import
Look at BasicDataEntry.frm into your application.
frmDataEntry
Figure 13 shows a form with some basic data entry controls. These include
labels, a text box, a command button, a frame and option buttons, and a check
box.

Figure 13. This form shows some basic data entry controls.

The Frame control can contain other controls, like the option buttons shown in
Figure 13. The frame is particularly useful for option buttons, because it allows
you to create multiple groups of option buttons on a form. Any option buttons
that are on the form, but not in a frame, behave as part of a single option
group. Since you can only select one option in a given option group, you’ll
probably want to group options into different groups.
Frames are also useful for grouping other controls. You can move the controls
in the frame around as a group. And you can treat them as a group from code
as well.
To place a control inside a frame, you can do any of the following:
• Draw it within the frame.
• Drag it into the frame. You can also drag it out of the frame.
• Cut and paste it into the frame.

3-24 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms: More Built-In Controls

Try It Out!
To get the hang of how frames work, try dragging some of the controls on
frmDataEntry into and out of the frame. Make the form larger if you need to.

List and Combo Boxes


Figure 14 shows the second form, which includes a list box and a combo box.
Check out
frmListCombo

Figure 14. This form shows off a list box and a combo box.

You can add items to a list box or combo box only at run time. In other words,
you must write code to do it. A good place to include this code is in the
Initialize event for the user form, which occurs when the form loads.
To add items to a list box or combo box, you can use the AddItem method.
The following example shows how to add items within the
UserForm_Initialize event.

Getting Started with VBA 3-25


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms

Private Sub UserForm_Initialize()

' Add items to list box.


Me.lstColors.AddItem "Red"
Me.lstColors.AddItem "Blue"
Me.lstColors.AddItem "Green"
Me.lstColors.AddItem "Yellow"

' Add items to combo box.


Me.cboCities.AddItem "Boston"
Me.cboCities.AddItem "New York"
Me.cboCities.AddItem "Washington, DC"
Me.cboCities.AddItem "Philadelphia"
End Sub

If you’re at all confused by this code, don’t be concerned—the new concepts


will be discussed in greater detail later on in the course.

SpinButton, ScrollBar, and Image


Controls
Play with Figure 15 shows a form that includes an Image control, a ScrollBar control,
frmIncrementCtls and a SpinButton control. You can display a graphic in the image control. The
spin button and the scroll bar are useful for incrementing and decrementing
values. In this example, clicking the spin button or the control bar changes the
height and width of the image.

3-26 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms: More Built-In Controls

Figure 15. You can use scroll bars and spin buttons to increment and decrement
values on a form.

As you click on the scroll bar, the image changes size by a specified
increment. The value of the increment depends on whether you click on the
scrolling area of the scroll bar or on one of the arrows at the ends. Either way,
clicking on the scroll bar changes the value of its Value property. The code in
the scroll bar’s Change event procedure sets the height and width of the Image
control to the current value of the scroll bar.
When you click on the spin button control, one of two events occurs: either the
SpinDown event or the SpinUp event. In the SpinDown event procedure, you
subtract a certain value from the height and width of the Image control, and in
the SpinUp event procedure, you add a value. The value that you add or
subtract depends on the value of the SmallChange property of the SpinButton
control. This property specifies by how much to change the spin button’s
Value property when a user clicks on the control.
This code is a little more complex than anything you’ve covered so far, so it’s
not included here. Feel free to take a look at it to figure it out for yourself.

The MultiPage Control


The MultiPage control (also sometimes called a tab control) allows you to
display different controls on multiple pages on a single form. You can use it to
group related information. Figure 16 shows a MultiPage control on a form.

Getting Started with VBA 3-27


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms

Figure 16. The MultiPage control is useful for organizing related information.

3-28 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms: More Built-In Controls

Summary
• A user form is a template that you can use to create custom dialog
boxes.
• When you’re designing a form in the Visual Basic Editor, you’re in
design mode. When you run the form in the user interface, you’re in
run mode.
• A control is a graphical component that exhibits some type of behavior
when you add it to your project.
• You use the Control Toolbox to select control types and then draw
them on a form using the mouse.
• You can move and resize a control using its sizing handles.
• You use the Properties window to set property values for a control.
• You can select multiple controls using the mouse or keyboard and then
change some common properties all at once.
• Events occur when the user, the system, or another application
performs an action.
• You can write event procedures in a form’s module to respond to
events on the form.

Getting Started with VBA 3-29


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms

Questions
1. What’s the difference between design mode and run mode?
2. How do you run a user form in the user interface from the VBE?
3. How can you create more than one control of a given type without having
to reselect the control’s toolbox icon?
4. Name two properties that you can set for a user form.
5. Where do you put code to respond to an action performed by the user?
6. Give an example of an event.
7. Which controls can you use when you want the user to select a value from
a list?

3-30 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating User Forms: More Built-In Controls

Answers
1. What’s the difference between design mode and run mode?
In design mode, you can add components to a project, design
user forms, and write code. In run mode the form appears within
the user interface, and your code runs in response to events.
2. How do you run a user form in the user interface from the VBE?
Click the form and choose the Run|Run Sub/UserForm menu
item, or press F5.
3. How can you create more than one control of a given type without having
to reselect the control’s toolbox icon?
Double-click the toolbox icon.
4. Name two properties that you can set for a user form.
Name, Caption, others
5. Where do you put code to respond to an action performed by the user?
In an event procedure
6. Give an example of an event.
Click event, Change event
7. Which controls can you use when you want the user to select a value from
a list?
ListBox, ComboBox

Getting Started with VBA 3-31


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures

Creating and
Running
Procedures
Objectives
• Become familiar with the features of the Visual Basic Editor that are
designed to help you write code.
• Call sub procedures and functions from the Immediate window.
• Employ the Object Browser and online Help to investigate VBA’s
built-in functions.

Getting Started with VBA 4-1


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures

Writing Procedures in the Visual


Basic Editor
This section focuses on the tools that the Visual Basic Editor (VBE) provides
See to help you write procedures. In order for you to have a module to work with,
IsLeapYearTemp() we’ve provided basLeapYear, along with the sample procedure,
in basLeapYear IsLeapYearTemp (you’ll use this to avoid having to type your own code).
You’ll work with this module throughout this chapter.

NOTE The sample function uses a technique not yet discussed: the
If...Then construct. If you’ll let these go for now, and just follow
the basic ideas, they’ll all make sense later.

Function IsLeapYearTemp(intYear As Integer) As Boolean


' If the year passed in intYear represents
' a leap year, return True.
Dim dtmDate As Date
Dim fIsLeapYear As Boolean

dtmDate = DateSerial(intYear, 2, 28)


If Day(dtmDate + 1) = 29 Then
fIsLeapYear = True
Else
fIsLeapYear = False
End If
IsLeapYearTemp = fIsLeapYear
End Function

This function won’t work if you pass it an invalid value for the intYear
parameter, so you’ll fix this later in the chapter (and end up with a function
named IsLeapYear). To start working with this procedure, first open the
module.

Creating a New Procedure


To create a new procedure, either start typing on a blank line in the module, or
select Insert|Procedure from the menu. You can also click the Insert
Procedure toolbar button.

4-2 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures: Writing Procedures in the Visual Basic Editor

If you choose the menu item or click the toolbar button, the Visual Basic
Editor will pop up the dialog box shown in Figure 1. Choose the type of
procedure (function or sub) and provide a name. For now, leave the other
options at their default values.

Figure 1. Use the Add Procedure dialog box to insert a new procedure.

VBA will insert a procedure stub into the module for you.

Public Function IsLeapYear()

End Function

(The Public keyword is optional here, and we’re going to leave it off, to save
space, for now.) If you want to type this yourself, you’ll find that by typing:

Function IsLeapYear

and pressing ENTER, VBA will create the rest of the stub for you.
Make sure you fill in the parameters and return value yourself, so that your
new procedure looks like this:

Function IsLeapYear(intYear As Integer) As Boolean

End Function

Getting Started with VBA 4-3


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures

As you type code into the module window, VBA checks the syntax of the
code. Every time you leave a line of code, VBA parses and checks the syntax
of the line. This is controlled by the Auto Syntax Check option in the
Tools|Options dialog box.

Moving Code Around


If you’re like most programmers, you do a lot of copying and pasting of code.
In VBA, as in other applications, you can select Edit|Copy or Edit|Paste from
the menu to do the work. (You can use the shortcut keys, CTRL+C and
CTRL+V, as well.)

TIP: You can also drag and drop code within the module editor. You can drag/drop
within a single module, or from one module to another.

To continue creating your new procedure, copy and paste all the code from
IsLeapYearTemp to the new IsLeapYear function. Make sure you change the
statement of code so that it assigns a return value to the name of the new
function. Your function should now look like this:

Function IsLeapYear(intYear As Integer) As Boolean


Dim dtmDate As Date
Dim fIsLeapYear As Boolean

dtmDate = DateSerial(intYear, 2, 28)


If Day(dtmDate + 1) = 29 Then
fIsLeapYear = True
Else
fIsLeapYear = False
End If
IsLeapYear = fIsLeapYear
End Function

Saving and Printing Code


Though you’re not finished with this function, it’s wise to save your file often.
Click the Save toolbar button (or select File|Save from the menu) to save the
file, together with the VBA project.
The Save button
You may want a printed record of your module. In that case, click the File
menu and then click Print. VBA will print the entire module.

4-4 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures: Writing Procedures in the Visual Basic Editor

Viewing Multiple Procedures


If you’d like to view more than one procedure at a time, you have two choices:
• Use the Procedure View and Full Module View buttons at the bottom
of the module. Full module view allows you to view all the procedures
in a module in a single stream. Procedure view shows one procedure in
the window at a time.
• Click the Window menu then click Split to split the module editor
window (see Figure 2). This option allows you to view multiple
locations in the same module. Once you’ve selected the item, drag the
divider bar with the mouse to size the two sections.

Figure 2. Using a split window allows you to view multiple, not necessarily
contiguous procedures.

Formatting Code
To help format your code, the Visual Basic Editor allows you to increase and
decrease the indentation of blocks of code. You may decide to indent an entire
block of a procedure, and rather than adding a tab to the beginning of each
line, you can move the entire block at once.
To indent a block of code, first select the region you want to work with, and
then press TAB or SHIFT+TAB to increase or decrease the indentation of your
The Increase code, respectively. Additionally, you can use the Increase Indent and
Indent/Decrease Decrease Indent buttons (see the icons to the left) on the Edit toolbar to work
Indent buttons with your code. You’ll also find these two options available on the Edit menu.

Getting Started with VBA 4-5


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures

Commenting Out Code


You can use the Comment Block button to comment out a section of code.
This is useful when you’re debugging, since the commented code isn’t
executed. You can try one strategy, comment it out, and then try another
The Comment Block strategy in its place. When you want to uncomment the code, you can use the
and Uncomment Uncomment Block button.
Block buttons To comment out a block of code, select the code and click the Comment
Block button on the Edit toolbar. Select the code and click the Uncomment
Block button to uncomment code. If the Edit toolbar isn’t visible, you can
display it by right-clicking on the Standard Toolbar and selecting Edit from
the shortcut menu.

Setting a Bookmark
You can use bookmarks to mark a position in your code and easily return to it.
When you’ve set a bookmark, a rectangle appears in the left-hand side of the
module, as Figure 3 shows.

Figure 3. Set a bookmark in your code to return to that position quickly.

You can work with bookmarks using the buttons on the Edit toolbar (or select
Edit|Bookmarks from the menu):
• To toggle a bookmark on or off, click the Toggle Bookmark button.
You can also toggle a bookmark by right-clicking the left-hand side of
the module and choosing Toggle|Bookmark from the shortcut menu.
• To move to the next bookmark, click the Next Bookmark button.
• To move to the previous bookmark, click the Previous Bookmark
button.
• To clear all bookmarks, click the Clear All Bookmarks button.

4-6 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures: Taking Advantage of IntelliSense

Taking Advantage of IntelliSense


Microsoft has included some truly timesaving features in VBA. These features,
which Microsoft calls IntelliSense, can reduce the amount of typing you have
to do as you’re writing code.

List Properties/Methods (CTRL+J)


As you’re typing code into the module editor, VBA will provide a list of
applicable properties and methods once you type a period or exclamation
point. Figure 4 shows this feature in action.

Figure 4. Use List Properties/Methods to view methods and properties of any


object.

Once you have selected an item in the list, you can commit it by pressing the
TAB key, by pressing the SPACE BAR, or by double-clicking the item with the
mouse. Pressing the ENTER key commits the item, but it also moves the
cursor to a new line, which can be annoying if you weren't finished typing the
statement. These methods also work for the List Constants feature, described
in the following section.
If you’ve disabled the Auto List Members option on the Editor tab of the
Tools|Options dialog box, you can force VBA to show the list by pressing
CTRL+J.

List Constants (CTRL+SHIFT+J)


When entering functions that accept enumerated values as parameters, VBA
can list available constants for you. Figure 5 shows what you might see when
calling the MsgBox procedure in your code. If the Auto List Members option
is not selected, you can display this list by pressing CTRL+SHIFT+J.

Getting Started with VBA 4-7


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures

Figure 5. VBA can list available constants for you (CTRL+SHIFT+J).

Parameter Info (CTRL+SHIFT+I)


If you’re working with unfamiliar functions, either built-in or user-defined,
you’ll find the Parameter Info feature useful. As you enter parameters for
procedures, VBA provides a list of the parameters and their types, as well as
the default value, if any. Figure 6 shows the Parameter Info tip for the MsgBox
statement.

Figure 6. Parameter Info makes it easier to enter complex procedure calls.


If you’ve cleared the Auto Quick Info check box in the Editor tab of the
Tools|Options dialog box, you can press CTRL+SHIFT+I to display the tip.

Word Completion
To complete its arsenal of IntelliSense features, VBA can complete words for
you as you type. As soon as VBA recognizes a unique match between what
you’ve typed and names it has parsed out of your code so far, you can press

4-8 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures: Taking Advantage of IntelliSense

CTRL+SPACEBAR to finish the keyword for you. If you haven’t typed enough
for a unique match, VBA will present a list of options when you press
CTRL+SPACEBAR.
This excellent time-saver works both with built-in and user-defined keywords
(variables and constants, as well).

Try It Out!
To try out some of the IntelliSense features:
1. Create a new Sub, named TestIt.
2. Inside the Sub, declare a string variable named “strCaption.”
3. Assign some text to the new variable.
Your function should look like this:

Sub TestIt()
Dim strCaption As String
End Sub

4. On a new line before the End Sub, type “MsgB” and press
CTRL+SPACEBAR. VBA will complete the rest of the keyword
“MsgBox” for you.
5. Press the SPACEBAR, and VBA will display the Parameter Info tip
describing the parameters.
6. Type “strCa” and press CTRL+SPACEBAR. VBA will fill in the rest
of the variable name. (If you type just “strC,” it’ll provide you with a
list of options, because “strC” isn’t a unique name.)
7. Type a COMMA, and VBA will provide both the Parameter Info tip
with the second parameter highlighted, and will also provide a drop-
down list of possible constants for the next parameter.
8. Continue playing with the MsgBox statement to get the feel for
IntelliSense.

Getting Started with VBA 4-9


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures

Using the Immediate Window


The Immediate Window
The Immediate window is an interactive debugging tool. You can open this
window at any time a database is open by pressing CTRL+G. You can also
click the View menu and then choose Immediate Window to display the
The Immediate window. In addition, you can click the Immediate Window toolbar button if
Window button you’re editing a module.

Writing Debug Information to the


Immediate Window from VBA
You may find it useful to write information directly to the Immediate window
from your applications. This way, you can track the status of what your code is
doing while it’s running.
The Immediate window is actually an object that VBA maintains, named
Debug. It has exactly one method, and no properties. Its one method is the
Print method, which prints information to the window’s contents. If you
include a statement like this in your VBA code, the current date and time will
appear in the Immediate window:

Debug.Print Now()

Calling Sub Procedures


To call a sub procedure from the Immediate window, you have two options.
You can type the name of the sub procedure, followed by its arguments,
without parentheses. Or, you can use the Call keyword, and group the
arguments within parentheses.

See TestLeapYear The sample file includes a sub procedure to test the IsLeapYear function we
in basLeapYear created earlier, TestLeapYear.

NOTE This sample function uses a technique not yet


discussed: For...Next loops. The For...Next construct loops
through the code as many times as you request, as the variable intI
takes the values from intLow to intHigh, sequentially.

4-10 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures: Using the Immediate Window

Sub TestLeapYear(intLow As Integer, intHigh As Integer)


Dim intI As Integer
For intI = intLow To intHigh
Debug.Print intI, IsLeapYear(intI)
Next intI
End Sub

To call the function from the Immediate window, type:

Call TestLeapYear(1998, 2004)


' or
TestLeapYear 1998, 2004

The output from the previous test is shown in Figure 7.

Figure 7. Use the Call keyword to call a subroutine.

Notice that when you call the TestLeapYear procedure from the Immediate
window, you don’t use the “?” character. Since you’re running a sub
procedure, you’re not asking VBA to print a value. You use the “?” character
only when you run a function, since a function returns a value that may be
printed to the Immediate window.

NOTE The Call keyword is unusual. Its only purpose is to allow you to
call a subroutine with the same syntax as a function. Because a
function returns a value, and a subroutine does not, the Call
keyword makes it clear that you’re not expecting a result.
(Conversely, the "?" character makes it clear that you are
expecting a result to be printed.) You can skip using the Call
keyword, but if you do, then you cannot use the parentheses

Getting Started with VBA 4-11


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures

around your parameters, and the syntax for calling subs looks
different than the syntax for calling functions. You may want to
use the Call keyword when calling subroutines, both to make it
clear that you’re calling a subroutine, and to make the calling
syntax the same as for calling functions.

When you're writing and testing code, keep in mind that you can run a
subroutine by placing the cursor with the procedure and clicking the Run
Sub/UserForm button. An even quicker way is to place the cursor within the
procedure and press F5, which is the shortcut key for the Run Sub/UserForm
command.

Calling Functions
To call a function from the Immediate window, use the “?” abbreviation for
the Print statement to cause VBA to print the output of the function. For
example, Figure 8 shows how you might call the IsLeapYear() function we
created earlier.

Figure 8. Use “?” to print the results of calling a function.

TIP: The Immediate window can only hold 200 lines of output. As it fills with
more output lines, information scrolls out the top of the window. If the
Immediate window fills with information and you’d like to clear it out, press
CTRL+SHIFT+HOME to select all the text back up to the top of the
window, and then press DELETE. (If you’re at the top and want to clear
from where you are to the bottom, press CTRL+SHIFT+END to select the
text.)

4-12 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures: Investigating Built-In Functions

Investigating Built-In Functions


VBA’s Built-In Functions
The VBA language has many built-in functions you can use to do all sorts of
things. The more familiar you are with VBA’s built-in functions, the better
programmer you will become.
This section highlights some of the most popular functions, grouped by
category. This is only a small subset of the available VBA functions; there are
many other functions to choose from.
For more details on the syntax of these functions, see online Help, the Object
Browser, or use the IntelliSense features of VBA.

Strings
The functions in Table 1 are useful for manipulating strings:

Function Description Example

InStr Finds the starting position of a InStr("My mother", "mo") = 4


substring within a string.
Left Returns the leftmost characters Left("hello",4) = "hell"
from a string.
Len Returns the length of a string. Len("hello") = 5
Mid Returns a portion of a string. Mid("microsoft", 3, 4) = "cros"
Trim Trims leading and trailing blanks Trim(" hello ") = "hello"
from a string.
Space Fills a string with a number of Space(10) = " "
space characters; useful for API
calls.
Table 1. Popular string functions.

Dates and Times


The functions in Table 2 come in handy when dealing with dates and times:

Getting Started with VBA 4-13


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures

Function Description Example

Date Returns the current date. Date() = 7/15/97


DateAdd Adds or subtracts an DateAdd("m", 2, #7/15/97#) = 9/15/97
interval to a date. DateAdd("q", -3, #7/15/97#) = 10/15/96
DateDiff Returns the difference DateDiff("d", #7/4/1776#, #7/15/97#) =
between two dates/times. 80729
DateDiff("yyyy", #7/4/1776#, #7/15/97#) =
221
DatePart Returns a part of a date. DatePart("d", #7/15/97#) = 15
Now Returns the current date Now() = 7/15/97 2:48:28 PM
and time.
Time Returns the current time. Time() = 2:48:28 PM
Table 2. Popular Date and Time functions.

Conversion
Thee functions in Table 3 come in handy whenever you need to convert one
type of data into another:

Function Description Example

Asc Converts a character into Asc("t") = 116


a character code.
Cxxx Converts one data type to CLng(23.45) = 23
another. CCur(45234.98076) = 45234.9808
Chr Converts a character code Chr(116) = "t"
into a character.
Format Formats an expression Format(#7/15/97#, "mmm") = "Jul"
into a string using a built- Format(#7/15/97#, "Medium Date")
in or custom template. = 15-Jul-97
Format(0.097, "0.00") = 0.10
Format(3445.569, "Currency")
= $3,445.57
Format("hello", ">") = "HELLO"
Int Truncates an expression Int(35690.78) = 35690
into a whole number.
Table 3. Popular conversion functions.

Other
The functions in Table 4 don’t fit neatly into any of the other categories:

4-14 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures: Investigating Built-In Functions

Function Description Example

DoEvents Yields to the operating system so it can DoEvents


process other operations.
InputBox Creates a rather crude-looking dialog box varAge =
containing a single text box for input; InputBox("Enter your
returns the value the user enters into the text age:", "An Age Old
box. Question")
MsgBox Creates a dialog box with a message; intResponse =
returns a code corresponding to the clicked MsgBox("OK to reformat
button. your hard drive?",
vbOkCancel, "Bad
Question")
Rnd Returns a random number between 0 and 1. intX = CInt(Rnd * 1000)
Table 4. Other popular functions.

Other Functionality in VBA


Your best bet in attempting to find out what else is included in VBA is to use
the Object Browser together with online Help. The Object Browser provides
information on most of the language elements that are available to you in
VBA. The Object Browser will be discussed in greater detail in a later chapter.
Figure 9 shows the Object Browser, searching through the VBA complement
of Date/Time functions. You can press F1 from the Object Browser to get help
on the selected item.

Getting Started with VBA 4-15


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures

Figure 9. Use the Object Browser (F2) to view built-in VBA procedures.

To use the Object Browser to peruse built-in functions:


1. Press F2, or click the Object Browser button on the Standard toolbar in
the Visual Basic Editor.
2. Click the drop-down list in the upper left corner of the Object Browser.
This is the Projects/Libraries list, and it lists all the different sets of objects
and language elements that are available to you.
3. From the list of available libraries, choose VBA.
4. Scroll through the list of groups in the lower left pane. The associated
items will appear in the window on the right.
5. Once you’ve selected a function, press F1 (or right-click and select Help)
to view the Help topic for the selected item.
VBA breaks its built-in procedures down into eight basic areas:
• Conversion
• Date/Time

4-16 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures: Investigating Built-In Functions

• File System
• Financial
• Information
• Interaction
• Math
• Strings

Try It Out!
Suppose you want to calculate the time 13 minutes from the current time. To
do this, you have to find some way to determine the current time, and then,
some way to add a specified number of minutes.
The first place to look is, of course, the Object Browser (or you could look in
the previous section). Use the Object Browser to find the functions that deal
with dates and times. The functions you’ll need to use to solve this problem are
the Time and DateAdd functions.
The Time function returns the current time. To try it out, type:

? Time

in the Immediate window. It should return the current time.


To add 13 minutes to the current time, you’ll need to use the DateAdd
function. (There’s no TimeAdd function; DateAdd handles both dates and
times.) The information in Figure 10, from the VBA Help file, describes the
function.

Getting Started with VBA 4-17


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures

Figure 10. The online Help for the DateAdd function.

To use DateAdd, you must specify:


• The interval ("n").
• The number of intervals (13).
• The start value (the return value from the Time function).
Therefore, to display the time 13 minutes from the current time, in the
Immediate window, type:

? DateAdd("n", 13, Time)

4-18 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures: Optional and Named Arguments

Optional and Named Arguments


Many built-in VBA procedures can accept more than one argument. Often, not
all of the arguments are required in order for the procedure to do its job. In
many cases, some or all of the arguments are optional, meaning that you skip
them when you call the procedure. In each case, if you skip the argument, the
procedure will assume a default value.
For example, the MsgBox function accepts up to five arguments, but all except
the first are optional. The syntax description in the Help file indicates this by
placing square brackets around optional parameters:

MsgBox prompt[, buttons] [, title] _


[, helpfile, context]

In calling MsgBox, you must specify a prompt, but besides that, all the rest of
the arguments are optional. If you skip a parameter, however, you must include
enough commas so that VBA can determine which parameter you are
specifying. For example, try out these variations:

MsgBox "Hello"
MsgBox "Hello",,"This is a Title"
MsgBox "Hello", vbExclamation

TIP: It’s possible, and quite useful, to create your own procedures with optional
arguments. We’ll cover this technique in detail later in the course.

Introducing Named Arguments


To make it even easier to call procedures with optional arguments, VBA
allows you to specify the parameters for a procedure in any order you like,
without counting commas. To do so, all you need to do is specify the name of
the parameter along with its value.
For example, to specify the prompt and title arguments for MsgBox, you could
use a call like this:

MsgBox "Hello", Title:="This is a title"

Or like this:

Getting Started with VBA 4-19


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures

MsgBox Prompt:="Hello", Title:="This is a title"

The rules?
• Separate the parameter name from its value with “:=”.
• Use online Help, or the ToolTips for each procedure, to determine the
appropriate argument names.
• Once you use a named parameter in a procedure call, the rest of the
parameters must be named.
• You can use named parameters with either built-in, or user-defined
procedures.
As you can see, this technique can be extremely useful for calling procedures
that have a large number of arguments, mostly optional. (It also makes your
code easier to follow.)

4-20 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures: Optional and Named Arguments

Summary
• Automatic syntax checking parses each line of code after you type it
and alerts you to any syntax errors.
• You can move code in a module by cutting and pasting or by dragging
and dropping.
• You can view multiple procedures in a module, or one procedure at a
time.
• Bookmarks enable you to mark a position in your code and return to it
easily.
• IntelliSense helps you write code by providing syntax information,
available properties and methods, available built-in constants, and
automatic word completion.
• You can use the Immediate window to display the output of any
expression involving built-in or user-defined functions or subroutines.
• Use the Print method of the Debug object (Debug.Print) to send
information to the Immediate window from your application code.

Getting Started with VBA 4-21


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures

Questions
1. Write out a function named MyName() that returns your name as its return
value.
2. On what side of an equals sign do you usually find an expression?
3. What’s the difference between a function procedure and a sub procedure?
4. Why would you set a bookmark?
5. Give an example of a built-in VBA function for working with strings.

4-22 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating and Running Procedures: Optional and Named Arguments

Answers
1. Write out a function named MyName() that returns your name as its
return value.
Function MyName() As String
MyName = “Mary Jo"
End Function
2. On what side of an equals sign do you usually find an expression?
On the right side
3. What’s the difference between a function procedure and a sub
procedure?
A function returns a value, a sub does not
4. Why would you set a bookmark?
To quickly return to a particular position in your code
5. Give an example of a built-in VBA function for working with strings.
InStr, Left, Mid, Right, Trim, Space, Len

Getting Started with VBA 4-23


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Mastering VBA Control Structures

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

Getting Started with VBA 5-1


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
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 boils down to normal 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.
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.

5-2 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Mastering VBA Control Structures: Branching Structures

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 makes up the chunk of
code.
For example, the procedure ValidateData in basIfThen uses the If…Then
Try out statement to validate user input:
ValidateData in
basIfThen
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

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:

Getting Started with VBA 5-3


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Mastering VBA Control Structures

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:

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

5-4 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Mastering VBA Control Structures: Branching Structures

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:

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 when 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 Example
The following function takes an argument of type Date. It evaluates the year
portion of the date within a Select Case statement.

Getting Started with VBA 5-5


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Mastering VBA Control 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

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

5-6 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Mastering VBA Control Structures: Branching 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 = 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
Case Else
CalcQuartile = 0
End Select
Case Else
CalcQuartile = 0
End Select
End Function

Getting Started with VBA 5-7


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Mastering VBA Control 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 Function 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 Function

There are other ways (perhaps better ones) to solve this problem, but GoTo is
commonly used in this situation anyway.

5-8 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Mastering VBA Control Structures: 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 is met, or a set number of times.

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

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
Sub Overflow()
Dim byt As Byte

Getting Started with VBA 5-9


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Mastering VBA Control Structures

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 and 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.
For example, the following procedure will loop until it hits a specific value,
See ExitLoop1 in and will then jump out of the loop:
basLoop

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.

5-10 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Mastering VBA Control Structures: Looping Structures

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. Looping with conditions.

Let’s look at the different ways that you can use a condition to exit a Do loop.
See ExitLoop2 -
ExitLoop5 in
basLoop First, you can use the Until statement at the beginning of a loop to loop until a
particular condition is True. In this case, you only enter the loop if the value of
the byt variable is not equal to 255, and loop until it equals 255.

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.

Sub ExitLoop3()
Dim byt As Byte

Getting Started with VBA 5-11


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Mastering VBA Control Structures

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:

Sub ExitLoop4()
Dim byt As Byte

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

' or

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.
Otherwise, place the condition at the top, next to the Do statement.
• Choose Until or While depending on the truth status of your condition:

5-12 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Mastering VBA Control Structures: Looping Structures

∗ If you want to loop while your condition is True, use While.


∗ If you want to loop while your condition is False, use Until.

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 a 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.

Getting Started with VBA 5-13


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Mastering VBA Control Structures

Using For...Next
Here’s a simple procedure that demonstrates how the For…Next loop works.
See SimpleLoop in
basLoop
Function SimpleLoop(lngNum As Long)
Dim lngI As Long

For lngI = 0 To lngNum


Debug.Print lngI * 100
Next lngI
End Function

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).
The code uses For...Next to loop backwards, starting at the value you pass to
Try Factorial() in the function, accumulating the products. The loop ends after the counter gets to
basLoop 2, because there’s no need to multiply by 1.

5-14 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Mastering VBA Control Structures: Looping 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 the concept of collections is covered
in more detail in a later chapter, you’ll learn about For Each...Next.

Getting Started with VBA 5-15


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Mastering VBA Control 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.
• You can use Exit Do to exit a Do loop.
• 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.
• Use For...Next to execute a series of statements a fixed number of
times.

5-16 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Mastering VBA Control Structures: 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.

Getting Started with VBA 5-17


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
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-18 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events

Understanding
Events
Objectives
• Observe the order in which events occur for forms and controls.
• Write simple event procedures.

Getting Started with VBA 6-1


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events

Events and Event Procedures


In the last chapter, you learned what an event is, and how to write an event
procedure that runs when a user performs an action on a control. In this chapter
you’ll delve more deeply into events and event procedures so that you can
begin to take advantage of their full power.

Run frmLogEvents In order to make it easier for you to study different events that occur on forms,
in Ch06.doc we’ve created a simple event logging mechanism in Word. To try this
example, run frmLogEvents in Ch06.doc and perform different actions to see
what kind of events they generate.
When you trigger an event on frmLogEvents, it is written to the Word
document. You can choose to look at certain events only by checking the
boxes in the Filter Events section. Figure 1 shows frmLogEvents in action.

Figure 1. Use frmLogEvents to watch form events as they occur.

Try It Out!
To test out the event logging facility, follow these steps:
1. Open Ch06.doc.
2. In the Visual Basic Editor, open frmLogEvents and press F5 to run it.
3. Click the Click Me button, type text into the text box, and select different
items in the list box. Play with the form and its controls, and watch the
output text in the Word document.

What Did You Just Do?


When you work with frmLogEvents, VBA prints one line of text to the Word
document for each event that occurs. For example, when you first load the
dialog box, the following event procedures run, in this order:

6-2 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events: Events and Event Procedures

• UserForm_Initialize: The user form is about to be loaded. Do any


controls on the form need to have an initial value or an initial state
before the user sees the form? Do any variables need to be initialized?
You can do these things in the Initialize event.
• Text1_Enter: Text1 has a TabIndex setting of zero, so it receives the
focus as soon as the form loads. This triggers the Enter event for the
text box.
• UserForm_Layout: The Layout event occurs when the form first
appears on the screen, and anytime it is resized from code.
• UserForm_Activate: The form has become the active window on the
screen. This event occurs when the form loads only if the form is
visible.
Your application could react to one, or more, of these events.

TIP: As a VBA programmer, your job is to learn which events occur when, and
which event is the most appropriate “hook” for your program code.

How Does frmLogEvents Work?


If you open the frmLogEvents code module, you’ll see a bunch of procedures,
each of which looks something like this:

Private Sub ListBox1_Change()


LogEvent Me, "ListBox1_Change", conEventData
End Sub

This event procedure calls a procedure called LogEvent. LogEvent takes


between three and eight parameters: Me, the shorthand for the form; a string
that contains the name of the event procedure; a numeric constant; and the
values of any arguments that are passed to the event procedure (more on that
shortly). An event procedure like this one exists for each of the most common
events on the form.
When an event occurs, its event procedure runs. It calls the LogEvent function
in basLogEvents, passing in the form on which the event occurred and the
event’s name and the type, designated by a constant. Another function checks
the value of the constant against the options that you’ve checked in the form,
so that only the types of events you’ve chosen to view will be displayed.
Table 1 breaks down the parts of this representative code fragment and
explains each. You’ll notice how much this resembles a standard subroutine
(except for the naming convention of the procedure title).

Getting Started with VBA 6-3


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events

Item Description

Private Sub Declares a new event procedure that is


private to this module.
ListBox1_ Indicates the object whose event you’re
reacting to. For any form, this will be
UserForm_. For controls, this will be the
name of the control.
Change Name of the event to which your code is
reacting.
LogEvent "ListBox1_Change", Code to call, in reaction to the event. This
conEventData could, of course, be multiple lines of code
or even no code (although that wouldn’t be
very interesting).
End Sub Marks the end of the event procedure.
Table 1. Items in the frmLogEvents form.

Hooking Up Your Own Events


If you want to add more controls to the existing test form, or hook up your own
form in this test environment, you can do it, but it requires considerable effort.
You must provide an event procedure for all the events of any control you’d
like to work with, and each event procedure must call LogEvent to log the
event. For the first parameter to LogEvent, pass in Me, representing the current
form. For the second parameter, pass in any string you want logged, and for
the third, choose one of the six event-type constants defined at the module
level in basLogEvents.
Many of the event procedures pass additional information to your code, and in
those cases, the sample form passes the information on to the logging form, for
display over there. For example, the MouseDown event tells you which button
was clicked, what the current shift state was, and where the click occurred. The
sample form uses code like this, passing in each of the arguments supplied by
the event procedure:

Private Sub TextBox1_MouseDown(ByVal Button _


As Integer, ByVal Shift As Integer, _
ByVal X As Single, ByVal Y As Single)
' Log the MouseDown event.
LogEvent Me, "TextBox1_MouseDown", _
conEventMouseClick, Button, Shift, X, Y
End Sub

There’s no “magic switch” you can set to force forms to log events: this
requires sweat and brute force, and you won’t want to take this task on

6-4 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events: Events and Event Procedures

casually. Start with our sample form, and add only the controls you need to test
the order in which events occur.

Where To from Here?


The rest of this chapter focuses on the order in which events occur, depending
on the actions you take. There are so many events that it’s often difficult to
know which one you need to react to. In the sections that follow, the sequence
of events that occur in different scenarios will be discussed. Although this isn’t
meant to be comprehensive, the most common situations are covered. You’ll
be using frmLogEvents along the way.
The most important thing you can learn from this section, though, is that you
should experiment with frmLogEvents. Try out different sequences of actions
to see what kinds of events they trigger.

Getting Started with VBA 6-5


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events

Which Objects Have Events?


Events occur in response to an action taken by the user, by running code, by
the operating system, or, in some cases, by another application. An event is
always associated with a particular object. This makes sense, since when a user
is interacting with an application, they’re interacting with objects such as
documents, spreadsheets, presentations, drawings, and dialog boxes.
There are three kinds of objects in a Visual Basic project that have events:
• User forms
• Controls
• Application-specific objects that appear in the Project Explorer
You may remember from a previous chapter that a project can include
application-specific objects. In Microsoft Excel, they’re called “Microsoft
Excel Objects;” in AutoCAD they’re called “AutoCAD objects;” in Visio
they’re called “Visio Objects;” and so on. In the next section, you’ll learn
about a few of the events belonging to each type of object.

6-6 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events: User Form Events

User Form Events


What kinds of events are available to you on a user form? You saw some of
them in the frmLogEvents example. To see a complete list of the events
available to a user form, check out the Object Browser. Press F2, or select
View|Object Browser from the menu, then choose MSForms from the
Project/Library box and select UserForm from the Classes list. The UserForm
object’s events show up with a bolt of lightning next to them in the Members
of list. A few common form events will be discussed here, but you can use the
Object Browser and online Help to learn about the others.

The UserForm Initialize Event


The Initialize event runs when a user form opens. You can use the Initialize
event to set initial values for the user form, before the user begins interacting
with it. For example, you can change the position of the user form or initialize
some of the other properties of the form.
Although you can set most of a user form’s properties in the Properties
window at design time, there may be cases in which you need to set them
when the user form opens. For example, your user form may need to utilize
data that the user enters. You can’t possibly guess what this data will be while
you’re designing the user form, but you can write your code in such a way that
the user form gets the data it needs when the Initialize event occurs.
You can also use the Initialize event to initialize module-level variables, so
that their values are available to the other event procedures on the form.

Try It Out!
To view this example, run frmInitialize in Ch06.doc, or import Initialize.frm
frmInitialize in into your application.
Ch06.doc
To work with the user form Initialize event, follow these steps:
1. In the Visual Basic Editor, display the Project
Explorer, if it isn’t already visible.
2. Create a new user form.
3. Change the user form’s name to frmInitialize in the Properties window.
4. In the Properties window, make sure user form’s StartupPosition property
is set to “0 – Manual.”
5. View the code module for frmInitialize.
6. In the Code window, choose UserForm from the left-hand drop-down list
(Object list).
7. Choose Initialize from the right-hand list (Procedure list).
8. Enter code into the procedure, as follows:

Getting Started with VBA 6-7


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events

Private Sub UserForm_Initialize()


Me.Move 0, 0
End Sub

9. Click the user form in the Visual Basic Editor to make it the active
window.
10. From the Run menu, choose Run Sub/UserForm. The user form shows
up in the upper left-hand corner of the host application’s user interface.
If the Run menu command shows Run Macro rather than Run
Sub/UserForm, try clicking the user form again.
11. Try changing the Move method’s arguments to other values, to see how it
affects the user form.

TIP: You can use an object’s Move method to position it within its owner. For a
form, the screen is the owner; for a control, it’s either a form or a frame that’s
the owner. To use the Move method, specify Left, Top, Width, and Height
values, measured in points. All coordinates except the Left coordinate are
optional.

The UserForm QueryClose Event


The QueryClose event occurs when the user form is closed. You can use the
QueryClose event to perform any operations that need to happen before the
form is unloaded, like saving out data that the user has entered into the form.
When you use the Unload statement to unload a user form, as shown in a
previous example, the QueryClose event occurs.
To view an example of the QueryClose event in action, open Ch06.doc in
Load and try Word, and run frmQueryClose. Type some text into the text box and click the
frmQueryClose in Close button. Although you can create a similar example in another
Ch06.doc application, you’d have to change the code slightly.
The two event procedures in frmQueryClose are the Click event for the
cmdClose button, and the QueryClose event for the user form. The Click event
procedure is familiar; it just uses the Unload statement to unload the form:

Private Sub cmdClose_Click()


' Unload the current form.
Unload Me
End Sub

6-8 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events: User Form Events

The QueryClose event procedure is a little less familiar:

Private Sub UserForm_QueryClose(Cancel As Integer, _


CloseMode As Integer)
' Check the length of the user's input
' in the text box.
If Len(txtInput.Value) <> 0 Then
' Add a new Word document.
Documents.Add
' Write the text in the text box
' to the Word document.
Selection.TypeText txtInput.Value
End If
End Sub

What’s this code doing? First, it checks to see whether you’ve entered any text
in the text box by checking the length of the text in the Text property. If there
is text in the text box, then it adds a new Word document, using
Documents.Add. Next it inserts the text that’s in the text box. In this
example, Selection just refers to the insertion point in the Word document,
and TypeText inserts the text that’s in the text box into the document.
If you’re a little confused by this code, don’t worry about it. The unfamiliar
concepts will be covered later in the course. For now, just keep this example in
mind as one way that you can use the QueryClose event.

Event Procedure Arguments


Notice that the QueryClose event procedure takes two arguments. These
arguments give you additional control over the event procedure. You can use
them within the code that you write in the body of the event procedure. Think
of these arguments as being passed by VBA to the event procedure.
For example, the Cancel argument allows you to cancel the QueryClose event.
You might cancel the event if there is some condition under which you don’t
want the user to close the form. To cancel the event, set the Cancel argument
to True within the body of the event procedure.
The following example builds on the previous one to prevent the user from
closing the form if they haven’t yet entered any text in the text box:

Private Sub UserForm_QueryClose(Cancel As Integer, _


CloseMode As Integer)
' Check the length of the user's input

Getting Started with VBA 6-9


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events

' in the text box.


If Len(txtInput.Value) <> 0 Then
' Add a new Word document.
Documents.Add
' Write the text in the text box
' to the Word document.
Selection.TypeText txtInput.Value
Else
Cancel = True
End If
End Sub

6-10 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events: Control Events

Control Events
Controls have many events. Just about every time a user does anything with a
control on a form, they’ll trigger an event. It’s up to you to decide which
events should run code in response to the user’s actions.
Just like form events, control events show up in the Object Browser. Choose
the Microsoft Forms library and select the control you’re interested in. The
control’s events will show up in the Members of list.
You’ve already learned about two common control events, the Click and
Change events. This chapter will cover the keyboard and mouse events.

Keyboard Events
When you enter a character into a text box (or any other control that accepts
text), a series of events occur. To duplicate this series of events, follow these
steps:
1. Run frmLogEvents. Make sure only the Keystroke and Data check boxes
are selected.
2. Type some text into the text box on the form.
For each character that you type, four events are triggered: KeyDown,
KeyPress, Change, and KeyUp.

Studying Key Events


Typing in the text box triggers these events, in the following order:
• KeyDown for the control:
∗ Occurs when you depress any key on the keyboard. VBA
passes a code representing the key you pressed (KeyCode),
along with a value indicating the current state of the SHIFT,
CTRL, and ALT keys (Shift).

∗ Allows you to cancel the handling of the key by setting the


KeyCode value to 0. Once you do that, it’s as if the key was
never pressed.
∗ Occurs for every key you press.
• KeyPress for the control:
∗ Occurs when you press and release a key that enters a
character into a text box, including the space and backspace
keys. VBA passes a code that represents the character you
typed (KeyASCII).
∗ Allows you to cancel the handling of the character by setting
the KeyASCII value to 0. Once you do that, it’s as if the key
was never pressed.

Getting Started with VBA 6-11


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events

∗ Only occurs for ANSI keys—keys that have visible, insertable


values.
• Change for the control:
∗ Occurs when the text in the text box changes because of
characters you’ve typed.
∗ Allows you to react to the change in the value of the control
without having to worry about the exact characters typed to
get you there.
∗ Retrieves the text of the text box in the Change event, using
the Value property of the text box.
• KeyUp for the control:
∗ Occurs when you let go of the key you pressed to trigger the
KeyDown event.
∗ Occurs for every key pressed.

KeyPress vs KeyDown/KeyUp
VBA provides two events you can use if you want to trap keystrokes in your
application. Many developers are confused by the inclusion of what appear to
be similar events:
• KeyPress event occurs whenever you press and release an ANSI key (a
typeable character like A-Z, 0-9, BACKSPACE, TAB, etc.). Use this
event if you need to know which character the user pressed (“a” is
different from “A” to the keypress event).
• KeyDown event occurs whenever you depress any key. Use this event
if you need to know which key the user pressed (“a” is the same key as
“A”).
In both cases, VBA sends the value of the key (or letter) pressed to the event
procedure. The KeyPress event gets a numeric value representing the ANSI
value of the letter you pressed (the KeyASCII parameter). The KeyDown
event gets a numeric value representing the key code for the key you pressed,
as well as the state of the shift keys at the time you pressed the key.
When VBA creates a new event procedure to react to the KeyDown event, the
procedure looks like this:

Private Sub TextBox1_KeyDown(KeyCode As Integer, _


Shift As Integer)
' Note that VBA passed the KeyCode and shift
' state to the procedure.
End Sub

For the KeyPress event, the procedure looks like this:

6-12 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events: Control Events

Private Sub TextBox1_KeyPress(KeyAscii As Integer)


' In this case, VBA just passes the KeyAscii
' value, indicating which letter was pressed.
End Sub

In either case, you can modify the value VBA sends to the event procedure by
modifying the KeyCode or KeyASCII parameter sent to the procedure.
To experiment further with KeyDown and KeyPress, take a look at
Check out frmKeyEvents in Ch06.doc. Run the form, and type some text into the text box
frmKeyEvents in as shown in Figure 2.
Ch06.doc

Figure 2. Type text into the text box to see the differences between KeyDown and
KeyPress.

The number of the key pressed is returned by the KeyDown event. Also, if
you’ve pressed the SHIFT, CTRL, or ALT key, or a combination, the
appropriate boxes are checked.
The KeyPress event, on the other hand, returns the ASCII value of the
character typed.

Mouse Events
When you click the mouse on a form or control, a number of events occur. To
observe mouse events in frmLogEvents, follow these steps:
1. Run frmLogEvents. Make sure only the Mouse Click check box is
selected.

Getting Started with VBA 6-13


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events

2. Double-click on the Click Me command button.


When you double-click on the command button, VBA triggers the following
events in this order:
• MouseDown:
∗ Happens when you click the mouse button.
∗ VBA passes an integer to your event procedure indicating
which button was pressed (Button), an integer indicating the
current state of the SHIFT/ALT/CTRL keys (Shift), and two
numbers representing the current mouse coordinates within the
area of the object.
• MouseUp:
∗ Happens when you release the mouse button.
∗ VBA passes the same four parameters as for MouseDown.
• Click:
∗ Happens when you’ve clicked and released the mouse once.
∗ VBA provides the primary event used for handling command
button events.
• DblClick:
∗ Happens when you click and release the mouse button twice
within a limited time frame.
∗ Makes it very difficult to react to both the Click and the
DblClick events, unless the DblClick event procedure expands
on, or enhances, what the Click event procedure started.
∗ Allows you to cancel the Click event that follows each
DblClick event by setting the DblClick event’s Cancel
parameter to True.
• MouseUp:
∗ Happens once you release the mouse from the second click.
There’s one final mouse event, but it happens a lot. The MouseMove event
occurs every time you move the mouse. To try this out, select only the Mouse
Movement check box on frmLog. Stand back! The log form will fill up quickly
as you move the mouse around on frmEventTest. Figure 3 shows frmLog after
a few seconds of mouse movement.

6-14 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events: Control Events

Figure 3. The MouseMove event tells you where the mouse is at any given time.

Getting Started with VBA 6-15


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events

VBA Host-Specific Events


Some of the objects in a VBA host application can also have code modules and
events. You’re probably already familiar with the objects themselves: Word
documents, and Excel worksheets and workbooks. Now you can write code
that runs when you perform an action like opening a worksheet or creating a
new document. You can write event procedures for these events just as you do
with form or control events.
Which objects have events? It depends on which host application you’re
talking about. Table 2 shows which objects have events for each application:

Host Application Project Explorer Folder Object Names Object


Types

Microsoft Excel Microsoft Excel Objects Worksheets Worksheet


ThisWorkbook Workbook
Microsoft Word Microsoft Word Objects ThisDocument Document
Microsoft Microsoft PowerPoint N/A N/A
PowerPoint Objects
Microsoft Outlook Microsoft Outlook ThisOutlookObject Application
Objects
AutoCAD AutoCAD Objects ThisDocument Document
ActiveDocument
Visio Visio Objects ThisDocument Document
Table 2. Many Office objects have events you can respond to.

To see which events each of these objects has, you can look in the Object
Browser. Or, you can open an object’s module and scroll through the Object
and Procedure lists.

Word Document Events


A Word Document object has three events: the Open event, the Close event,
and the New event.

The Word Open Event


The Open event occurs when you open a document. You can add code to the
Open event procedure to perform an operation every time a user opens the
document.
For example, suppose you want to store the current date and time in the
document every time a user opens it. You could run the code to do this in the
Open event procedure. Here’s how to do it:
1. Create a new Word document and save it.
2. Open the Visual Basic Editor.

6-16 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events: VBA Host-Specific Events

3. In the Project Explorer, select the project that’s associated with your new
document.
4. Expand the Microsoft Word Objects node, and select the ThisDocument
object (Figure 4).

Figure 4. The Word ThisDocument object.

The ThisDocument object is the object you use from code to work with the
DocEvents document. It refers to the document that’s associated with the
active project.
5. Click the View Code button on the toolbar to open the code module for the
ThisDocument object.
6. In the code module, choose ThisDocument from the Object list and then
choose Open from the Procedure list.
VBA creates the event procedure stub for you:

Private Sub Document_Open()

End Sub

7. Add the following code to the event procedure:

Selection.TypeText Date & " " & Time & vbCrLf & vbCrLf

8. Save and close the document.


9. Reopen the document to trigger the Open event. You’ll see the current date
and time inserted at the top of the document.
Notice that you used Selection again to insert the current date and time into
the document at the insertion point.
What’s vbCrLf? It’s a constant that adds a carriage return and line feed to a
string. In this example, you concatenated vbCrLf into the string twice to create
a blank line after the date and time.

Getting Started with VBA 6-17


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events

The Worksheet Change Event


Now let’s examine an Excel worksheet event. The Change event occurs when
you change the value of a cell on the worksheet. You can use this event to
validate data, or to keep track of what information a user has changed.
To see a simple example of the worksheet Change event, open Ch06.xls and
Try typing values try typing a value into the worksheet. When you change a cell and then leave
into Ch06.xls the cell, the worksheet Change event fires and VBA displays a message box.
Here’s the code for the event procedure:

Private Sub Worksheet_Change(ByVal Target _


As Excel.Range)
' When the user changes a value on the worksheet,
' a message box pops up.
If Target.Cells.Count = 1 Then
MsgBox "You changed the value of " _
& Target.Cells.Address _
& " to '" & Target.Cells.Value & "'."
End If
End Sub

When the user changes a cell on the worksheet, VBA passes a value to the
Change event procedure in the Target argument. This value indicates which
cell on the worksheet was changed. You use the value in the Target argument
to get the address of the cell that was changed and also the value that it was
changed to. You also use it to make sure only one cell is selected.
If you’re somewhat confused by this code, don’t worry about it; it will become
more clear after Excel is covered in more detail. For now, just remember that
you can use events to react to the user’s actions on a worksheet.

6-18 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events: Is There More?

Is There More?
Of course there’s more. You’ve touched on only a few of the many different
events that VBA makes available. Whenever you need to accomplish a task,
your goal will be to determine which events are available, and attach code to
the most appropriate event procedure.
To peruse events, the simplest method is to use the Object Browser:
1. Press F2 to bring up the Object Browser window.
2. Find the object you want in the browser.
3. Right-click to make sure you’ve selected the “Group Members” option.
4. Scroll down until you find the Events (little lightning bolt icons) for the
selected object.
5. Press F1 on any entry in the Object Browser to jump to its Help page.
Figure 5 shows the Object Browser’s list of events for the ComboBox control.

Figure 5. Use the Object Browser to review the list of events for an object.

Other Events
You may notice that other objects in the Object Browser have events listed.
For example, the Microsoft Excel Application object has several events. The
Application object doesn’t have an associated module, however. With some
advanced coding, you can write event procedures for the Application object,

Getting Started with VBA 6-19


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events

even though it doesn’t have a module. However, the technique for doing this is
beyond the scope of this course.

6-20 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events: Is There More?

Summary
• Events occur as the user interacts with the application, and VBA
provides hooks for you to react to these events.
• Event procedures contain code that will run whenever the associated
event occurs.
• Use frmLogEvents to view simple user form events as they occur.
• A form’s Initialize event allows you to modify the user interface
before it’s visible, and to initialize module-level variables.
• You can use the QueryClose event to save data in a user form before
the form closes.
• The Click, DblClick, MouseUp, and MouseDown events occur when
you click or double-click the mouse on a form or control. The
MouseMove event occurs when you move the mouse.
• When you type in a control that can receive text, VBA triggers the
KeyDown, KeyPress, Change, and KeyUp events.
• Some application-specific objects have events that you can use in
VBA. For example, you can run code when a Word document opens,
or when the user changes a cell on a Microsoft Excel worksheet.

Getting Started with VBA 6-21


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events

Questions
1. What is an event?
2. What can you, as a programmer, do when an event occurs?
3. Name two events that occur when a user form loads.
4. What events may occur when the user clicks the mouse on a control?
5. What kinds of events can occur for a Word document?

6-22 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Understanding Events: Is There More?

Answers
1. What is an event?
Something that happens in the application, to which your code
can react. An event may occur when the user performs an action,
or in some cases, when the application performs an action.
2. What can you, as a programmer, do when an event occurs?
Write code in an event procedure that gets called when the event
occurs
3. Name two events that occur when a user form loads.
Initialize, Load, Resize, Activate
4. What events may occur when the user clicks the mouse on a control?
Click, DblClick, MouseDown, MouseUp
5. What kinds of events can occur for a Word document?
Events occur when a document is opened, when a new document
is created from a template, and when a document is closed.

Getting Started with VBA 6-23


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Manipulating Form and Control Properties

Manipulating Form
and Control
Properties
Objectives
• Set and retrieve property values at run time.
• Change a form’s back color and mouse cursor.
• Understand how to work with data entry controls.
• Set different properties for a text box control.

Getting Started with VBA 7-1


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Manipulating Form and Control Properties

Setting Properties at Run Time


The Properties window is just the beginning when it comes to setting property
values. You also find that you’ll want to set property values while a user form
is loaded, or when an event occurs.
As you’ve seen, you always begin running your code from an event procedure.
You’ll often set property values of controls and forms in response to events. In
this section, you’ll see how to do this in some real-world situations.

Setting Property Values


In general, you’ll need to do two things to property values—set them and
retrieve them. The general syntax for setting property values is:

object.property = value

In this example:
• Object is the name of a form or control (other types of objects are
discussed later in the course).
• Property is the name of a property.
• Value is the new value for the property and can be a literal value, a
variable, or an expression.
You saw several examples of this in previous chapters. For instance, you saw
this line of code:

Me.cmdOK.Enabled = False

This statement sets the Enabled property of a control named cmdOK to the
value False. This means that at run time, the user would not be able to click on
the OK button—usually this is a condition that you set while you’re waiting
for a user to do something somewhere else on the form. Read the next section
to see how you would actually use property values in your VBA code.

Retrieving Property Values


When you retrieve a property’s value, you usually want to do something with
the value you get back. Depending on what your code is doing, you have a
variety of choices, including:
• Storing the value in a variable so that you can use it later in your
procedure.

7-2 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Manipulating Form and Control Properties: Setting Properties at Run Time

Dim strCaption As String


strCaption = UserForm1.Caption

• Printing the value to the Debug window.

Debug.Print UserForm1.Caption

• Using the value in another expression or function.

MsgBox "The current caption is " & _


UserForm1.Caption
' or
Call HandleButton(Me.cmdOK.Enabled)

TIP: Remember that when VBA sees object.property it interprets this (in most
cases) as a value. That means you can use this syntax wherever you would
normally use a literal value like a string or number.

Getting Started with VBA 7-3


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Manipulating Form and Control Properties

Setting Form Properties


Changing the BackColor
Let’s start off with an easy example—changing a form’s BackColor property.
To change the color, you’ll supply values between 0 and 255 for the red, blue,
and green components of an RGB color value.
Open frmChangeColor, which appears as shown in Figure 1, type numbers
See between 0 and 255 in each of the text boxes, or click the spin buttons.
frmChangeColor

Figure 1. Enter values between 0 and 255 in each text box.

Here’s the event procedure that changes the form’s BackColor property when
you click the spin button associated with the red color element. The procedure
first updates the value in the text box to match the value of the spin button.
Then it calls the RGB function with the values contained in all of the text
boxes, and assigns the result to the form’s BackColor property.

Private Sub spbRed_Change()


' Change text box value to match spin button.
Me.txtRed.Value = Me.spbRed.Value
' Change back color.
Me.BackColor = RGB(Me.txtRed.Value, _
Me.txtGreen.Value, Me.txtBlue.Value)
End Sub

This form also allows you to change the form’s BackColor by typing a new
value in the text box. The Change event procedure for each text box performs
some data validation, and then changes the value of the corresponding spin
button. When the value of the spin button changes from code, the spin button’s
Change event occurs automatically, running the code that changes the
BackColor property.

7-4 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Manipulating Form and Control Properties: Setting Form Properties

Changing a Form’s Mouse Cursor


Changing the mouse cursor is a good way to provide users with feedback. You
can do this by setting a form’s MousePointer property.
The MousePointer property accepts one of several predefined values and
changes the mouse cursor. The values used most often are
fmMousePointerHourglass and fmMousePointerDefault, two constants that
change the cursor to an hourglass and the default arrow, respectively.
The frmMousePointer form contains two buttons that change the mouse
Check out pointer to an hourglass and back to the default arrow. Here’s the code:
frmMousePointer
in Ch07.xls

Private Sub cmdOn_Click()


' Change mouse pointer to an hourglass
Me.MousePointer = fmMousePointerHourGlass
End Sub

Private Sub cmdOff_Click()


' Change mouse pointer back to an arrow
Me.MousePointer = fmMousePointerDefault
End Sub

Table 1 shows the other constants that you can use to set the MousePointer
property:

Getting Started with VBA 7-5


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Manipulating Form and Control Properties

Constant Description

fmMousePointerArrow Arrow
fmMousePointerCross Cross-hair pointer
fmMousePointerIBeam I-beam
fmMousePointerSizeNESW Double arrow pointing northeast and southwest
fmMousePointerSizeNS Double arrow pointing north and south
fmMousePointerSizeNWSE Double arrow pointing northwest and southeast
fmMousePointerSizeWE Double arrow pointing west and east
fmMousePointerUpArrow Up arrow
fmMousePointerNoDrop “Not” symbol (circle with a diagonal line) on top of
the object being dragged. Indicates an invalid drop
target
fmMousePointerAppStarting Arrow with an hourglass
fmMousePointerHelp Arrow with a question mark
fmMousePointerSizeAll Size all cursor (arrows pointing north, south, east,
and west)
Table 1. Constants for the MousePointer property.

You can use the MousePointer property to change the cursor to one of several
standard cursors that are defined by the Control Panel settings on your
computer.

7-6 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Manipulating Form and Control Properties: Setting Control Properties

Setting Control Properties


Most of the properties that you manipulate at run time will be control
properties. This section covers a number of broad categories of controls, giving
useful examples of each.

Data Entry Controls


If you are creating any type of data entry application, then you’ll find that you
need to set properties on the data entry controls (text boxes, check boxes, etc.)
to control when and how the user interacts with them. There are three
properties that you’ll want to pay special attention to:
• The Enabled property regulates whether a user can select a control
and, possibly, enter or change data. When this property is set to False
(i.e., the control is disabled), the user cannot select it and it appears
“grayed out.”
• The Locked property regulates whether a user can change the data that
appears in the control. If a control is enabled but locked, the user will
be able to select the control and its data (perhaps to copy it to the
clipboard) but cannot alter it.
• The Visible property regulates whether a control appears on a form at
all. Sometimes hiding a control makes sense when you don’t want
users to see or change data.

Check out To demonstrate these properties in action the frmEnLockVis (see Figure 2)
frmEnLockVis in form features buttons that toggle a text box’s Enabled, Locked, and Visible
Ch07.xls properties.

Figure 2. This form lets you test the Enable, Locked, and Visible properties.

The code behind each button’s Click event is shown below:

Getting Started with VBA 7-7


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Manipulating Form and Control Properties

Private Sub cmdDisable_Click()


' Disable the control
Me.txtTest.Enabled = False
End Sub

Private Sub cmdEnable_Click()


' Enable the control
Me.txtTest.Enabled = True
End Sub

Private Sub cmdUnlock_Click()


' Unlock the control
Me.txtTest.Locked = False
End Sub

Private Sub cmdLock_Click()


' Lock the control
Me.txtTest.Locked = True
End Sub

Private Sub cmdHide_Click()


' Hide the control
Me.txtTest.Visible = False
End Sub

Private Sub cmdShow_Click()


' Show the control
Me.txtTest.Visible = True
End Sub

TIP: With the exception of check boxes, option buttons, and frames, controls on
user forms don’t have attached labels; a label is always a separate control. If
you change the Visible or Enabled property of a control, you should also
change the same property of the label that identifies it, if there is one.

7-8 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Manipulating Form and Control Properties: Setting Control Properties

Text Box Properties


The text box is one of the controls you’ll use most frequently, so it’s helpful to
be familiar with some of its properties.
• The MultiLine property specifies that a text box can have more than one
line. If a text box can contain more than just a few words, and you want
the user to be able to view all of the text at once, set the MultiLine
property to True.
• The EnterKeyBehavior property determines what happens when the user
presses the ENTER key while in the text box. This property can only be
true if the MultiLine property is also set to True. If both MultiLine and
EnterKeyBehavior are True, then pressing ENTER creates a new line in
the text box.
• The SelectionMargin property specifies whether the user can select a line
by clicking in the left-hand margin of the text box.
• The ScrollBars property specifies whether the text box contains scroll bars.
When the ScrollBars property is True, scroll bars only appear when there
is more text in the text box than it can display.
• The MaxLength property determines the maximum number of characters
that the user can type into the text box. The default value is 0, which
indicates that there is no limit to the number of characters. This may be a
little counter-intuitive, but that’s the way it works.

Try It Out!
To get the hang of how these text box properties work, look at frmTextBox in
frmTextBox in Ch07.xls, or import TextBox.frm into your application.
Ch07.xls

1. Load frmTextBox properties by pressing F5 or choosing Run|Run


Sub/UserForm from the menu. The form appears as in Figure 3.

Figure 3. You can use the frmTextBox form to try out text box properties.

Getting Started with VBA 7-9


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Manipulating Form and Control Properties

2. Type some text into the text box, then check the MultiLine option to make
it a multi-line text box.
3. Toggle the SelectionMargin option to see how it affects the text box.
4. Try pressing the ENTER key with and without the EnterKeyBehavior
option selected.
5. When you’ve typed more text into the text box than it can display at once,
select the ScrollBars option to show the scroll bars for the form text box.
6. Clear the text from the text box. Change the value of the MaxLength
property to a small integer like 2, then try typing in the text box again.
Each property is set in the Change event procedure for the associated check
box. Here are the event procedures that set each property:

Private Sub chkMultiLine_Change()


' This procedure sets the MultiLine property
' based on the value of chkMultiLine.
' It enables the chkEnterKey check box if
' MultiLine is True.

If Me.chkMultiLine.Value = True Then


' Set MultiLine to True.
Me.txtData.MultiLine = True
' Enable the EnterKeyBehavior check box.
Me.chkEnterKey.Enabled = True
Else
Me.txtData.MultiLine = False
Me.chkEnterKey.Enabled = False
End If
End Sub

Private Sub chkSelectionMargin_Change()


' If the check box is checked, set the
' SelectionMargin property to True.
If Me.chkSelectionMargin.Value = True Then
Me.txtData.SelectionMargin = True
Else
Me.txtData.SelectionMargin = False
End If
End Sub

7-10 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Manipulating Form and Control Properties: Setting Control Properties

Private Sub chkEnterKey_Change()


' If the check box is checked, set the
' EnterKeyBehavior property to True.
If Me.chkEnterKey.Value = True Then
Me.txtData.EnterKeyBehavior = True
Else
Me.txtData.EnterKeyBehavior = False
End If
End Sub

Private Sub chkScrollBars_Change()


' If the Scroll Bars check box is checked,
' show both scroll bars. Otherwise show none.
If Me.chkScrollBars = True Then
Me.txtData.ScrollBars = fmScrollBarsBoth
Else
Me.txtData.ScrollBars = fmScrollBarsNone
End If
End Sub

Private Sub txtMaxLength_Change()


' Set the max length of the text box
' to the value in txtMaxLength.
Me.txtData.MaxLength = Me.txtMaxLength.Value
End Sub

Getting Started with VBA 7-11


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Manipulating Form and Control Properties

Summary
• You can set properties of forms and controls at run time.
• The general syntax for referring to properties is object.property.
• You can change a form’s mouse cursor to provide your users with
feedback.
• Most controls have Enabled, Locked, and Visible properties that you
can use to control data entry.
• You can change properties of a text box to achieve the behavior you
want.

7-12 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Manipulating Form and Control Properties: Setting Control Properties

Questions
1. List two things you can do with the value you retrieve from a property
setting.
2. What are the two most commonly used mouse pointer constants?
3. How do you create a text box that allows users to select, but not change
text?
4. Which property do you set to make a text box display more than one line?
5. Write a statement that sets the Height property for the currently running
form to 200 points.
6. Write a statement that prints the value of the Text property of a text box to
the Immediate window.

Getting Started with VBA 7-13


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Manipulating Form and Control Properties

Answers
1. List two things you can do with the value you retrieve from a property
setting.
Assign it to a variable, print it to the Immediate window, use it in
an expression (e.g., pass it to a procedure, use it as a conditional
value in a loop or branching statement)
2. What are the two most commonly used mouse pointer constants?
fmMousePointerDefault and fmMousePointerHourGlass
3. How do you create a text box that allows users to select, but not change
text?
Set its Locked property to True
4. Which property do you set to make a text box display more than one line?
MultiLine property
5. Write a statement that sets the Height property for the currently running
form to 200 points.
Me.Height = 200
6. Write a statement that prints the value of the Text property of a text box to
the Immediate window.
Debug.Print TextBox1.Text

7-14 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
An Introduction to Objects

An Introduction to
Objects
Objectives
• Understand objects, object models, and collections.
• Explore the Object Browser.
• Learn to work with properties and methods.
• Learn to work with object variables.
• Learn to use For Each...Next to iterate through collections of objects.
• Learn to use With...End With to work with multiple properties and
methods.

Getting Started with VBA 8-1


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
What Is an Object?

What Is an Object?
An object is a single entity that you can use in code to work with some part of
an application. It’s a thing that you can control, programmatically. Often an
object represents a part of an application that you’re already familiar with, like
a form.
An object maintains its own set of properties and methods, which you’ll work
with in order to control the object. You’ve read about properties in previous
chapters, but let’s review:

Key Terms

Property An attribute of an object, such as its color or its font name. You
can both set and retrieve most properties of most objects.

Method An action the object “knows” how to take. For example, a user
form, in VBA, knows how to show itself (that is, make itself
visible) using its Show method.

Object Models
Objects represent different parts of an application conceptually. For some
applications, just about every part of the application that you can work within
the user interface is also represented by an object.
The set of objects that an application has is referred to as its object model. An
object model is a logical representation of the way programmable objects are
grouped, within an application.
Most object models are organized hierarchically. This means that there are
certain objects that contain other objects, and those objects may contain still
other objects.
When you’re programming in VBA, you’ll find a number of different object
models: one for VBA itself, another for user forms, and another for the
application you’re working in. In each case, an object model consists of
objects, and collections of like objects. For example, the Microsoft Excel
object model (discussed in the next section) contains the Application object
and a collection of open Workbook objects.

8-2 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
An Introduction to Objects: What Is an Object?

Key Term

Collection A group of objects that all have the same type. A collection may
contain any number of objects, or it may contain none at all.

The Microsoft Excel Object Model


Let’s consider the Excel object model. The Excel object model is quite
extensive and complex; there’s an object to represent just about every part of
Excel. The model won’t be discussed in detail here, but a few objects will be
used to demonstrate the object model hierarchy. Figure 1 shows the objects at
the top of the Excel object model.

Figure 1. A portion of the Excel object model.

A Few Good Objects


The highest-level object in the Excel object model is the Application object.
The Application object represents the Excel application itself. The Application
object contains the Workbooks collection.
A Workbook object corresponds to an Excel workbook, which is what you
create when you create a new document in Excel. The Workbook object, in
turn, contains two other collections, the Worksheets collection and the Charts
collection.
The Worksheet object represents a Excel worksheet, which is the page onto
which you enter data in Excel. The Chart object represents a chart on a sheet in
a workbook.
Figure 1 also shows a few methods of the Worksheet and Chart objects. You
use these methods to work with the objects.

Getting Started with VBA 8-3


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
What Is an Object?

The Microsoft Forms Object Model


Let’s briefly examine one more object model, the Microsoft Forms object
model. This object model contains user form and control objects that are
objects you can work with in your code. In fact, that’s what you did in the
previous chapter when you set their properties from code.
The Microsoft Forms object model is a little more complex than Figure 2
shows, but for now this is all you need to worry about. The UserForms
collection contains all open UserForm objects. A UserForm object contains a
Controls collection, which contains all the Control objects on the user form.

Figure 2. The relationship between UserForms and Controls.

8-4 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
An Introduction to Objects: The Object Browser

The Object Browser


How do you keep track of all the objects in each object model, and their
properties and methods? One helpful tool is the Object Browser, shown in
Figure 3. The Object Browser lists all of the objects, properties, methods,
constants, and events in an object model.

Project/Library
list

Search text

Members
Classes list of list

Details
pane
Figure 3. The Object Browser shows the properties, methods, and events for each
object in an object model.

Opening the Object Browser


To open the Object Browser, open a document in your host application and
follow these steps:
1. Open the Visual Basic Editor.
2. Choose View|Object Browser from the menu, or press F2.

The Parts of the Object Browser


The Object Browser has been mentioned in previous chapters, but you haven’t
learned how to use it yet. In order to familiarize yourself with the Object
Browser, this section dissects it into its various parts.

Getting Started with VBA 8-5


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
The Object Browser

The Project/Library List


This drop-down list contains all of the object models that are currently
available to VBA. You can select <All Libraries> to view them all at once, or
you can choose an individual library from the list.

Search Text
To search the Object Browser, enter the text you want to search for and press
ENTER, or click the Search button.

Classes List
The Classes list shows all the available types of objects in the selected type
library. When you select an object from the Classes list, the properties,
methods, and events (or members) for the selected class appear in the
“Members of” list box.

Members of List
The “Members of” list displays the methods, properties, events, and constants
that belong to the selected object in the Classes list.

Details Pane
The Details pane at the bottom of the Object Browser provides additional
information on any class, property, method, event, or constant that you select.

Try It Out!
Now that you’re familiar with the Object Browser, take a minute to explore it.
1. Open a new workbook in Excel.
2. Switch to the Visual Basic Editor and open the Object Browser.
3. In the Project/Library list, choose Excel.
4. Select the Application object and examine its members in the “Members
of” list.
5. Select the Visible property in the “Members of” list. Notice that when you
select the property, information about the property shows up in the Details
pane at the bottom of the Object Browser.
6. Press F1 to bring up the Help topic on the Visible property.

NOTE If you get an error when you press F1, you probably haven’t
installed Visual Basic Help for Microsoft Excel. To install Visual
Basic Help, rerun Setup and make sure you select Visual Basic
Help under the main Help category.

8-6 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
An Introduction to Objects: The Object Browser

Figuring Out the Object Hierarchy


Although the Object Browser is a great tool for finding out about an object’s
properties and methods, it’s not much help for understanding the overall
structure of an application’s object model. All of the objects in the object
model appear together in the Classes list, and it’s difficult to see quickly how
they relate to one another in the hierarchy.
You can view the complete object model diagrams in online Help. Follow
these steps to find the object model diagrams for Excel:
1. From the Object Browser, choose the Excel library and click the Help
(question mark) button.
2. Click the Contents tab.
3. Open the entry for the Microsoft Excel Visual Basic reference, and double-
click the Microsoft Excel Objects topic.
The steps for finding the object model diagrams for the other Office
applications are similar.

Getting Started with VBA 8-7


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Objects in VBA

Working with Objects in VBA


Referring to Objects in Collections
As you saw in Figure 1, many objects in the Microsoft Excel object model
belong to collections of objects. The Workbooks collection contains all the
open workbooks, and the Worksheets collection contains all the worksheets in
the workbook.
To refer to an object in code, you specify its position in the object model. In
other words, you specify an “address” for an object within the object model so
that VBA knows exactly which one you want.

Referring to Objects by Name


You can refer to an object in a collection by its name. For example, suppose
See module you want to refer to a particular workbook object that’s open in Microsoft
basReferToObjects Excel. You can refer to the Workbook object in the Workbooks collection by
for examples its name:

Application.Workbooks("Ch08.xls")

This code tells VBA that you want to work with the workbook Ch08.xls. It
refers to the Workbooks collection of the Application object, then to an
individual workbook within the collection.
Actually, you don’t need to include the Application object in this code. Since it
contains all of the other objects and collections in Excel, it’s implied. We
included it just to show that Workbooks is a collection of the Application
object.

Referring to Objects by Position


Another way to refer to an object in a collection is by its position within the
collection, which is identified by a number called an index. The first open
workbook in the Workbooks collection will have an index of 1, the second, an
index of 2, and so on. To refer to the first workbook in the collection, specify
the index value:

Workbooks(1)

The problem with using this technique is that if there is more than one
workbook open, there’s no way to know which one you’ll get back. If you
need just any old workbook, it doesn’t matter, but if you need a specific one,
you should probably refer to it by name.

8-8 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
An Introduction to Objects: Working with Objects in VBA

What If You Don’t Know the Object’s Name?


When you’re writing code, you may encounter a situation where you need to
refer to an object, but you won’t know which object until the code is running.
In that case, you still refer to the object in the collection by its name, but you
use a string variable to represent the name of the object.

' Here, strWorkbook is a string variable


' containing the name of the workbook.
Workbooks(strWorkbook)

NOTE There’s another way to refer to an object that you may also
encounter. This syntax uses the bang (!) operator. The bang
operator separates the collection from the name of the object. You
can use the bang syntax to refer to an object in a collection, but
there’s no need to, since the parentheses syntax discussed
previously works perfectly well. What’s more, the parentheses
syntax accommodates a variable, while the bang syntax does not.

Table 1 summarizes the different ways to refer to an object in a collection:

Syntax Notes

Collection("ObjectName") Preferred syntax if you know the name of the


object, or if the object name is stored in a variable.
Collection(Index) Refer to an object by its position in the collection.
Collection!ObjectName Acceptable, but less flexible than parentheses
syntax.
Table 1. There are several different techniques you can use to refer to an item in a
collection.

Referring to Collections Within Objects


As previously discussed, collections can contain objects, and objects can also
contain other collections. You’ve seen how to refer to an object within a
collection, but that’s only the first step. To get to a specific object in the object
hierarchy, you’ll need to refer to both objects and collections.
To refer to a collection contained within an object, you use the dot (“.”)
operator. For example, to refer to the Worksheets collection of a Workbook
object, you would use syntax like the following:

Workbooks("Ch08.xls").Worksheets

Getting Started with VBA 8-9


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Objects in VBA

Note that the dot operator separates the Workbook object specified by
Workbooks(“Ch08.xls”) from the Worksheets collection.
Of course, you can then refer to a specific object within the Worksheets
collection, and so on through the object hierarchy:

Workbooks("Ch08.xls").Worksheets(1)

Sometimes you may see a UserForm object and a Control object separated
only by the dot operator, as in the following example:

UserForm1.CommandButton1

What’s going on here? This is actually a special shortcut that you can use to
refer to controls on user forms.
In this case, the command button is a Control object that belongs to the
Controls collection of the user form. The Controls collection is the default
collection of a user form (in fact, it’s the only collection of a user form). That
is, if you don’t explicitly state a collection, VBA assumes that the object
belongs to the Controls collection. You can also explicitly state that the object
is a member of the Controls collection:

UserForm1.Controls("CommandButton1")

Setting Properties on Objects


Excel Objects
You use the same strategies to set and return properties values for Excel
objects that you use for properties of forms and controls. This code prints the
path and filename of the workbook to the Immediate window:

Debug.Print Workbooks("Ch08.xls").FullName

To work with an object that’s “deeper” into the object model, you just have to
specify which objects are above it. For example, to return the Visible property
of a Worksheet object, you refer to the workbook that contains the worksheet,
then to the worksheet itself:

Debug.Print Workbooks("Ch08.xls").Worksheets(1).Visible

8-10 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
An Introduction to Objects: Working with Objects in VBA

In this case you referred to the worksheet by its index number. This code will
return the Visible property for the first worksheet in the workbook.

Shorten Your Code with Default Properties


Most objects have a “most likely to be set or retrieved” property. This property
is called the default property.
Some objects have as their default property a property that returns an object or
collection. The default collection of the UserForm object has already been
discussed—it’s the Controls collection. You actually use the Controls property
to return a reference to the Controls collection. In other words, the default
property and the default collection for the UserForm object are the same thing.
You can refer to the value of a control on a user form in one of the following
ways:

Debug.Print UserForm1.Controls("txtInput").Value
' or
Debug.Print UserForm1.txtInput.Value

For controls, the default property is typically the one you’ll check most often.
For example, the default property of a TextBox control is the Value property.
You can get the value of the Value property without actually including the
Value property:

Debug.Print txtInput.Value
' or
Debug.Print txtInput

How can you tell which property is an object’s default property? Take a look
at the MSForms library in the Object Browser. You’ll see that the Controls
property of the UserForm object has a small blue marble above it. This marble
denotes that a property is the default property.

Taking Action: Methods


In addition to properties, the objects in an object model also have methods. A
method is an action that the object can perform.
Using a method of an object is similar to calling any other procedure, except
that you must refer to the object. Like procedures, methods can take
arguments.
Some methods behave like function procedures and return a value (or in some
cases, an object). You can use the value they return elsewhere in your code, or

Getting Started with VBA 8-11


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Objects in VBA

you can ignore it. Other methods behave like Sub procedures; they simply
perform an operation and don’t return a value.
For example, the Save method of a Workbook object doesn’t return a value, so
you don’t include parentheses with it:

Workbooks("Ch08.xls").Close xlSaveChanges

The CheckSpelling method of the Microsoft Excel Application object, on the


other hand, does return a value:

Dim blnSpell As Boolean


blnSpell = Application.CheckSpelling("alot")

In this case, the CheckSpelling method returns False, since the word is spelled
incorrectly.

8-12 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
An Introduction to Objects: Using Object Variables

Using Object Variables


Introducing Object Variables
When manipulating objects, it is often more convenient to use a variable to
represent the object than to refer to it repeatedly through the VBA hierarchical
syntax. In fact, for repeated references to the same object, the code executes
much faster if you use a variable.
When you create an object variable, VBA creates only a “pointer” to the
object. That is, the variable it creates only refers to a real object in memory;
it’s not a real object itself. This is different from other variable types, where
the variable itself actually contains the value that it’s assigned.
You can create an object variable to refer to most objects. VBA supports
object variable types for each of the objects. That is, you can write code like
this:

Dim frm As UserForm


Dim ctl As Control
Dim wbk As Workbook
Dim wks As Worksheet

In the most general case, you can write:

Dim obj As Object

But the more specific you can be about your object variable declarations, the
more VBA can do for you internally.
In the previous code example, the variables do not hold any data, nor do they
refer to any real objects at this point. To make an object variable actually refer
to a real object, you must use the Set keyword. In every case, you use Set to
“point” the variable at a real object. For example, using the variables in the
previous example, you might see code like this:

Set frm = UserForms("frmChangeProps")


Set ctl = Me.cmdOK
Set wks = Workbooks("Ch08.xls").Worksheets(1)

Getting Started with VBA 8-13


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Using Object Variables

In each case, you’ve made the object variable refer to an actual object. Without
this step, the object variables are just placeholders—they don’t actually refer to
any object.

Using Object Variables


Imagine that you want to change a number of properties of a specific control,
Try at run time. The sample form, frmChangeProps, includes code to change
frmChangeProps in properties of one of the text boxes on the user form. The code uses direct,
Ch08.xls explicit references to the control each time:

Me.txtInput.BackColor = RGB(0, 255, 0)


Me.txtInput.ForeColor = RGB(255, 0, 0)
Me.txtInput.FontName = "Arial"
Me.txtInput.FontSize = 14
Me.txtInput.FontBold = True

A better way (but not the best way—see the next section for the best way)
would be to use an object variable to refer to the control that’s being altered:

Dim txt As Control


Set txt = Me.txtInput

txt.BackColor = RGB(0, 255, 0)


txt.ForeColor = RGB(255, 0, 0)
txt.FontName = "Arial"
txt.FontSize = 14
txt.FontBold = True

Note the use of the Set keyword to make the variable txt refer to the real text
box before the code attempts to use txt. If you want to see what happens
without the Set statement, comment out that line of code and attempt to run the
form example again. You’ll get an error 91: “Object variable or With block
variable not set.”

8-14 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
An Introduction to Objects: Using Object Variables

What About Uninitialized Object


Variables?
Before you assign a value to a simple variable, its type determines its value—
any numeric variable has a value of 0, a variant variable has the special value
of Empty, and a string variable contains a zero-length string. All object
variables, however, can have the special value of Nothing. If an object variable
has the value of Nothing, it either hasn’t yet been initialized, or it no longer
points to an object in memory.
You cannot use the equals operator to check whether an object variable has the
value of Nothing; you must use the Is operator instead:

If ctl Is Nothing Then


' You know that ctl doesn't point to any
' object yet.
End If

To check and see that a variable does point to an object, you can use code like
this:

If Not ctl Is Nothing Then


' You know ctl points to an object.
End If

To free up resources, you can set an object variable to Nothing when you’re
done using it. This is considered good coding practice:

Set ctl = Nothing

Getting Started with VBA 8-15


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Special VBA Constructs for Objects

Special VBA Constructs for Objects


Introducing For Each...Next
The For Each...Next looping control structure allows you to loop through all
the elements of any collection, without having to know how many items there
are. The general syntax is:

For Each element In group


[statements]
[Exit For]
[statements]
Next [element]

The following points explain each of the parts of the construct:


• element: an object variable of the type of object contained in the
collection.
• group: a collection of objects, such as UserForms, Controls,
Worksheets, etc.
• statements: 0 or more statements to execute for each element of the
collection.
• Exit For: Just as with For...Next loops, you can exit a For...Each...Next
loop early. The code will continue execution with the line after the
Next [element] statement.
• Next [element]: Concludes the loop. The [element] is optional, but
makes the code easier to read, and is highly recommended.

A Simple Example
For example, you could use the following code to loop through all the open
Try frmForEach forms and change all their background colors to a specific color:

8-16 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
An Introduction to Objects: Special VBA Constructs for Objects

Private Sub cmdForEach_Click()


Dim ctl As Control

For Each ctl In Me.Controls


ctl.BackColor = RGB(0, 255, 0)
Next ctl
End Sub

Differentiating Types of Controls


Each user form contains a Controls collection. You may have an occasion to
want to visit every control on the form, and do something with that control
depending on its type.
If you need to differentiate between types of controls within a procedure, VBA
provides a method for doing this, but it’s not pretty. To determine the control
type from within your code, you must use the construct:

If TypeOf <control> Is <ClassName> Then

You cannot use a Select Case statement, so you must check for each control
type with an individual call to TypeOf, like this:

If TypeOf ctl Is TextBox Then


' Code here to handle text boxes
ElseIf TypeOf ctl Is ComboBox Then
' Code here to handle combo boxes
ElseIf TypeOf ctl Is CheckBox Then
' Code here to handle check boxes
' And so on, and so on…
End If

The following example works its way through each control on the form and
changes the text color of the control according to what type of control it is.
To run this code, run frmForEach, and click on the TypeOf Control button.
Open frmForEach This will change the background color for each control on the form.
and click the
“TypeOf Control”
button Private Sub cmdTypeOfControl_Click()

Getting Started with VBA 8-17


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Special VBA Constructs for Objects

' Change the text color of all the controls


' on frmForEach.

' You can't declare this as a specific control


' type, because you don't know the control type.
Dim ctl As Control

For Each ctl In Me.Controls


If TypeOf ctl Is CommandButton Then
ctl.BackColor = vbRed
ElseIf TypeOf ctl Is ComboBox Then
ctl.BackColor = vbBlue
Else
ctl.BackColor = vbGreen
End If
Next ctl
End Sub

TIP: You could use this same technique to disable certain types of controls on a
form; loop through the Controls collection, and set the Enabled and Locked
properties for specific controls.

NOTE There’s another way to determine the type of any object; the
TypeName function returns a string containing the type name of
the object you pass it (“ListBox” for a list box, “TextBox” for a
text box, and so on). Although this function has its uses, you may
not want to use it for determining an object’s type, because using a
string provides no compile-time checking. If you’re checking to
see if a control is a list box, and compare its TypeName to
“ListBox,” what happens if you type the name incorrectly? Your
code doesn’t work, and the compiler doesn’t complain. The If
TypeOf construct may be difficult to use, but it does provide
compile-time checking of your code.

8-18 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
An Introduction to Objects: Special VBA Constructs for Objects

Referring to Objects on Forms


Step through the So far, you’ve only referred to objects on the current user form, from code in
code in that form’s class module. When you need to refer to controls on a different
frmReferToObjects form, you must tell VBA what form you’re referring to. For example, to refer
to the control named cboStates on the form named frmReferToObjects, in the
module attached to frmReferToObjects, you could write code like this:

cboStates.AddItem "Some New Item"

You could also use the Me keyword to refer to the current form:

Me.cboStates.AddItem "Some New Item"

If you wanted to refer to that same combo box from a different form, you’d
have to tell VBA where to look for the control, like this:

frmReferToObjects.cboStates.AddItem "Some New Item"

You can’t use the Me keyword to refer to a form from any module except that
form’s own module.

Using With...End With


The With...End With statement allows you to set multiple properties or call
multiple methods on the same object in one construct. For example, suppose
you want to refer to many properties or methods for one object. You can use
the With...End With statement to set multiple properties, or execute methods,
by typing the object name only once.
The general syntax looks like this:

With object
[statements]
End With

The object reference can be any object, and [statements] refers to any
properties or methods of that object that you need to reference. In those
statements, you don’t repeat the name of the object, or the reference to it; you
just include the “.” separator.

Getting Started with VBA 8-19


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Special VBA Constructs for Objects

Previously, frmChangeProps showed you how to change multiple properties of


Check out a control. Using the With...End With construct, you could rewrite the code like
frmChangeProps this:
once again

Dim txt As Control


Set txt = Me.txtTest

With txt
.BackColor = vbBlack
.ForeColor = vbCyan
.FontName = "Arial"
.FontSize = 16
.FontBold = True
End With

8-20 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
An Introduction to Objects: Special VBA Constructs for Objects

Summary
• Objects represent different parts of a component or application that
you can work with from code.
• Objects have properties and methods that you can use to determine
their characteristics and make them perform certain actions.
• You can use the Object Browser to investigate properties and methods
of objects.
• To work with an object, you must refer to it by its position in the
object model.
• You can refer to an object either by its name or by its index number in
the collection to which it belongs.
• When creating object variables, assign them the most specific type you
can.
• Use the Set keyword to assign an object variable to an object.
• Once you use the Set keyword, the object variable acts as a reference
to the real object. Use the variable any place you might otherwise use
a reference to the object.
• Use the For Each…Next construct to loop through all of the objects in
a collection, without having to know the number of objects.
• Use the TypeOf construct to determine a control’s type
programmatically.
• Use With...End With to set multiple properties or call multiple
methods for a single object, without having to retype its name or re-
reference it.

Getting Started with VBA 8-21


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Special VBA Constructs for Objects

Questions
1. What is a property? What’s a method? Give an example of each.
2. Write a loop that will traverse all the controls on the current form (i.e., you
can use Me) and print all the control names to the Debug window.
3. How can you locate a property of a Worksheet object in the Object
Browser?
4. How might you refer to a workbook named MyWorkbook?
5. Is the Set keyword ever optional when declaring an object variable?
6. Why should you use a specific object type, rather than a generic one?

8-22 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
An Introduction to Objects: Special VBA Constructs for Objects

Answers
1. What is a property? What’s a method? Give an example of each.
A property is an attribute of an object. A method is an action that
an object knows how to perform.
2. Write a loop that will traverse all the controls on the current form (i.e., you
can use Me) and print all the control names to the Debug window.
Dim ctl As Control
For Each ctl In Me.Controls
Debug.Print ctl.Name
Next ctl
3. How can you locate a property of a Worksheet object in the Object
Browser?
Choose Excel from Project/Library list, locate Worksheet in
Classes list, look for properties in Members of list
4. How might you refer to a workbook named MyWorkbook?
Workbooks(“MyWorkbook”)
5. Is the Set keyword ever optional when declaring an object variable?
No, not ever. It’s required in order to make an object variable
refer to an object.
6. Why should you use a specific object type, rather than a generic one?
Using a specific object makes it possible for VBA, at compile-time,
to gather information it needs to run your code faster. If you
want to write a single procedure that can work with multiple
object types, use a generic object type.

Getting Started with VBA 8-23


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel

Programming
Word and Excel
Objectives
• Learn about the top-level objects in the Excel object model.
• Work with data in cells on a worksheet.
• Become familiar with some of the key objects in the Word object
model.
• Use the Range object to manipulate text in a document.

Getting Started with VBA 9-1


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel

The Excel Object Model


Excel’s object model includes just about every feature that’s available to you
in Microsoft Excel. As object models go, it’s sophisticated and fairly complex.
Fortunately, to get started programming with Excel, you only need to
understand how to work with a few objects. From there, you’ll find that you
can figure out what you need to know as you go along.
Figure 1 shows a simplified version of the Excel object model. For the
complete object model, see online Help. The object model is also available on
the Microsoft web site, at
http://www.microsoft.com/OfficeDev/Articles/OMG/default.htm.

Figure 1. A portion of the Excel object model.

TIP: If you want to explore Excel’s objects, properties, and methods, head to the
Object Browser, and press F1 for context-sensitive Help.

9-2 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel: Microsoft Excel’s Top-Level Objects

Microsoft Excel’s Top-Level Objects


The Application Object
The Application object represents Excel itself. It contains all of the other
objects and collections in the object model. It also contains properties and
methods of its own.
When you’re programming in Excel, you don’t always need to refer to the
Application object explicitly. If you’re using a property or method that appears
under the Globals class in the Object Browser, then you don’t need to specify
the Application object. If you’re using a property or method that appears only
under the Application class, and not also in the Globals class, then you do need
to explicitly refer to the Application object.
For example, you don’t need to use the Application object when you refer to a
member of the Workbooks collection, because the Workbooks property is
global. This code makes a workbook the active workbook in Microsoft Excel:

Workbooks(1).Activate

However, you do need to use it when you call a method of the Application
object. The GetOpenFileName method of the Application object shows the
File Open dialog box, and returns a string containing the name of the file that
the user chose:

Dim strFileName As String


Const conFilter = "All Files (*.*),*.*"

strFileName = Application.GetOpenFilename(conFilter)

The Workbook Object


The Workbook object represents a workbook that’s open in Excel. It can refer
only to open workbooks.
There are a couple of ways to refer to a Workbook object in order to use it:
• Use the Workbooks property of the Application object with an index
value or the name of the Workbook:

Getting Started with VBA 9-3


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel

' No need to say Application.Workbooks(1)


' because Application is assumed
Workbooks(1).Activate
' or
Workbooks("Ch09.xls").Activate

• Use the ActiveWorkbook property of the Application object to return a


reference to the active workbook. The active workbook is the one
currently displayed in the Excel user interface.

ActiveWorkbook.Save

The ActiveWorkbook property is convenient, but be careful when you use it. If
more than one workbook is open, the active workbook may not be the one your
code is expecting. Use the Activate method to make an open workbook the
active workbook.

NOTE Excel’s collections are all one-based collections, rather than zero-
based. In other words, the first object in a collection has an index
of 1 rather than 0.

Some Common Methods and Properties


What kinds of things can you do with a Workbook object? Since it represents a
file that’s open in Excel, you can do quite a lot with it. Here are just a few
examples of some common properties and methods of a Workbook object.
You can open a workbook using the Open method of the Workbooks
collection, and assign it to an object variable:

Dim wkb As Workbook


Set wkb = Workbooks.Open("Ch09.xls")

You can create a new workbook with the Add method, and save it with the
SaveAs method:

Dim wkb As Workbook

Set wkb = Workbooks.Add


Set wkb = Workbooks.SaveAs("NewWorkbook.xls")

You can return the workbook’s name, its path, or both together:
9-4 Getting Started with VBA
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel: Microsoft Excel’s Top-Level Objects

With ActiveWorkbook
Debug.Print .Name
Debug.Print .Path
Debug.Print .FullName
End With

The Worksheet Object


Next in line is the Worksheet object. The Worksheet object represents a
worksheet in a workbook. As you might expect, it belongs to the Worksheets
collection of a Workbook object.
Referring to a worksheet is similar to referring to a workbook. You can:
• Use the Worksheets property with an index value or the worksheet’s name.

Debug.Print ActiveWorkbook.Worksheets(1).Name

• Use the ActiveSheet property to refer to the active worksheet.

ActiveWorkbook.ActiveSheet.Copy

The Copy method copies a worksheet to another workbook or to another


position in the current workbook.
You’ll use the Worksheet object often while you’re programming in Microsoft
Excel. Most of the time you use it in the course of referring to another object,
so let’s move on to the things that come beneath it in the object model.

Getting Started with VBA 9-5


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel

The Range Object


The Range object is probably the most important member of the Excel object
model, because it’s the object that lets you get to the values within the cells of
a worksheet. It refers to a block of cells on a worksheet. Ranges can be many
different shapes and sizes. A range can include just a single cell, or several
rows and columns.
The Range object belongs to a Worksheet object; there is no Ranges collection.
To refer to a Range object, you use the Range property of the Worksheet
object.

Referring to a Range
In order to refer to a range, you need to specify either a name or an address for
the range. The following are just a few of the ways to refer to a range.
• To refer to a single cell, you can use the Range("A1") format:

Debug.Print Worksheets(1).Range("A1").Value

• To refer to a multi-cell range, you can use a format like


Range("A1:B5"):

Worksheets(1).Range("A1:B5").Font.Bold = True

• To refer to a named range, you can just use the name of the range:

Debug.Print _
Worksheets(1).Range("ProductName").Rows.Count

TIP: To create a named range in Excel, select the cells you want to include in the
range, then type a name for the range into the Name Box in the upper left-
hand corner of Excel. You can also create a named range programmatically,
by using the Add method of the Names collection.

The CurrentRegion Property


The Range object has a CurrentRegion property, which returns another Range
object representing the contiguous data region around the active cell. The
range returned by the CurrentRegion property is bounded by an empty row and
an empty column. The CurrentRegion property is useful when you need to
work with a set of data on a worksheet.

9-6 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel: The Range Object
To use the CurrentRegion property, a cell within the data region must be the
active cell. You can make a cell active by using the Activate method on the
range that represents that cell.
The following example uses the CurrentRegion property to get information
See DataRegion in about the data region on a worksheet:
basObjectModel

Sub DataRegion()
Dim rng As Range

' Activate cell A1.


ActiveSheet.Range("A1").Activate
' Get the data region around cell A1.
Set rng = _
ActiveSheet.Range("A1").CurrentRegion
' Print information about the data region.
With rng
Debug.Print .Address
Debug.Print .Columns.Count
Debug.Print .Rows.Count
Debug.Print .End(xlDown).Address
End With
End Sub

The Cells Property


The Cells property allows you to refer to a specific cell within a range, using
row and column coordinates. It helps you to navigate through the range in
order to set or return cell values.
For example, suppose you want to get the value of the first cell in the
ProductName range. Rather than figuring out the address for that cell, you can
use the Cells property:

Dim rng As Range

Set rng = Worksheets(1).Range("ProductName")


Debug.Print rng.Cells(1, 1).Value

Getting Started with VBA 9-7


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel
The Cells property takes as arguments the row and column that you’re
interested in within the range. In other words, Cells(1, 1) returns the cell
that’s in the upper leftmost corner of the range. Cells(2, 1) returns the
cell that’s in the first column and second row of the range, and so on. The
Cells property evaluates rows and columns relative to the range, so it doesn’t
matter where the range is on the worksheet – Cells(1, 1) always returns
the first cell.

Look at The Cells property is especially useful when you want to loop through a group
PrintCellValues in of cells and set or return their value. You can use a nested For…Next loop to
basObjectModel get to all the cells in a range:

Sub PrintCellValues()
Dim wbk As Workbook
Dim rng As Range
Dim intRowCount As Integer
Dim intColCount As Integer
Dim intI As Integer
Dim intJ As Integer

' Assign workbook to object variable.


Set wbk = Workbooks("Ch09.xls")
' Assign range to object variable.
Set rng = Worksheets(1).Range("A2:B11")
' Return number of rows and columns
' in range.
intRowCount = rng.Rows.Count
intColCount = rng.Columns.Count

' Use nested loop to print values


' for each cell in range.
' Begin counting at 1.
For intI = 1 To intRowCount
For intJ = 1 To intColCount
Debug.Print rng.Cells(intI, intJ)
Next intJ
Next intI
End Sub

9-8 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel: The Word Object Model

The Word Object Model


The Word object model is just as sophisticated and extensive as the Microsoft
Excel object model, maybe even more so. Using the Word object model, you
can control just about any aspect of Word from VBA.
You can get underway programming with Word if you understand just a few of
the many objects in the object model. From there, you’ll quickly be able to
figure out what objects, properties, and methods you need to use for a given
task.
Since the Word object model is quite complicated, the relationships between
the different objects in the Word object model will be discussed as you go
along. To view the entire object model, see online Help. The object model is
also available on the Microsoft web site, at
http://www.microsoft.com/OfficeDev/Articles/OMG/default.htm.

Getting Started with VBA 9-9


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel

Word’s Top-Level Objects


The Application Object
The Word Application object represents Word itself. It contains all the other
objects and collections in the Word object model. In particular, the Application
object contains two objects that you’ll use frequently, the Document and
Selection objects (see Figure 2).

Figure 2. The Application object contains the Documents collection and the
Selection object.

When you’re referring to objects and collections beneath the Application


object, you don’t need to explicitly refer to the Application object. For
example, you can refer to the active document without the Application object.

ActiveDocument.Close

However, when you refer to properties or methods of the Application object


itself, you do need to refer to it explicitly:

Application.CapsLock = True

The Document Object


Just about everything you do in Word will involve the Document object,
which, naturally, represents an open document. Document objects belong to
the Documents collection of the Application object (see Figure 2). There are a
few ways to refer to a Document object:
• Refer to the document within the Documents collection, using either
the document’s name or its index.

9-10 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel: Word’s Top-Level Objects

Application.Documents("Ch09.doc").Save

• Use the ActiveDocument property. The active document is the one


that’s currently on top in the Word user interface.

ActiveDocument.CheckSpelling

Some Properties and Methods


How do you work with the Document object? You can perform all the tasks
that you’re accustomed to when you work with a Word document in the user
interface. Here are just a few examples to get you started.
For example, you can open a document, using the Open method:

Dim doc As Document


Set doc = Documents.Open("Ch09.doc")

You can create a new document, using the Add method:

Documents.Add

You can print a document in the background, using the PrintOut method:

ActiveDocument.PrintOut Background:=True

You can determine which template is attached to the document, or attach a


new template, using the AttachedTemplate property:

If ActiveDocument.AttachedTemplate = "NORMAL.DOT" Then


ActiveDocument.AttachedTemplate = "MyTemplate.DOT"
End If

You can check a document’s spelling, using the CheckSpelling method:

ActiveDocument.CheckSpelling

You can insert a hyperlink, using the Hyperlinks property:

Getting Started with VBA 9-11


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel

ActiveDocument.Hyperlinks.Add Selection.Range, _
"http://www.appdev.com"

TIP: If you want to explore Word’s objects, properties, and methods, head to the
Object Browser, and use F1 for context-sensitive Help!

The Selection Object


The Selection object represents the selection in a window. The selection may
be an area of the document, or, if nothing is selected, it may represent the
insertion point.
If you record a macro in Word that involves inserting text, the macro recorder
will often use the Selection object. However, when you’re writing your own
code, you’ll probably want to use the Range object to insert text at a particular
location, and use the Selection object only to work with selected text. The
Range object will be discussed in the next section.
You can do a lot with the Selection object. For example, you can copy the
selected text, move the insertion point to a new line, and paste in the text from
the Clipboard:

With Selection
.Copy
.MoveDown
.Paste
End With

9-12 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel: Manipulating Text with the Range Object

Manipulating Text with the Range


Object
What’s a Range?
The Word Range object gives you a way to work with text in a document. It’s
a designated area in your document; it can be a paragraph, several paragraphs,
a few words, a few characters, or even the entire document. Like a Microsoft
Excel range, it can be a variety of shapes and sizes.
A range has a starting position and an ending character position. At the most
granular level, you can define a range by its “coordinates” in the document,
which are a row and column value that identifies a particular character’s
position in the document.

Referring to a Range
How do you refer to a range? Just like in Microsoft Excel, there’s a Range
property that returns a reference to a Range object. You can then use the
properties and methods of the Range object.
For example, you can define a range in the active document that begins at
position 0 and ends at position 50.

Debug.Print ActiveDocument.Range(0, 50).Text

This code prints the text found in character positions 0 to 50 in the active
document. Notice the Text property, which returns the text that’s in the range.
That’s great, but you probably don’t want to sit in front of your Word
documents counting character positions. Fortunately, you don’t have to. Most
of the objects that represent a part of a document, like a table, a paragraph, or
even a selection, have an associated range that you can use.
For example, suppose you want to work with the text of the third paragraph in
the active document. You can use the Range property to get to this text:

Dim strText As String


strText = ActiveDocument.Paragraphs(3).Range.Text

As you can see, in this case you don’t need to know how many characters you
have; instead, you can just refer to a paragraph.

Getting Started with VBA 9-13


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel

Inserting Text
You can use the Range object to insert text into a document. It’s simple to add
text to a new document, as the following code shows:

Sub InsertText()
Dim doc As Document

Set doc = Documents.Add


doc.Activate
doc.Range.Text = "Add some text."
End Sub

In this case the Range object refers to the whole document. If this were an
existing document that had text in it already, all of that text would have been
deleted.
What if you want to insert text either before or after other text, without
deleting the original text? You can use the InsertBefore and InsertAfter
methods of a Range object. Let’s take a look at an example.

See frmInsertText Try running frmInsertText, in the sample file Ch09.doc. Type some text into
the text box, and click Insert Text to insert it into the document. Play with the
settings of the Start of Document and End of Document options to see how
Word inserts the text that you type. Figure 3 shows the form in action.

9-14 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel: Manipulating Text with the Range Object

Figure 3. Try using frmInsertText to insert text into the beginning and end of a
Word document.

How does this form work? Here’s the code in the Click event for the Insert
Text command button:

Getting Started with VBA 9-15


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel

Private Sub cmdInsert_Click()


Dim doc As Document
Dim intPosition As Integer

' Assign document to object variable.


Set doc = Documents("Ch09.doc")
' Activate document.
doc.Activate

' Check value of options.


If optStart = True Then
' Use InsertBefore with 0.
doc.Range(0).InsertBefore _
txtInsert.Text
Else

' Store last position in the document.


intPosition = doc.Range.End - 1
' Use InsertAfter with that position.
doc.Range(intPosition).InsertAfter txtInsert.Text
End If
End Sub

When this code runs, it first checks the values of the option buttons to
determine which option the user has chosen. If the user picked Start of
Document, the position to start inserting text in the document is 0. The
procedure calls the InsertBefore method to insert the text before the range
beginning with 0—in other words, at position 0.
If the user selected End of Document, then the code determines the current
ending position for the document, using the End property. You can’t insert text
after the end of the document, so you have to subtract 1 from the value of the
End property. The procedure then calls the InsertAfter method to insert the text
after the last character in the document.

9-16 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel: Manipulating Text with the Range Object

Summary
• Some of the key objects in the Microsoft Excel object model are:
Application, Workbook, Worksheet, Range, and Chart.
• The Range object is the object that you use to work with sets of cells
in Microsoft Excel. You can refer to ranges using an address such as
A1:B5, or by using a name if you’ve created a named range.
• The Cells property of the Range object enables you to set or retrieve a
value from a cell.
• The Word object model is complex, but once you understand a few
key objects, you can use it to automate many common tasks in Word.
• The Document object represents an open Word document.
• The Selection object represents the current selection in the document,
or the insertion point, if there is no selection.
• The Range object is useful for working with text. It identifies a
position in the document.

Getting Started with VBA 9-17


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel

Questions
1. Write a procedure that prints the name of the active worksheet to the
Immediate window.
2. Give an example of a range using an address.
3. What property can you use to refer to an individual cell within a range?
4. What property can you use to return a contiguous range of data, beginning
at the active cell?
5. What method can you use to insert text at the very beginning of a
document?

9-18 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Programming Word and Excel: Manipulating Text with the Range Object

Answers
1. Write a procedure that prints the name of the active worksheet to the
Immediate window.
Sub PrintWorksheetName()
Debug.Print ActiveWorkbook.ActiveSheet.Name
End Sub
2. Give an example of a range using an address.
A5:B10
3. What property can you use to refer to an individual cell within a range?
The Cells property
4. What property can you use to return a contiguous range of data, beginning
at the active cell?
The CurrentRegion property
5. What method can you use to insert text at the very beginning of a
document?
InsertBefore

Getting Started with VBA 9-19


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation

Creating
Integrated
Applications with
Automation
Objectives
• Learn to set a reference to another object model.
• See examples of communication between a VBA host and another
application.
• Use automation to design solutions to business problems.

Getting Started with VBA 10-1


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation

Expanding Your Horizons Using


Automation
What’s Automation? If you’ve used many of the VBA host applications
before, you probably appreciate their strongest individual features, and you
may wish that those features were available to you in every application. For
example, Excel’s calculation engine is superior for high-powered computation,
but it’s hard to create a nice-looking report in Excel. Access, on the other hand,
makes it easy to create a report, but it lacks some of the sophisticated
mathematical functions that Excel provides. With Automation, you can harness
one application’s power from the other through VBA.
Automation (until recently called OLE Automation and sometimes called
ActiveX Automation) is a powerful and easy-to-use technology that lets you
control one application or component’s objects from code in another
application. It’s actually a Windows technology that VBA host applications
can take advantage of.
Automation is always a one-way relationship between two applications. The
Automation client contains the code that drives the Automation process, while
the Automation server simply provides its objects for use.

Key Terms

Client The application that issues commands to instruct another


application to do something.

Server The application that responds to commands sent from the


controller.

10-2 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation: Getting to the Object Model

Getting to the Object Model


Before you can work with another application’s objects, you must indicate to
VBA that you want these objects to be available to you. When you’re working
with VBA in Excel, for example, VBA knows about Excel’s objects, but it
doesn’t automatically recognize Word or Access objects. You notify VBA that
you want to use an Automation server’s objects by setting a reference to that
application’s type library. This is the first step in getting ready to write
Automation code.
What’s a type library? You can think of a type library as a small database that
contains all the objects, properties, methods, and constants that another
application implements. A type library is actually contained in a file saved on
your computer. It usually has an extension of .tlb or .olb (for object library),
but sometimes the type library may be embedded in the application’s .exe file.
When you set a reference to a type library, you instruct VBA to recognize the
objects in that type library.

Key Term

Type library A file that contains information about an object model’s objects,
properties, methods, events, and constants.

Setting References
You set and remove references from a VBA project using the References
dialog box shown in Figure 1. To open this dialog box, select
Tools|References from the menu in the Visual Basic Editor.

Getting Started with VBA 10-3


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation

Figure 1. The References dialog box from a Word project.

The dialog box shows a list of all the type libraries VBA finds on your system.
If the check box next to a type library is selected, that means it is included in
your VBA project. When you first open the References dialog box, several
references will be selected depending on which application you’re working in.
The type libraries that are selected are the ones that VBA loads automatically
with your application.
To set a reference to an Automation server application, locate an entry for that
application in the list and select its check box. For example, to create a
reference to Excel’s type library for the examples later in this section, select
the check box next to “Microsoft Excel 9.0 Object Library.”
If the server application does not appear in the list it might be that VBA does
not recognize it as an Automation server. In this case you can click the Browse
button to display a dialog box for locating the application’s type library.

NOTE You can create references to type libraries, programs, ActiveX


controls, and other VBA projects. Normally you create a reference
to another VBA project when you want to use that project as a
library, calling functions it contains.

Viewing Other Applications’ Objects


Once you have created a reference to a server application’s type library, you
can use the Object Browser to view a list of the application’s objects,
properties, and methods from whatever application you’re working in.

10-4 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation: Getting to the Object Model

For example, to look at Excel’s objects from a Word project once you’ve set a
reference to the Excel type library, open the Object Browser by selecting the
Object Browser command from a module’s View menu, or press F2. Select the
application from the Object Browser dialog box’s list of Libraries and
Databases (see Figure 2).

Figure 2. The Object Browser showing Excel objects.

From the Object Browser, you can select any object, property, or method in the
Excel object model and get details on it, including online Help, just as you can
when you’re working in Excel.

TIP: The most difficult thing about using Automation is learning the object model
of the application you want to use. Often, though, you can get started if you
understand how just a few of the most common objects work. Use the Object
Browser together with online Help to explore the object models.

Creating an Instance of the Application


Once you’ve created a reference to an application’s type library, you can begin
writing VBA code to control it. The first thing to do is to create an instance of
the application and assign it to an object variable.
What’s an instance? It’s a session of an application. In order to use an
application’s objects, you need to load the application into memory, just as if
you were working with that application itself. The application doesn’t have to
be visible to the user, but it does need to be in memory.

Getting Started with VBA 10-5


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation

You create references to Automation objects the same way you do with built-
in objects, by using a Dim statement. The only difference is that you must use
the New keyword to create new instances of objects. You should also fully
qualify the object class by including the server name. In our example, the
server is Excel, but you can use a similar approach with any application.

Dim objApp As New Excel.Application

This line declares an object variable of type Excel.Application. The New


keyword instructs VBA to reserve space for a new instance of the Excel
Application object in memory.
The new instance of Excel isn’t actually created until you refer to the object
variable in a line of code. For example, if you include the following line, then
VBA creates a new instance of Excel and makes it visible when this line
executes:

objApp.Visible = True

You can also use the New keyword in a Set statement:

Dim objApp As Excel.Application

Set objApp = New Excel.Application

In this case, the new instance of Excel is created when VBA executes the line
containing the Set statement.

TIP: It’s better to use the New keyword with the Set statement, rather than the Dim
statement, even though it takes an additional line of code. When used in the
Set statement, you have greater control over when the Automation server is
instantiated.

NOTE Some applications such as Outlook only allow one running


instance at any given time. Therefore using the New keyword will
establish a reference to the existing instance and will not launch a
new copy of the server program.

10-6 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation: Getting to the Object Model

A Simple Automation Example


Once you’ve set a reference to an application’s type library and you’ve created
a new instance of the application, you’re ready to go. You can begin using the
application’s objects as though you were programming in that application
itself.
Let’s start out with a simple example. Take a look at the module
See module basAutomation in Ch10.doc to try it out, or import basAutomation into the
basAutomation application you’re working in.
Suppose that you’re working in Word, and you need to find the median of a
group of numbers. You could write a function in VBA in Word that would find
the middle value of a set of numbers. But Excel has a Median function that
does it for you. You can use Automation to call Excel’s Median function, as in
the following GetMedian function:

Function GetMedian(lngW As Long, lngX As Long, _


lngY As Long, lngZ As Long) As Long

Dim objApp As Excel.Application


Set objApp = New Excel.Application

GetMedian = _
objApp.WorksheetFunction.Median(lngW, _
lngX, lngY, lngZ)
objApp.Application.Quit
Set objApp = Nothing
End Function

What’s going on here? The GetMedian function definition takes four


parameters. If you were going to use this code in an application, you’d
probably want to rewrite it to accept more values, but we’ve kept it simple for
the purposes of this example.
The following line reserves space in memory for a new instance of the Excel
Application object:

Dim objApp As Excel.Application

The next line creates the new instance of Microsoft Excel and assigns it to the
object variable:

Getting Started with VBA 10-7


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation

Set objApp = New Excel.Application

Next there is a line that assigns an expression to the name of the function. This
expression does all the work: it calls the Median method with the specified
arguments. The expression is:

objApp.WorksheetFunction.Median(lngW, lngX, lngY, lngZ)

The following table breaks this expression down into its individual parts:

Part Function

objApp The variable that refers to the Microsoft Excel


Application object.
WorksheetFunction A property of the Microsoft Excel Application object
that specifies that you want to work with Microsoft
Excel’s function set.
Median A method that calls the Microsoft Excel Median
function.
lngW, lngX, lngY, lngZ Arguments passed to the Median method. Median
can take up to 30 arguments.

Finally, the last line is:

objApp.Application.Quit

Why do you need to include this line? When this code runs, Excel is taking up
space in memory, even though it’s not visible to the user. You free up that
space by quitting Excel.

Try It Out!
Try calling the previous function from the Immediate window. Set a
breakpoint on the line beginning with Set, and step through each line to see
what happens.

Are All Applications the Same?


Do all applications behave the same way when they act as Automation
servers? Of course not! For example, some applications don’t display their
main window when launched, as you saw with Excel. Some terminate
automatically when the object variable that refers to them goes out of scope,

10-8 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation: Getting to the Object Model

while others keep running. Table 1 lists some of the differences between
applications in the Microsoft Office suite.

Application Reaction To Automation Commands

Access Launches as an icon with a Visible property of False.


Changing the Visible property to True restores the main
window; changing it to False minimizes the window.
Additionally, destroying the object variable causes Access
to terminate if it was launched via Automation. You can
also use the Quit method.
Excel Launches as a hidden window with a Visible property of
False. Changing the Visible property to True “unhides” the
window. Destroying the object variable does not cause
Microsoft Excel to terminate. Use the Quit method instead.
PowerPoint Launches as a hidden window with a Visible property of
False. Changing the Visible property to True “unhides” the
window. Destroying the object variable does not cause
PowerPoint to terminate. Use the Quit method instead.
Outlook Launches as a hidden window. The Application object does
not have a Visible property. There is no way to make it
visible using the object model. You must use the Windows
API instead. Destroying the object variable does not cause
Outlook to terminate. Use the Quit method instead.
Word Launches as a hidden window with a Visible property of
False. Changing the Visible property to True “unhides” the
window. Destroying the object variable does not cause
Word to terminate. Use the Quit method instead.
Table 1. Different products act differently when they are automated from another
VBA host.

Getting Started with VBA 10-9


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation

Example: Building an Excel Chart


To demonstrate a complex example of Automation, let’s look at a procedure
that uses Automation to create a Excel chart from data in a Access database.
As before, we’ll explain how this procedure works step by step and provide the
complete listing at the end of this section.
The code in this example is intended to run from Access, so you’ll need to
have Access on your computer to try it. Keep in mind that you need to set a
reference to the Excel type library before you run the procedure.

Creating a New Workbook


We mentioned earlier in this chapter that to create a new instance in the Excel
See CreateXLChart Application you use the New keyword. After launching Excel and making it
in basAutomation visible, the procedure creates a new workbook using the Add method of the
in Ch10.mdb Workbooks collection. It stores a reference to this new workbook in a
Workbook object variable, objBook:

10-10 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation: Example: Building an Excel Chart

' Excel object variables


Dim objApp As Excel.Application
Dim objBook As Excel.Workbook
Dim objSheet As Excel.Worksheet
Dim objChart As Excel.Chart

' Access/Jet object variables


Dim db As Database
Dim rst As Recordset

' Normal variables


Dim cSheet As Integer
Dim lngRows As Long

' Create XL Application object


Set objApp = New Excel.Application

' Make it visible so we can watch it work


objApp.Visible = True

' Create a new workbook


Set objBook = objApp.Workbooks.Add

Once the new workbook has been created the procedure removes all but one of
the worksheets in the workbook. It then stores a reference to the first
worksheet in the workbook in another object variable, objSheet, and uses this
reference to change the Name property of the worksheet:

Getting Started with VBA 10-11


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation

' Get rid of all but one worksheet


objApp.DisplayAlerts = False
For cSheet = objBook.Worksheets.Count To 2 Step -1
objBook.Worksheets(cSheet).Delete
Next
objApp.DisplayAlerts = True

' Capture reference to first worksheet


Set objSheet = objBook.Worksheets(1)

' Change the worksheet name


objSheet.Name = "Average Order Volume"

Transferring Data
A summary query in the sample database, qryAvgQtyPerOrder, is used to
compute the average number of each item that appears on each order. Figure 3
shows the query open in datasheet view in Access.

Figure 3. The qryAvgQtyPerOrder query, open in datasheet view.

To transfer the results of this query to the Excel worksheet, the procedure calls
the CopyFromRecordset method of an Excel Range object. This method

10-12 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation: Example: Building an Excel Chart

accepts a Jet Recordset object and dumps the contents of it into the worksheet
starting at the address defined by the Range object:

' Use Excel's CopyFromRecordset method to dump


' all the data in the recordset into the worksheet
' starting at cell A2
objSheet.Range("A2").CopyFromRecordset rst

Creating the Chart


After all the data has been entered into the worksheet and formatted, the
procedure creates a chart on the worksheet. It accomplishes this in three steps:
1. It starts by creating a new Chart object using the Add method of the Charts
collection. It stores a reference to the new object in a Chart variable
(objChart).
2. It uses the ChartWizard method of the Chart object to set specific
properties of the chart.
3. It formats elements of the chart, such as the gap width and title font.
The code that performs these tasks follows:

Getting Started with VBA 10-13


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation

' Create the chart


Set objChart = objBook.Charts.Add()
With objChart
.ChartWizard Source:= _
objSheet.Cells(1, 1).CurrentRegion, _
Gallery:=xl3DBar, Format:=4, _
PlotBy:=xlColumns, CategoryLabels:=1, _
SeriesLabels:=1, HasLegend:=2, _
Title:=objSheet.Name, CategoryTitle:="", _
ValueTitle:="", ExtraTitle:=""

' Apply some formatting


.Name = objSheet.Name & " Chart"
With .ChartGroups(1)
.GapWidth = 20
.VaryByCategories = True
End With
With .ChartTitle
.Font.Size = 16
.Shadow = True
.Border.LineStyle = xlSolid
End With
End With

The ChartWizard method requires a Range object as the source for the chart.
CreateXLChart uses the CurrentRegion property to return all the nonblank
cells surrounding a given range.

TIP: For more information on the other objects, properties, and methods used in
the sample procedure, select them in the VBA module window and press F1.
You can also use the VBA Object Browser.

You can test this procedure by running CreateXLChart from the Debug
Run window (the Access equivalent of the Immediate window). After it finishes
basAutomation’s you should have an Excel chart that looks something like the one in Figure 4.
CreateXLChart
from the Debug
window

10-14 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation: Example: Building an Excel Chart

Figure 4. An Excel chart created using Automation.

Complete Procedure Listing


In case you don’t have access to a computer right now, the complete listing for
See CreateXLObject is included here so you can see the entire procedure.
basAutomation’s
CreateXLObject

Getting Started with VBA 10-15


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation

Sub CreateXLChart()
' Excel object variables
Dim objApp As Excel.Application
Dim objBook As Excel.Workbook
Dim objSheet As Excel.Worksheet
Dim objChart As Excel.Chart

' Access/Jet object variables


Dim db As Database
Dim rst As Recordset

' Normal variables


Dim cSheet As Integer
Dim lngRows As Long

' Create XL Application object


Set objApp = New Excel.Application

' Make it visible so we can watch it work


objApp.Visible = True

' Create a new workbook


Set objBook = objApp.Workbooks.Add

' Get rid of all but one worksheet


objApp.DisplayAlerts = False
For cSheet = objBook.Worksheets.Count To 2 Step -1
objBook.Worksheets(cSheet).Delete
Next
objApp.DisplayAlerts = True

' Capture reference to first worksheet


Set objSheet = objBook.Worksheets(1)

' Change the worksheet name


objSheet.Name = "Average Order Volume"

' Create recordset

10-16 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation: Example: Building an Excel Chart

Set db = CurrentDb()
Set rst = db.OpenRecordset( _
"qryAvgQtyPerOrder", dbOpenSnapshot)

With objSheet
' Copy field names to Excel
.Cells(1, 1).Formula = rst.Fields(0).Name
.Cells(1, 2).Formula = rst.Fields(1).Name

' Bold the column headings


.Cells(1, 1).Font.Bold = True
.Cells(1, 2).Font.Bold = True
End With

' Use Excel's CopyFromRecordset method to dump


' all the data in the recordset to the worksheet
' starting at cell A2
objSheet.Range("A2").CopyFromRecordset rst

' Format the data


With objSheet.Columns
With .Item(2)
.NumberFormat = "0.00"
.AutoFit
End With
.Item(1).AutoFit
End With

' Create the chart


Set objChart = objBook.Charts.Add()
With objChart
.ChartWizard Source:= _
objSheet.Cells(1, 1).CurrentRegion, _
Gallery:=xl3DBar, Format:=4, _
PlotBy:=xlColumns, CategoryLabels:=1, _
SeriesLabels:=1, HasLegend:=2, _
Title:=objSheet.Name, CategoryTitle:="", _

Getting Started with VBA 10-17


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation

ValueTitle:="", ExtraTitle:=""

' Apply some formatting


.Name = objSheet.Name & " Chart"
With .ChartGroups(1)
.GapWidth = 20
.VaryByCategories = True
End With
With .ChartTitle
.Font.Size = 16
.Shadow = True
.Border.LineStyle = xlSolid
End With
End With

' Clean up
rst.Close
Set objChart = Nothing
Set objRange = Nothing
Set objSheet = Nothing
Set objBook = Nothing
Set objApp = Nothing
End Sub

10-18 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation: Example: Building an Excel Chart

Summary
• Using Automation, you can work with one application’s objects from
another application. Automation enables you to create integrated
solutions using components of two or more applications.
• The application that supplies objects to another application is called
the Automation server, and the application that uses the objects is
called the Automation client.
• Type libraries provide information about an application’s objects to
VBA. You create a reference to a type library using the References
dialog box.
• You can use the Object Browser to view an application’s objects,
properties, methods, and constants.
• The key steps to writing Automation code include: setting a reference
to the Automation server’s type library; declaring an object variable to
represent the Automation server; creating a new instance of the
Automation server; working with the Automation server’s objects; and
closing the Automation server and freeing any memory it used.

Getting Started with VBA 10-19


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation

Questions
1. Which application provides its objects to a second application in an
Automation operation?
2. What should you always do before beginning an Automation operation?
3. What keyword do you use to create a new instance of an Automation
server?
4. What object do you use to create a new instance of Microsoft Excel?

10-20 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Integrated Applications with Automation: Example: Building an Excel Chart

Answers
1. Which application provides its objects to a second application in an
Automation operation?
The Automation server
2. What should you always do before beginning an Automation operation?
Set a reference to the Automation server’s type library
3. What keyword do you use to create a new instance of an Automation
server?
The New keyword
4. What object do you use to create a new instance of Microsoft Excel?
The Application object

Getting Started with VBA 10-21


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Appendix A: The Reddick VBA Naming Conventions

Appendix A: The
Reddick VBA
Naming Conventions
Version 4.0
Greg Reddick
Copyright  1995-1997 Greg Reddick. All Rights Reserved.
Some of the naming tags, prefixes, and qualifiers in this document are derived from the
Leszynski/Reddick naming conventions, Copyright  1994 Stan Leszynski and Greg
Reddick.
The purpose of the Reddick VBA (RVBA) naming conventions is to provide a guideline
for naming objects in the Microsoft Visual Basic for Applications (VBA) language.
Having conventions is valuable in any programming project. When you use them, the
name of the object conveys information about the meaning of the object. These
conventions provide a way of standardizing what that meaning is across the programming
industry.
VBA is implemented to interact with a host application—for example, Microsoft Access,
Visual Basic, Microsoft Excel, and Microsoft Project. The RVBA conventions cover all
implementations of the VBA language, regardless of the host application. Note that some
of the tags described in this appendix may not necessarily have an implementation within
some particular host program. The word object, in the context of this document, refers to

Getting Started with VBA A-1


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Appendix A: The Reddick VBA Naming Conventions

simple variables, as well as to objects presented in the interface of the VBA host
program.
While I’m the editor of these conventions and in 1992 proposed the original conventions
for Microsoft Access, they are the work of many people, including Charles Simonyi, who
invented the Hungarian conventions on which these are based; Stan Leszynski, who co-
authored several versions of the conventions; and Paul Litwin, for his contributions and
for getting the conventions in front of the public. Many others, too numerous to mention,
have also contributed to the development of these conventions.
These conventions are intended as a guideline. If you disagree with a particular part,
simply replace that part with what you think works better. However, keep in mind who
will see those changes and place a comment in the header of a module indicating what
changes have been made. The conventions are presented without rationalizations for how
they were derived; you may assume that there are good reasons for the choices that have
been made. Send me any questions or comments about the conventions. (See the
addresses at the end of this appendix.) Suggestions for future versions are welcome.

A-2 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Index

Changes to the Conventions


These conventions first appeared in print in the charter issue of Smart Access in February
of 1993. A significantly revised version appeared in the August 1993 issue.
Some of the tags in the version of the conventions presented here have changed from
previous versions. Consider all previous tags to be grandfathered into the conventions—
you don’t need to go back and make changes. For new development work, we leave it up
to you to decide whether to use the older tags or the ones suggested here.

Getting Started with VBA A-3


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Appendix A: The Reddick VBA Naming Conventions

An Introduction to Hungarian
The RVBA conventions are based on the Hungarian style, named for the native country
of Charles Simonyi, the inventor of this style of naming objects. The objective of
Hungarian is to convey information about the object concisely and efficiently. Hungarian
takes some getting used to, but once adopted, it quickly becomes second nature. The
format of a Hungarian object name is as follows:
[prefixes]tag[BaseName[Suffixes]]

The square brackets indicate optional parts of the object name.


These components have the following meanings:
• Prefixes: Modify the tag to indicate additional information. Prefixes are in all
lowercase letters. They are usually picked from a standardized list of prefixes,
given later in this appendix.
• Tag: Short set of characters, usually mnemonic, that indicates the type of the
object. The tag is in all lowercase letters. It’s usually selected from a
standardized list of tags, given later in this appendix.
• BaseName: One or more words that indicate what the object represents. The first
letter of each word in the base name is capitalized.
• Suffixes: Additional information about the meaning of the base name. The first
letter of each word in the suffix is capitalized. They are usually picked from a
standardized list of suffixes, given later in this appendix.
Notice that the only required part of the object name is the tag. This may seem
counterintuitive; you may feel that the base name is the most important part of the object
name. However, consider a generic procedure that operates on any form. The fact that the
routine operates on a form is the important thing, not what that form represents. Because
the routine may operate on forms of many different types, you don’t necessarily need a
base name. However, if you have more than one object of a type referenced in the
routine, you must have a base name on all but one of the object names to differentiate
them. Also, unless the routine is generic, the base name conveys information about the
variable. In most cases a variable should include a base name.

A-4 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Index

Tags
You use tags to indicate the data type of an object, and you construct them using the
techniques described in the following sections.

Variable Tags
Use the tags listed in Table 1 for VBA data types. You can also use a specific tag instead
of “obj” for any data type defined by the host application or one of its objects. (See the
section “Host Application and Component Extensions to the Conventions” later in this
appendix.)

Tag Object Type


byt Byte
f Boolean
int Integer
lng Long
sng Single
dbl Double
cur Currency
dtm* Date
obj Object
str String
stf String (fixed length)
var Variant
Table 1. Tags for VBA Variables. *Prior versions of these naming conventions
used the “dat” tag.

Here are several examples:


lngCount
intValue
strInput

You should explicitly declare all variables, each on a line by itself. Don’t use the old type
declaration characters, such as %, &, and $. They are extraneous if you use the naming
conventions, and there are no characters for some of the data types, such as Boolean. You
should explicitly declare all variables of type Variant, the default, as type Variant. For
example:
Dim intTotal As Integer
Dim varField As Variant
Dim strName As String

Getting Started with VBA A-5


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Appendix A: The Reddick VBA Naming Conventions

Constant Tags
You should indicate generic constants by using the tag “con.” If you need to differentiate
one class of constants from another, you can invent a class name, such as adh (for Access
Developer’s Handbook), and append the letter c to the class—for example, adhcPi. You
may want to do this if you have some specific component that has global constants and
you want to ensure that they don’t conflict with other constants. For example:
conPi
glrcError205

Tags for User-Defined Types and Classes


User-defined types and user-created class objects are treated the same because user-
defined types are really a kind of simple user-defined class. These objects have two
components: the class name that defines the structure of the class and a tag that is used
for instances of that class. Choose an appropriate name for the class. For example, if you
had a user-defined class that described a glyph bitmap created at run time on a form, the
class name would be glyph. The tag would be an abbreviation of glyph—perhaps gph. If
you had another class that was a collection of these objects, it would use glyphs and gphs,
respectively. You can treat a form as a user-defined class with a user interface. For
example:
gphGlyph
nclName

Collection Tags
You treat a collection object with a special tag. You construct the tag using the data type
of the collection followed by the letter “s.” For example, if you had a collection of Longs,
the tag would be lngs. If it were a collection of user-defined types with the tag gph, the
collection would be gphs. Although in theory, a collection can hold objects of different
data types, in practice, each of the data types in the collection is the same. If you do want
to use different data types in a collection, use the tag objs. For example:
intsEntries
erhsHandler
bscsBaseClass

A-6 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Index

Constructing Procedures
VBA procedures require you to name various objects: procedure names, labels, and
parameters. These objects are described in the following sections.

Constructing Procedure Names


VBA names event procedures, and you can’t change them. You should use the
capitalization defined by the system. For user-defined procedure names, capitalize the
first letter of each word in the name. For example:
cmdOK_Click
GetTitleBarString
PerformInitialization

Procedures should always have a scope keyword, Public or Private, when they are
declared. For example:
Public Function GetTitleBarString() As String
Private Sub PerformInitialization

Naming Parameters
You should prefix all parameters in a procedure call with ByVal or ByRef, even though
ByRef is optional and redundant. Procedure arguments are named the same as simple
variables of the same type, except that arguments passed by reference use the prefix “r.”
For example:
Sub TestValue(ByVal intInput As Integer, _
ByRef rlngOutput As Long)
Function GetReturnValue(ByVal strKey As String, _
ByRef rgph As Glyph) As Boolean

Getting Started with VBA A-7


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Appendix A: The Reddick VBA Naming Conventions

Prefixes
Prefixes modify an object tag to indicate more information about an object.

Arrays of Objects Prefix


Arrays of an object type use the prefix “a.” For example:
aintFontSizes
astrNames

Index Prefix
You indicate an index into an array with the prefix “i,” regardless of the data type of the
index. You may also use the index prefix to index into other enumerated objects, such as
a collection of user-defined classes. For example:
iaintFontSizes
iastrNames
igphsGlyphCollection

Prefixes for Scope and Lifetime


Three levels of scope exist for each variable in VBA: Public, Private, and Local. A
variable also has a lifetime of the current procedure or the length of the program. You
may optionally use the prefixes in Table 2 to indicate scope and lifetime.

Prefix Object Type


(none) Local variable, procedure-level lifetime
s Local variable, program-level lifetime (static variable)
m Private (module) variable, program-level lifetime
g Public (global) variable, program-level lifetime
Table 2. Prefixes for Scope and Lifetime.

You also use the “m” and “g” constants with other objects, such as constants, to indicate
their scope. For example:
intLocalVariable
mintPrivateVariable
gintPublicVariable
mconPi

A-8 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Index

Other Prefixes
Table 3 lists and describes some other prefixes.

Prefix Object Type


c Count of some object type
h Handle to a Windows object
r Parameter passed by reference
Table 3. Other Commonly Used Prefixes.

Here are some examples:


cstrArray
hwndForm

Getting Started with VBA A-9


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Appendix A: The Reddick VBA Naming Conventions

Suffixes
Suffixes modify the base name of an object, indicating additional information about a
variable. You’ll likely create your own suffixes that are specific to your development
work. Table 4 lists some generic VBA suffixes.

Suffix Object Type


Min The absolute first element in an array or other kind of
list.
First The first element to be used in an array or list during
the current operation.
Last The last element to be used in an array or list during
the current operation.
Lim The upper limit of elements to be used in an array or
list. Lim isn’t a valid index. Generally, Lim equals
Last + 1.
Max The absolutely last element in an array or other kind
of list.
Cnt Used with database elements to indicate that the item
is a counter. Counter fields are incremented by the
system and are numbers of either type Long or type
ReplicationId.
Table 4. Commonly Used Suffixes

Here are some examples:


iastrNamesMin
iastrNamesMax
iaintFontSizesFirst
igphsGlyphCollectionLast
lngCustomerIdCnt
varOrderIdCnt

A-10 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Index

Host Application and Component


Extensions to the Conventions
Each host application for VBA, as well as each component that can be installed, has a set
of objects it can use. This section defines tags for the objects in the various host
applications and components. Future versions of the conventions will include tags for
other VBA hosts and components.

Microsoft Access 97, Version 8.0 Objects


Table 5 lists Microsoft Access object variable tags. Besides being used in code to refer to
these object types, these same tags are used to name these kinds of objects in the form
and report designers.

Getting Started with VBA A-11


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Appendix A: The Reddick VBA Naming Conventions

Tag Object Type


app Application
bof BoundObjectFrame
chk CheckBox
cbo ComboBox
cmd CommandButton
ctl Control
ctls Controls
ocx CustomControl
dcm DoCmd
frm Form
frms Forms
grl GroupLevel
hlk Hyperlink
img Image
lbl Label
lin Line
lst ListBox
bas (or mdl) Module
bass (or mdls) Modules
ole ObjectFrame
opt OptionButton
fra OptionGroup (frame)
pge Page of Tab Control
pges Pages (of Tab Control)
brk PageBreak
pal PaletteButton
prps Properties
shp Rectangle (shape)
ref Reference
refs References
rpt Report
rpts Reports
scr Screen
sec Section
sfr SubForm
srp SubReport
tab Tab Control
txt TextBox
tgl ToggleButton
Table 5. Microsoft Access Object Variable Tags.

A-12 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Index

Here are some examples:


txtName
lblInput

For OLE/ActiveX custom controls, you can use the tag OCX, as specified in Table 5, or
more specific object tags if they have been specified for the control.

DAO 3.5 Objects


DAO is the programmatic interface to the Jet database engine shared by Microsoft
Access, Visual Basic, and Visual C++. The tags for DAO 3.5 objects are shown in Table
6.

Getting Started with VBA A-13


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Appendix A: The Reddick VBA Naming Conventions

Tag Object Type


cnx Connection
cnxs Connections
cnt Container
cnts Containers
db Database
dbs Databases
dbe DBEngine
doc Document
docs Documents
err Error
errs Errors
fld Field
flds Fields
grp Group
grps Groups
idx Index
idxs Indexes
prm Parameter
prms Parameters
prp Property
prps Properties
qry (or qdf) QueryDef
qrys (or qdfs) QueryDefs
rst Recordset
rsts Recordsets
rel Relation
rels Relations
tbl (or tdf) TableDef
tbls (or tdfs) TableDefs
usr User
usrs Users
wrk Workspace
wrks Workspaces
Table 6. DAO 3.5 Object Tags.

Here are some examples:


rstCustomers
idxPrimaryKey

Table 7 lists the tags used to identify types of objects in a database.


A-14 Getting Started with VBA
Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Index

Tag Object Type


cls Class Module
tbl Table
qry Query
frm Form
rpt Report
mcr Macro
bas (or mdl) Module
Table 7. Microsoft Access Database Window Object Tags.
If you want, you can use more exact tags or suffixes to identify the purpose and type of a
database object. If you use the suffix, use the tag from Table 7 to indicate the type. Use
either the tag or the suffix found along with the more general tag, but not both. The tags
and suffixes are shown in Table 8.
TAG SUFFIX OBJECT TYPE
tlkp Lookup Table (lookup)
qsel (none) Query (select)
qapp Append Query (append)
qxtb XTab Query (crosstab)
qddl DDL Query (DDL)
qdel Delete Query (delete)
qflt Filter Query (filter)
qlkp Lookup Query (lookup)
qmak MakeTable Query (make table)
qspt PassThru Query (SQL pass-
through)
qtot Totals Query (totals)
quni Union Query (union)
qupd Update Query (update)
fdlg Dlg Form (dialog)
fmnu Mnu Form (menu)
fmsg Msg Form (message)
fsfr SubForm Form (subform)
rsrp SubReport Form (subreport)
mmnu Mnu Macro (menu)
Table 8. Specific Object Tags and Suffixes for Microsoft Access Database
Window Objects.

Here are some examples:


tblValidNamesLookup
tlkpValidNames
fmsgError

Getting Started with VBA A-15


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Appendix A: The Reddick VBA Naming Conventions

mmnuFileMnu

When naming objects in a database, don’t use spaces. Instead, capitalize the first letter of
each word. For example, instead of Quarterly Sales Values Table, use
tblQuarterlySalesValues.
There is strong debate over whether fields in a table should have tags. Whether you use
them is up to you. However, if you do use them, use the tags from Table 9.

Tag Object Type


bin Binary
byt Byte
guid Globally unique identifier (GUID) used for replication
AutoIncrement fields
lng Autoincrementing (either sequential or random) Long (used with
the suffix Cnt)
cur Currency
dat Date/time
dbl Double
int Integer
lng Long
mem Memo
ole OLE
sng Single
str Text
f Yes/No
Table 9. Field Tags (If You Decide to Use Them).

Microsoft Office 8.0 Objects


Table 10 lists the tags for Microsoft Office 8.0 objects.

A-16 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Index

Tag Object Type


ast Assistant
bln Balloon
chk BalloonCheckbox
chks BaloonCheckboxes
lbl BalloonLabel
lbls BalloonLabels
cbr CommandBar
cbrs CommandBars
cmd CommandBarButton
cbo CommandBarComboBox
ctl CommandBarControl
ctls CommandBarControls
cbp CommandBarPopup
dcp DocumentProperty
dcps DocumentProperties
sch FileSearch
ffl FoundFiles
prt PropertyTest
prts PropertyTests
Table 10. Microsoft Office 8.0 Object Tags.

Microsoft Common Control Objects


Windows 95 and Windows NT have a set of common controls that are accessible from
VBA. Table 12 lists the tags for objects created using these controls.

Getting Started with VBA A-17


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Appendix A: The Reddick VBA Naming Conventions

Tag Object Type


ani Animation
btn Button (Toolbar)
btns Buttons (Toolbar)
hdr ColumnHeader (ListView)
hdrs ColumnHeaders (ListView)
ctls Controls
iml ImageList (ImageList)
lim ListImage
lims ListImages
lit ListItem (ListView)
lits ListItems (ListView)
lvw ListView (ListView)
nod Node (TreeView)
nods Nodes (TreeView)
pnl Panel (Status Bar)
pnls Panels (Status Bar)
prb ProgressBar (Progress Bar)
sld Slider (Slider)
sbr StatusBar (Status Bar)
tab Tab (Tab Strip)
tabs Tabs (Tab Strip)
tbs TabStrip (Tab Strip)
tbr Toolbar (Toolbar)
tvw TreeView (TreeView)
udn UpDown (UpDown)

Table 12. Microsoft Common Control Object tags.

Other Custom Controls and Objects


Finally, Table 13 lists the tags for other commonly-used custom controls and objects.

A-18 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Index

Tag Object Type


cdl CommonDialog (Common Dialog)
dbc DBCombo (Data Bound Combo Box)
dbg DBGrid (Data Bound Grid)
dls DBList (Data Bound List Box)
gau Gauge (Gauge)
gph Graph (Graph)
grd Grid (Grid)
msg MAPIMessages (Messaging API Message Control)
ses MAPISession (Messaging API Session Control)
msk MaskEdBox (Masked Edit Textbox)
key MhState (Key State)
mmc MMControl (Multimedia Control)
com MSComm (Communication Port)
out Outline (Outline Control)
pcl PictureClip (Picture Clip Control)
rtf RichTextBox (Rich Textbox)
spn SpinButton (Spin Button)
Table 13. Tags for commonly-used custom controls.

Getting Started with VBA A-19


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Appendix A: The Reddick VBA Naming Conventions

Summary
Using a naming convention requires a considerable initial effort on your part. It also
requires that you conform to rules specified by other parties, which is difficult for many
programmers. The payoff comes when either you or another programmer has to revisit
your code at a later time. Using the conventions makes your code more readable and
maintainable.

NOTE A later version of these conventions that includes updated tags for Visual
Basic 5.0 will made be available electronically. This update should be
available electronically at several web sites, including the MCW
Technologies site at http://www.mcwtech.com.

Greg Reddick is the President of Gregory Reddick & Associates, a consulting company
specializing in software development in Microsoft Access, VB, and C/C++. He worked
for four years on the Access development team at Microsoft. He was a coauthor of the
Microsoft Access 95 Developer’s Handbook, published by Sybex. He can be reached at
71501,2564 on CompuServe or 71501.2564@compuserve.com from the Internet.

A-20 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Index

Index

selecting............................................................... 3-8
Control Events ........................................................ 6-11
A controls
Access .......................................................................1-5 check box .......................................................... 3-23
Activate event ...........................................................6-3 combo box......................................................... 3-23
Activate method........................................................9-4 command button................................................ 3-23
ActiveSheet property ................................................9-5 defined................................................................. 3-5
ActiveWorkbook property ........................................9-4 frame ...............................See controls; option group
ActiveX controls .......................................................3-2 image control..................................................... 3-24
Add method label................................................................... 3-23
Workbooks collection..........................................9-4 list box............................................................... 3-23
Application ...............................................................8-3 moving................................................................. 3-8
creating an instance of in Automation ...............10-5 option button ..................................................... 3-23
Application Object option group ...................................................... 3-23
Excel....................................................................9-3 resizing ................................................................ 3-8
Word..................................................................9-10 scroll bar, vertical .............................................. 3-23
Argument ................................................................1-14 selection tool ..................................................... 3-23
Automation text box.............................................................. 3-23
creating integrated applications .........................10-2 Controls
definition ...........................................................10-2 Built-In .............................................................. 3-23
varying application behavior .............................10-8 data entry........................................................... 3-24
deleting................................................................ 3-9
formatting.......................................................... 3-10
B manipulating on a User Form .............................. 3-8
working with multiple ......................................... 3-9
Bookmark Conversion functions.............................................. 4-14
setting ..................................................................4-6 Currency data type.................................................... 2-4
Boolean data type......................................................2-4 CurrentRegion Property............................................ 9-6
breakpoint ...............................................................1-19
build button.............................................................3-12
buttons D
custom .................................................................1-7
Byte data type ...........................................................2-4 Date and time functions .......................................... 4-13
Date data type ........................................................... 2-4
DblClick event........................................................ 6-14
C Decimal data type ..................................................... 2-4
Design Mode ............................................................ 3-3
Call keyword...........................................................4-10 Dialog Box
Caption Property.....................................................3-13 designing ........................................................... 3-16
Cells Property ...........................................................9-7 dialog boxes
Change ....................................................................6-12 custom ................................................................. 1-6
Change Event..........................................................3-21 Dim statement........................................................... 2-5
Click event ..............................................................6-14 Do...Loops ................................................................ 5-9
Click Event .............................................................3-20 Document Object
Code Word.................................................................. 9-10
commenting .........................................................4-6 Double data type....................................................... 2-4
formatting ............................................................4-5 drag and drop code ................................................. 1-20
Collection..................................................................8-3
Collections
referring to within objects....................................8-9 E
Combo box..............................................................3-25
CommandButton Control..........................................3-5 Empty keyword......................................................... 2-9
comments................................................................1-18 Enabled property....................................................... 7-7
Constants Enter event................................................................ 6-3
creating your own ..............................................2-17 EnterKeyBehavior property...................................... 7-9
defined ...............................................................2-14 Event
Control definition ........................................................... 1-11

Getting Started with VBA Index-1


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Index

Worksheet Change.............................................6-18 line continuation character...................................... 1-19


event procedure.......................................................1-11 List box................................................................... 3-25
Event procedure List Constants ........................................................... 4-7
anatomy of...........................................................6-3 List Properties/Methods............................................ 4-7
Event Procedure Locked property........................................................ 7-7
creating ..............................................................3-19 Long data type .......................................................... 2-4
important considerations....................................3-18 Looping Structures ................................................... 5-9
Event Procedure Arguments .....................................6-9 Loops
Event Procedures .............................................3-18, 6-2 choosing between .............................................. 5-12
Events .................................................... 1-11, 3-18, 6-2 exiting prematurely............................................ 5-10
host-specific.......................................................6-16 For...Next .......................................................... 5-13
Word document .................................................6-16
Excel Object Model ..................................................9-2
Explicit Declaration ................................................2-11 M
MaxLength property ................................................. 7-9
F Me3-21
Median function...................................................... 10-7
For Each...Next .......................................................8-16 menu
form properties..........................................................7-4 custom ................................................................. 1-7
function...................................................................1-13 method
returning a value from .......................................1-18 definition ........................................................... 8-11
functions Method...................................................................... 8-2
CreateXLChart ................................................10-15 Methods
taking action ...................................................... 8-11
Microsoft Access
G as an Automation server .................................... 10-9
GoTo .........................................................................5-8 Microsoft Excel ...................................................... 10-9
Microsoft Outlook .................................................. 10-9
Microsoft PowerPoint............................................. 10-9
I Microsoft Word ...................................................... 10-9
Module.................................................................... 1-10
If...Then...[Else...]End If construct............................5-2 mouse cursor, changing ............................................ 7-5
If...Then...Else[If]...End If construct .........................5-3 Mouse Events ......................................................... 6-13
Image ......................................................................3-26 MouseDown event.................................................. 6-14
Immediate Window........................................1-12, 4-10 MouseUp event....................................................... 6-14
calling functions ................................................4-12 MsgBox .................................................................. 2-14
calling subroutines.............................................4-10 MultiLine property ................................................... 7-9
programmatically writing to ..............................4-10 MultiPage ............................................................... 3-27
Implicit Declaration ................................................2-11
Implicit vs. Explicit Declarations............................2-11
Initialize event ..........................................................6-3 N
using ....................................................................6-7
instance Name Property........................................................ 3-13
definition ...........................................................10-5 Named Arguments .................................................. 4-19
Instance New keyword.......................................................... 10-6
creating in Automation ......................................10-5 Null keyword ............................................................ 2-9
Integer data type........................................................2-4
O
K object
Keyboard Events.....................................................6-11 definition ............................................................. 8-2
KeyDown................................................................6-11 Object Browser ................................................4-15, 8-5
KeyPress .................................................................6-11 using with Automation servers .......................... 10-4
keystrokes object library........................................................... 10-3
comparing KeyPress and KeyDown ..................6-12 object model ............................................................. 8-2
KeyUp.....................................................................6-12 Excel.................................................................... 8-3
getting to in Automation.................................... 10-3
MSForms............................................................. 8-4
L Object Model
Excel.................................................................... 9-2
Label Control ............................................................3-7 Object Variables ..................................................... 8-13
Layout event .............................................................6-3 Objects
licensing VBA ..........................................................1-5

Index-2 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Index

on Forms............................................................8-19 Set statement


referring to by name ............................................8-8 in Automation.................................................... 10-6
referring to in Collections....................................8-8 setting control properties .......................................... 7-7
referring to position .............................................8-8 Single data type ........................................................ 2-4
the Nothing keyword .........................................8-15 SpinButton.............................................................. 3-26
Office ........................................................................1-4 Static statement......................................................... 2-5
Open method String data type......................................................... 2-4
Workbooks collection..........................................9-4 String functions....................................................... 4-13
Operators Sub.......................................................................... 1-13
”&” ....................................................................1-18 Sub procedure
Option Explicit........................................................2-11 creating.............................................................. 1-22
Setting by default...............................................2-11 Subroutine............................................................... 1-13
Optional arguments.................................................4-19
T
P Text Box
Parameter ................................................................1-14 properties............................................................. 7-9
Parameter Info ..........................................................4-8 TextBox Control ....................................................... 3-6
Private keyword ......................................................1-17 toolbars
Private statement.......................................................2-5 custom ................................................................. 1-7
Procedure ................................................................1-10 type library
creating ................................................................4-2 references .......................................................... 10-3
Procedures Type library ............................................................ 10-3
viewing multiple..................................................4-5
Project.....................................................................1-10
properties U
retrieving values ..................................................7-2 UCase ..................................................................... 1-18
setting values at runtime ......................................7-2 Unititialized object variables .................................. 8-15
Properties User Form
default................................................................8-11 adding controls .................................................... 3-5
in code ...............................................................3-22 creating a new...................................................... 3-2
setting ................................................................3-11 User Form Events ..................................................... 6-7
setting on objects ...............................................8-10 User Forms
Properties Window .................................................3-11 definition ............................................................. 3-2
property working with ....................................................... 3-2
definition .............................................................8-2
Public keyword .......................................................1-17
Public statement........................................................2-5 V
Variable
Q definition ............................................................. 2-2
variables
QueryClose Event .....................................................6-8 declaring.............................................................. 2-5
initializing ........................................................... 2-8
R Variables
assigning meaningful names................................ 2-3
Range data types............................................................. 2-4
referring to...........................................................9-6 naming conventions............................................. 2-8
Range Object ............................................................9-6 variant type.......................................................... 2-9
Word..................................................................9-13 Variant data type....................................................... 2-9
reference Variant data type....................................................... 2-4
setting ................................................................10-3 VBA
Run Mode .................................................................3-3 Definition ............................................................ 1-2
VBA built-in functions ........................................... 4-13
Visible property ........................................................ 7-7
S
ScrollBar.................................................................3-26
ScrollBars property ...................................................7-9
W
Select Case construct ................................................5-5 With...End With...................................................... 8-19
Selection Object Word Completion ..................................................... 4-8
Word..................................................................9-12 Word Object Model .................................................. 9-9
SelectionMargin property .........................................7-9 Workbook object ...................................................... 8-3

Getting Started with VBA Index-3


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Index

Workbook Object......................................................9-3 WorksheetFunction property .................................. 10-8


Worksheet Object .....................................................9-5

Index-4 Getting Started with VBA


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

Potrebbero piacerti anche