You are on page 1of 13

Definitive Guide to Excel VBA, Second Edition

Michael Kofler
David Kramer
Apress

Copyright 2003 Michael Kofler

All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying, recording, or by any information storage or retrieval
system, without the prior written permission of the copyright owner and the publisher.

1-59059-103-8

12345678910

Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a
trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner,
with no intention of infringement of the trademark.

Translator and Editor: David Kramer


Editorial Board: Dan Appleman, Craig Berry, Gary Cornell, Tony Davis, Steven Rycroft, Julian Skinner,
Martin Streicher, Jim Sumser, Karen Watterson, Gavin Wright, John Zukowski
Assistant Publisher and Project Manager: Grace Wong
Copy Editor: Rebecca Rider
Production Manager: Kari Brooks
Production Editor: Janet Vail
Proofreader: Lori Bring
Compositor: Diana Van Winkle, vwdesign.com
Indexer: Kevin Broccoli
Cover Designer: Kurt Krames
Manufacturing Manager: Tom Debolski

Distributed to the book trade in the United States by Springer-Verlag New York, Inc., 175 Fifth Avenue, New
York, NY, 10010 and outside the United States by Springer-Verlag GmbH & Co. KG, Tiergartenstr. 17,
69112 Heidelberg, Germany.

In the United States: phone 1-800-SPRINGER, email orders@springer-ny.com, or visit


http://www.springer-ny.com. Outside the United States: fax +49 6221 345229, email orders@springer.de, or
visit http://www.springer.de.

For information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219, Berkeley, CA
94710. Phone 510-549-5930, fax 510-549-5939, email info@apress.com, or visit http://www.apress.com.

The information in this book is distributed on an "as is" basis, without warranty. Although every precaution
has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any
person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the
information contained in this work.

The source code for this book is available to readers at http://www.apress.com in the Downloads section.

Definitive Guide to Excel VBA, Second Edition 1


2 Definitive Guide to Excel VBA, Second Edition

2 Definitive Guide to Excel VBA, Second Edition


Preface
Excel offers right out of the box an enormous variety of functions. So why does one need VBA macros? With
VBA you can accomplish wonders:

You can program your own worksheet functions that are easier to use than complicated formulas.
You can configure Excel to suit your requirements and in this way achieve greater simplicity and
efficiency.
You can structure and simplify complex processes such as filling out forms by means of "smart"
forms (templates).
You can automate processes that are used frequently. This is particularly useful in dealing repeatedly
with large data sets that must be processed, analyzed, and graphically displayed.
You can create freestanding Excel programs that display their own menus, dialogs, and toolbars. This
makes it possible to simplify an Excel application to the point where those unfamiliar with Excel can
run the program correctly.

What's New in Excel 2000 and 2002?


With Excel 97, the VBA programming model and the most important object libraries became fairly stable.
Excel 2000 and 2002 introduced a host of new objects, but in practice these are seldom used (if for no other
reason than to make VBA applications backward compatible with the widely distributed Excel 97). The most
important innovations are the Scripting and ADO libraries, both of which have been available since Excel
2000, simplifying access to files, directories, and external databases.

Excel and .NET


In connection with Microsoft's .NET offensive, it should be mentioned that Office 2000 and 2002 are not yet
.NET compatible. Even the forthcoming Office edition scheduled for release sometime in 2003 will not be
based on .NET, according to current word from Microsoft. But that is no reason for tears. If Microsoft were
someday to decide actually to convert the Office suite to .NET and the new programming language VB.NET,
then there would be a great number of compatibility problems built into Excel.

An important function of .NET, namely, the so-called web services, can already be used with Excel 2000 and
2002 without compatibility problems. The Web Services Toolkit, a simple and freely distributed extension of
the VBA development environment, makes this possible. (Details on the use of this toolkit appear in Chapter
14.)

Why This Book?


The real problem in VBA programming is not VBA itself. The formulation of a loop or test, the use of
methods and properties, are easily understood as in any programming language and will cause you no trouble
after a couple of days. The problem is to get a handle on the complex object libraries within Excel, with their
more than a thousand keywords, and to use them efficiently. The focus of this book and the examples
presented herein is to explain these object libraries.

