Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Getting Started
with VBA
www.appdev.com
7610 Executive Drive • Eden Prairie, MN 55344 • 800-578-2062
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
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
Introduction
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
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.
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.
The Visual
Basic Editor
Figure 1. Microsoft Excel and the Visual Basic Editor appear in separate
application windows.
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.
NOTE You can create custom toolbars and menus in the Office products,
but not all VBA host products support them.
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.
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.
Key Terms
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.
Key Term
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
they’re familiar with, like clicking a button or dropping down a combo box, to
run your code.
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.
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
e
Valu
Input
Figure 6. Function DoSomething() accepts two values in, and returns a single
value.
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
Figure 7. Call a function in the Immediate Window, and VBA responds with the
results.
Key Terms
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.
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).
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
End Function
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.
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).
BuildCSZ = UCase(City & " " & State & " " & Zip)
End Function
HOUSTON TX 77024
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.
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:
Debug.Print City
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:
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.
DisplayDate
• 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
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.
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?
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
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.)
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
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.
Try running the function from the Immediate window. Yes, it works, but it has
some serious flaws:
• 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”?
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.
• 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.
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).
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.
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:
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:
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.
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.
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.
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.
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.
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:
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:
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.
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):
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.
vbOK OK
vbCancel Cancel
vbAbort Abort
vbRetry Retry
vbIgnore Ignore
vbYes Yes
vbNo No
Table 7. Constants representing the possible return values from MsgBox.
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:
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.
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.
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.”
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”
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.
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.
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.
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.
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.
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.
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.
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).
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).
Deleting Controls
To delete a control, select the control and press DELETE.
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.
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
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.
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.
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.
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.
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.
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.
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.
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
attached code to the form’s and controls’ events. Events will be discussed in
the following section.
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.
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.
Object list
Procedure
list
Click event
procedure
Figure 12. The code module for a form, displaying the Click event procedure for
CommandButton1.
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:
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
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:
End Sub
Me.Caption = txtInput.Text
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.
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.
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.
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.
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.
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.
Figure 16. The MultiPage control is useful for organizing related information.
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.
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?
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
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.
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.
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.
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.
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:
End Function
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.
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:
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.
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.
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.
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.
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
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.
Debug.Print Now()
See TestLeapYear The sample file includes a sub procedure to test the IsLeapYear function we
in basLeapYear created earlier, TestLeapYear.
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
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.
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.)
Strings
The functions in Table 1 are useful for manipulating strings:
Conversion
Thee functions in Table 3 come in handy whenever you need to convert one
type of data into another:
Other
The functions in Table 4 don’t fit neatly into any of the other categories:
Figure 9. Use the Object Browser (F2) to view built-in VBA procedures.
• 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 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.
Or like this:
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.)
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.
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.
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
Mastering VBA
Control Structures
Objectives
• Learn about Visual Basic for Applications’ control structures.
• Understand the principles of branching and looping.
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 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
If...Then...Else[If]...End If
If you require more than a single condition, and the conditions are mutually
exclusive, you may find that ElseIf may be what you need.
The general syntax is:
If <condition1> Then
<statement block 1>
ElseIf <condition2> Then
<statement block 2>
...
Else
<statement block 3>
End If
You can have as many ElseIf’s as you want (0, or more) but only a single Else.
The Else clause catches any condition you’ve not checked for explicitly, and is
optional.
Run InputType in As an example, look at the function InputType in basIfThen. This function
basIfThen prompts the user for a value, then checks whether the value is a numeric value,
a date, or an alphanumeric text string.
The code looks like this:
Sub InputType()
Dim strInput As String, strMsg As String
Select Case
The Select Case control structure compares a condition against a single value,
and based on the value, selects a block of statements to execute.
The general syntax looks like this:
VBA 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.
lngThisYear = Year(Date)
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.
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
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:
If someBadCondition Then
GoTo ProcedureExit
End If
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.
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.
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
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.
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.
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
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
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
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
[Exit For]
statement N
Next [variable]
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
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.
For Each...Next
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.
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.
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.
Understanding
Events
Objectives
• Observe the order in which events occur for forms and controls.
• Write simple event procedures.
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.
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.
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.
Item Description
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
casually. Start with our sample form, and add only the controls you need to test
the order in which events occur.
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:
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.
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.
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.
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:
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.
Figure 3. The MouseMove event tells you where the mouse is at any given time.
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.
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).
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:
End Sub
Selection.TypeText Date & " " & Time & vbCrLf & vbCrLf
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.
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,
even though it doesn’t have a module. However, the technique for doing this is
beyond the scope of this course.
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.
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?
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.
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.
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.
Debug.Print UserForm1.Caption
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.
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.
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.
Table 1 shows the other constants that you can use to set the MousePointer
property:
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.
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.
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.
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
Figure 3. You can use the frmTextBox form to try out text box 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:
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
Syntax Notes
Workbooks("Ch08.xls").Worksheets
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")
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
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.
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.
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
In this case, the CheckSpelling method returns False, since the word is spelled
incorrectly.
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:
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.
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:
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.”
To check and see that a variable does point to an object, you can use code like
this:
To free up resources, you can set an object variable to Nothing when you’re
done using it. This is considered good coding practice:
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:
You cannot use a Select Case statement, so you must check for each control
type with an individual call to TypeOf, like this:
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()
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.
You could also use the Me keyword to refer to the current form:
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:
You can’t use the Me keyword to refer to a form from any module except that
form’s own module.
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.
With txt
.BackColor = vbBlack
.ForeColor = vbCyan
.FontName = "Arial"
.FontSize = 16
.FontBold = True
End With
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.
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?
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.
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.
TIP: If you want to explore Excel’s objects, properties, and methods, head to the
Object Browser, and press F1 for context-sensitive Help.
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:
strFileName = Application.GetOpenFilename(conFilter)
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.
You can create a new workbook with the Add method, and save it with the
SaveAs method:
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
Debug.Print ActiveWorkbook.Worksheets(1).Name
ActiveWorkbook.ActiveSheet.Copy
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
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.
Sub DataRegion()
Dim rng As Range
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
Figure 2. The Application object contains the Documents collection and the
Selection object.
ActiveDocument.Close
Application.CapsLock = True
Application.Documents("Ch09.doc").Save
ActiveDocument.CheckSpelling
Documents.Add
You can print a document in the background, using the PrintOut method:
ActiveDocument.PrintOut Background:=True
ActiveDocument.CheckSpelling
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!
With Selection
.Copy
.MoveDown
.Paste
End With
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.
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:
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.
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
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.
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:
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.
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.
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?
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
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.
Key Terms
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.
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.
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).
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.
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.
objApp.Visible = True
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.
GetMedian = _
objApp.WorksheetFunction.Median(lngW, _
lngX, lngY, lngZ)
objApp.Application.Quit
Set objApp = Nothing
End Function
The next line creates the new instance of Microsoft Excel and assigns it to the
object variable:
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:
The following table breaks this expression down into its individual parts:
Part Function
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.
while others keep running. Table 1 lists some of the differences between
applications in the Microsoft Office suite.
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:
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.
To transfer the results of this query to the Excel worksheet, the procedure calls
the CopyFromRecordset method of an Excel Range object. This method
accepts a Jet Recordset object and dumps the contents of it into the worksheet
starting at the address defined by the Range object:
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
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
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
ValueTitle:="", ExtraTitle:=""
' Clean up
rst.Close
Set objChart = Nothing
Set objRange = Nothing
Set objSheet = Nothing
Set objBook = Nothing
Set objApp = Nothing
End Sub
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.
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?
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
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
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.
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]]
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.)
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
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
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
Constructing Procedures
VBA procedures require you to name various objects: procedure names, labels, and
parameters. These objects are described in the following sections.
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
Prefixes
Prefixes modify an object tag to indicate more information about an object.
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
You also use the “m” and “g” constants with other objects, such as constants, to indicate
their scope. For example:
intLocalVariable
mintPrivateVariable
gintPublicVariable
mconPi
Other Prefixes
Table 3 lists and describes some other prefixes.
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.
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.
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.
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.
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