Preface 1
2 Preface
In contrast to Excel's Help, the goal of this book is not to offer merely a referenceoften one that says next to
nothingof key words. It is our purpose to show the connections among the numerous objects and to
demonstrate their use with concrete application examples as they appear in the real world. We do not hesitate
to point out problems with Excel where they exist, in order to spare you, the reader, from a fruitless search for
errors of which you were not the cause.

Enjoy!
The examples of this book show just how far one can go with Excel programming. The possibilities are truly
endless. This book will help you to become acquainted quickly with Excel's object model, and once you have
gotten over that hurdle (figure one or two weeks), you will find that VBA programming is a lot of fun.
Therefore, I wish you great success and plenty of fun and enjoyment in your Excel programming.

Michael Kofler, May 2003


http://www.kofler.cc

2 Preface
The Idea Behind This Book
Visual basic for applications is, to be sure, a modern object-oriented programming language that offers an
incredible number of keywords, but at the same time it offers many difficulties. At the beginning one has no
hope of gaining even an overview of VBA. And even after months of programming in VBA the on-line help
will remain the most important source of advice on the details of a particular keyword. Therefore, this book
attempts to compensate for the shortcomings in the original documentation and the on-line help by providing
the following assistance:

Genuine applications in the form of concrete, realistic examples


Thematic syntax summaries (for example, all properties and methods for dealing with ranges of cells)
Detailed information on the use of DLL functions, on ActiveX automation, on the creation of custom
on-line help texts, on programming your own add-ins.
Useful descriptions of all VBA objects and their arrangement in the object hierarchy
Information on inconsistiencies and errors in VBA

However, there is one attribute that this book does not possess: completeness. There is no point, it seems to
me, in filling hundreds of pages with a reference to all keywords when practically the same information can
be found in the on-line help. Instead of seeking to give only the appearance of completeness, I have attempted
to give preference to the most important topics and to deal with these in full detail.

Formalities
Keyboard shortcuts are given in the form Ctrl+F2. Menu commands appear as follows: FILE|OPEN,
CANCEL, or OK. The instruction EDIT|DELETE|SHIFT cells left means that you first execute the menu
command EDIT|DELETE and then in the dialog that appears select the button Shift cells left.

VBA keywords as well as variables and procedures are written in italics, for example, "Application object" or
"Visible property." Worksheet functions are written in the same type style, but in all uppercase letters, as in
IF, for example.

(In international versions of Excel it is necessary to distinguish worksheet functions from VBA keywords:
VBA keywords are always in English, while worksheet functions must be given in the local language.)
Keywords that appear in the text for the first time with an explanation or that are particularly important are
printed in bold italics.

The Example Files


The example files for this book are available at http://www.Apress.com in the downloads section.

Excel XP or Excel 2002? Office XP or Office 2002?


Microsoft markets the current version of its Office suite as Office XP, though the version of Excel contained
in Office XP is usually referred to as Excel 2002. In any case, they are the same. Excel 2002 = Excel XP. This
book uses the names Excel 2002 and Office 2002.

The Idea Behind This Book 1


2 The Idea Behind This Book

2 The Idea Behind This Book


Part One: An Intuitive Approach
Chapter List
Chapter 1: Writing Your First Macro
Chapter 2: What's New in Excel 2000

Part One: An Intuitive Approach 1


2 Part One: An Intuitive Approach

2 Part One: An Intuitive Approach


Chapter 1: Writing Your First Macro
In this chapter you will learn about such concepts as "macro" and "Visual Basic for Applications." You will
also record your very own macros, link macros with new tools (which you create) in the toolbar, change the
menu structure, and put together a simple database application. This chapter offersto the extent possible
with simple examplesa brief glance at the material that will be covered in much greater detail in the
remainder of this book. Welcome aboard!

1.1 Definition of Terms


Macros

This chapter is entitled "Writing Your First Macro." It thus seems appropriate at this point to explain the term
"macro." A macro is a sequence of instructions to the computer that the computer then carries out when
ordered to do so.

What is the purpose of macros? With macros it is possible to simplify and automate tasks that are frequently
repeated. You can customize Excel to meet your particular needs and equip Excel with new menu commands
and tools. Furthermore, you can simplify Excel for other users so that they can make use of particular Excel
applications with almost no additional training. And finally, you can write full-blown "programs" that will be
hardly recognizable as having originated from within Excel.

Since the computer unfortunately does not understand instructions such as "save this data" or "display the
three selected cells in a larger font," macro instructions must be formulated in a special language. For reasons
of compatibility, Excel offers two such languages from which to choose:

The original macro programming language, called XLM, was created for early versions of Excel.
Macros written in this language are referred to as XLM macros or Excel 4 macros, since the basic
structure of this language has not been changed since version 4 of Excel.
Beginning with version 5, the new language Visual Basic for Applications (VBA for short) was
introduced. It offers more extensive and refined possibilities for the control of programs, though at
first glance it may seem somewhat complex (especially for those who have written XLM macros).

Note In Excel version 5 several dialects of VBA in several languages were available, such as French, German,
and Spanish. In version 7 these dialects were still supported, but they were no longer the default
language. With version 97 they disappeared entirely. Foreign-language VBA code is now automatically
converted to English when a file is loaded. This book describes English VBA exclusively. Here is an
example in the two macro languages (first as an Excel 4 macro, then in VBA) that saves the current file:

=SAVE() 'XLM macro (Excel 4)


ActiveWorkbook.Save 'VBA (Excel 5, 7, 97, 2000 etc.)
Our next example displays a group of selected cells in a larger font size (first as an Excel 4 macro, then in
VBA):

=FONT.PROPERTIES(, GET.CELL(19)+2) 'Excel 4


Selection.Font.Size = Selection.Font.Size + 2 'VBA

When the term "macro" is used in books or in on-line documentation it is not always made clear whether the
XLM or VBA language is meant. In this book, however, the term "macro" will always mean a VBA macro.

Note The above examples are not usable in the form given. An Excel 4 macro must begin with the name of
the macro and end with the command =RETURN().VBA macros must be bracketed between Sub
Name() and End Sub. The basic syntax of VBA should become clear from the examples presented in
this chapter. A detailed description of VBA syntax will be presented in Chapter 4.

Chapter 1: Writing Your First Macro 1


2 Chapter 1: Writing Your First Macro
Recording Macros

In general, there are two ways of creating macros: You can input the VBA commands from the keyboard, or
you let Excel "record" the macro. By this is meant that (using the mouse and keyboard) you perform actions
such as data entry, formatting of cells, and executing commands, and Excel follows your actions and writes
the corresponding VBA instructions in a module. When later you execute the macro that has been created in
this way, the exact same steps that you had previously executed by hand are executed.

In reality, macros are generally created by a combination of these two methods. You will certainly frequently
let Excel record your actions, but it will also frequently be necessary to alter or supplement these macros by
typing at the keyboard.

Executing Macros

The least satisfactory method of executing a macro is provided by the command Tools|Macro, which produces
a list of all the defined macros in all open workbooks. When you click on the name of a macro, the
corresponding macro is executed.

However, there are quite a few more elegant methods available: You can link a macro to an arbitrary (new)
tool in the toolbar, to a menu item, or to a keyboard shortcut Ctrl+ letter. The macro is executed when you
choose the menu item, click on the tool, or type the keyboard shortcut. Macros implemented in this way can
save a great deal of effort, as shown in the examples that appear in the following section.

There is even the possibility of having macros execute automatically when certain events occur. Excel knows
about a large number of such events, such as a change in the active worksheet, the recalculation of a
worksheet, and saving a workbook. Event procedures will be dealt with in detail in Chapter 4.

Programs

Many users of Excel, even those who have already created macros, are ready to tear out their hair when they
hear the term "programming." One frequently hears the following opinion expressed: "Programming? That is
something for computer professionals, for that you need an advanced degree." But relax! You are, in fact,
already a programmer by virtue of having created your first macro, even if it is only three lines long. In
principle, every macro is a program.

In this book the notion of a program will be construed for the most part somewhat more broadly. By a
program we will mean a freestanding Excel application, distinguished in general by having its own menu
commands, forms, and, usually, a large number of macros. This book will take you from the baby steps of
your first macro (in this chapter) all the way to the giant steps of substantial programs.

1.2 What Is Visual Basic for Applications?


Visual Basic for Applications (VBA) is a macro programming language. With VBA you can automate Excel
applications or simplify their use. The possibilities for using macros are so numerous and varied that you can
create completely freestanding programs that can hardly be recognized as Excel applications. In this chapter
you will find some introductory examples of simple macros.

Historical Note

Excel's XLM macro language arose originally from the desire to define new worksheet functions and to
collect frequently occurring commands into a unit (into a macro, that is). Furthermore, to make Excel

2 Chapter 1: Writing Your First Macro


Chapter 1: Writing Your First Macro 3
applications as easy as possible to use, XLM made it possible to alter menus and to define custom forms. The
fact that Excel offers a large range of functions meant that by the time of Excel 4 a rather confusing macro
language had developed.

To be sure, this macro language made possible almost unlimited programming of all Excel functions, though
many programming problems could be solved only in a rather convoluted way. The programs that resulted
were generally subject to error, and they often ran slowly. In large projects the limitations of this macro
language became clear. Those who simultaneously used several Microsoft programs (Excel, Word, Access)
were faced with the further problem that each program came equipped with its own macro language.

Because of all these shortcomings, Microsoft decided to develop a completely new macro language, designed
first and foremost for Excel, but which by now has been integrated into all components of the Microsoft
Office suite.

Special Features of VBA

Unlike earlier macro languages, VBA is a complete programming language: VBA recognizes all
variable types that are found in "real" programming languages, and it can handle such macho tasks as
working with character strings, managing dynamic fields, and employing recursive functions.
VBA is object oriented: Among the objects are to be found selected ranges of cells, worksheets, and
charts. Typical characteristics of such objectssuch as the orientation of cell contents, the
background color of a chartare set by means of manipulating their properties. Thus, properties are
predefined keywords intended for the manipulation of objects. In addition to properties there are
methods, which are used for executing complex operations, such as creating objects (new charts, pivot
tables, for example) and deleting existing objects. Methods can be most nearly compared with XLM
commands. The essential difference is that a method can be applied only to those objects that support
that method.
VBA is event oriented: Choosing a menu entry, clicking on a button or tool, results automatically in a
call to the associated macro. As a programmer you need not be concerned with the management of
events, but only with creating macros, which then are called independently by Excel.
VBA places professional assistance for debugging at your fingertips: Program segments can be run in
step mode, while the contents of variables are examined. The execution of the program can be
interrupted when particular conditions are met.
VBA is extensible: In every VBA dialect one can make use of objects belonging to other applications.
For example, it is possible in an Excel VBA program to use keywords (in computer jargon, the object
library) from Access or Word. With add-ins you can create new Excel functions and objects.
Integrated in VBA are form (dialog) and menu editors. The management of forms is handled in the
same object and event-oriented way as the management of Excel objects.

Note Occasionally, there is a certain amount of confusion caused by the fact that Visual Basic is connected
with a number of Microsoft products. The theme of this book is Excel, and how it can be controlled
using the integrated language VBA. However, there is also the independent product "Visual Basic"
(currently available in version 6) and the new "Visual Basic .NET." In this case we are dealing with a
programming language that you can use to develop programs independent of the Office suite of
applications; the execution of such programs does not presuppose that the user has installed Microsoft
Office. VBA on the one hand, and Visual Basic 6 and Visual Basic .NET on the other, exhibit a number
of similarities, but they are in many ways incompatible (in particular, Visual Basic .NET has very many
differences from VBA).
Drawbacks

After describing the advantages of VBA you may have received the impression that with VBA you have
landed in programmer's nirvana. That, however, would be an erroneous assessment of the situation. VBA has
many advantages, but it has, alas, a number of drawbacks:

Chapter 1: Writing Your First Macro 3


4 Chapter 1: Writing Your First Macro

The VBA language is quite large, and it is therefore difficult to obtain a broad overview of it. With
well over one thousand keywords (without counting the predefined constants), VBA programming far
exceeds the size that programmers previously had to deal with. In searching for a suitable method or
property for a specific task you could end up missing both your dinner and next morning's breakfast.
VBA programs are long-winded in their formulation. If you were to record the same macro once as an
XLM macro and again as a VBA macro, you would find that the VBA code is on average at least fifty
percent larger than the XLM code. (There is no dispute, however, that the VBA code is easier to
read!)

1.3 Linking a Custom Style with a Tool


In our first example we shall begin by defining a style. (A style gathers together a collection of format
information such as font, alignment, border, and color. Styles can be used for formatting cells.) Then we shall
record a macro that assigns this style to selected cells. Then a new tool will be added to the toolbar, which will
be linked to this macro. We will then be able to format previously selected cells with the style that we have
defined by clicking on the new tool.

Note All the examples in this chapter can also be found in the example files at http://www.apress.com.
Before You Begin

We begin with three tips that will simplify your programming with Excel 2000:

With Excel 2002 the default setting for the security of macros is High. This means that VBA code can
be executed only when the Excel file comes from a trustworthy source and is signed.

This is not the case for Excel files that one develops oneself, nor for the example files in this book. To
develop and test your own VBA-Code you must therefore set the macro security to Medium in the
menu Tools|Macro|Security. (Further information on security can be found in the last section of
Chapter 4.)
A new feature of Office 2000 that drives every user to despair is dealing with menus: In the default
settings, only the most important menu items are shown, which, moreover, appear only after some
time. To bring this nonsense to an end, execute View|Toolbars|Customize, click on the Options tab,
and there deactivate the option Menus Show Recently Used Commands. From now on the full menus
will be shown in all your Office applications.
In the VBA development environment (which you may invoke by pressing Alt+F11) there are also
some options whose preset values are a bit weird. You can reach the options form (dialog) by
executing Tools|Options. When you get there, deactivate Auto Syntax Check. (Syntax will still be
checked; lines containing errors will be marked in red. But you will be spared the burdensome
announcement of the error accompanied by a beep.)

Then activate the option Require Variable Declaration. (Extensive justification for this will be given
in the first section of Chapter 4.)

In the dialog page General deactivate Compile On Demand (see Section 3.2). Finally, on the page
Docking deactivate all of the options fields. (You will thereby obtain the result that in the
development environment you will be able to place windows on top of each other. In the default
setting the environment behaves as in Windows 1.0and one would have thought that those times
were long gone!)

4 Chapter 1: Writing Your First Macro


Chapter 1: Writing Your First Macro 5

Step 1: Definition of the Custom Style "Result"

We would like cells that contain an (intermediate) result of a calculation to look as follows:

Font: Arial, 14 point, bold


Border: double line below
Number format: two decimal places

If you wished, you could, of course, choose other formatting characteristics. The only point of the particular
choice in this example is to define a new uniquely recognizable style.

To define a style, open a new workbook by executing File|New, type a number in an arbitrary cell, and format
this cell according to the characteristics given above. Then execute the command Format|Style. In the dialog
that appears give the style the name "Result" and click first ADD and then OK.

Figure 1-1: Defining a new style


Step 2: Recording a Macro

We would like the steps that we have just taken to format a test cell to be carried out in the future by a macro.
Why should we have to do all the work? For this to happen we must first record these steps with the macro
recorder. Move the pointer into a new cell and input a number (in order to verify the result). Terminate input
by hitting Return, and move the pointer if necessary back into the cell that you have just altered. Now select
the command Tools|Macro|Record New Macro, and give the macro the name "FormatAsResult"(see Figure
1-2).

Figure 1-2: Form for recording macros


As soon as you click on OK, Excel begins to record your new macro. Format the currently active cell with the
style "Result"(just as you did at the end of Step 1 when you were testing the new style). Terminate the

Chapter 1: Writing Your First Macro 5

You might also like