Tải bản đầy đủ (.pdf) (2,322 trang)

Programming excel with VBA and NET

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (10.85 MB, 2,322 trang )

This document is created with a trial version of CHM2PDF Pilot


Programming Excel with VBA and .NET
By Steve Saunders, Jeff Webb
...............................................
Publisher: O'Reilly
Pub Date: April 2006
Print ISBN-10: 0-596-00766-3
Print ISBN-13: 978-0-59-600766-9
Pages: 1114

Table of Contents | Index

Why program Excel? For solving complex calculations and presenting results, Excel is amazingly complete with every
imaginable feature already in place. But programming Excel isn't about adding new features as much as it's about
combining existing features to solve particular problems. With a few modifications, you can transform Excel into a
task-specific piece of software that will quickly and precisely serve your needs. In other words, Excel is an ideal
platform for probably millions of small spreadsheet-based software solutions.

The best part is, you can program Excel with no additional tools. A variant of the Visual Basic programming language,
VB for Applications (VBA) is built into Excel to facilitate its use as a platform. With VBA, you can create macros and
templates, manipulate user interface features such as menus and toolbars, and work with custom user forms or
dialog boxes. VBA is relatively easy to use, but if you've never programmed before, Programming Excel with VBA and
.NET is a great way to learn a lot very quickly. If you're an experienced Excel user or a Visual Basic programmer,
you'll pick up a lot of valuable new tricks. Developers looking forward to .NET development will also find discussion of
how the Excel object model works with .NET tools, including Visual Studio Tools for Office (VSTO).

This book teaches you how to use Excel VBA by explaining concepts clearly and concisely in plain English, and
provides plenty of downloadable samples so you can learn by doing. You'll be exposed to a wide range of tasks most
commonly performed with Excel, arranged into chapters according to subject, with those subjects corresponding to


one or more Excel objects. With both the samples and important reference information for each object included right
in the chapters, instead of tucked away in separate sections, Programming Excel with VBA and .NET covers the entire
Excel object library. For those just starting out, it also lays down the basic rules common to all programming
languages.

With this single-source reference and how-to guide, you'll learn to use the complete range of Excel programming
tasks to solve problems, no matter what you're experience level.


This document is created with a trial version of CHM2PDF Pilot


Programming Excel with VBA and .NET
By Steve Saunders, Jeff Webb
...............................................
Publisher: O'Reilly
Pub Date: April 2006
Print ISBN-10: 0-596-00766-3
Print ISBN-13: 978-0-59-600766-9
Pages: 1114

Table of Contents | Index

Programming Excel with VBA and .NET
Preface
Part I: Learning VBA
Chapter 1. Becoming an Excel Programmer
Section 1.1. Why Program?
Section 1.2. Record and Read Code
Section 1.3. Change Recorded Code

Section 1.4. Fix Misteakes
Section 1.5. Start and Stop
Section 1.6. View Results
Section 1.7. Where's My Code?
Section 1.8. Macros and Security
Section 1.9. Write Bug-Free Code
Section 1.10. Navigate Samples and Help
Section 1.11. What You've Learned
Chapter 2. Knowing the Basics
Section 2.1. Parts of a Program
Section 2.2. Classes and Modules
Section 2.3. Procedures
Section 2.4. Variables
Section 2.5. Conditional Statements
Section 2.6. Loops
Section 2.7. Expressions
Section 2.8. Exceptions
Section 2.9. What You've Learned
Chapter 3. Tasks in Visual Basic
Section 3.1. Types of Tasks
Section 3.2. Interact with Users
Section 3.3. Do Math
Section 3.4. Work with Text
Section 3.5. Get Dates and Times
Section 3.6. Read and Write Files
Section 3.7. Check Results
Section 3.8. Find Truth
Section 3.9. Compare Bits
Section 3.10. Run Other Applications
Section 3.11. Control the Compiler

Section 3.12. Not Covered Here
Section 3.13. What You've Learned
Chapter 4. Using Excel Objects


This document is created with a trial version of CHM2PDF Pilot

Section 4.1. Objects and Their Members
Section 4.2. Get Excel Objects
Section 4.3. Get Objects from Collections
Section 4.4. About Me and the Active Object
Section 4.5. Find the Right Object
Section 4.6. Common Members
Section 4.7. Respond to Events in Excel
Section 4.8. The Global Object
Section 4.9. The WorksheetFunction Object
Section 4.10. What You've Learned
Chapter 5. Creating Your Own Objects
Section 5.1. Modules Versus Classes
Section 5.2. Add Methods
Section 5.3. Create Properties
Section 5.4. Define Enumerations
Section 5.5. Raise Events
Section 5.6. Collect Objects
Section 5.7. Expose Objects
Section 5.8. Destroy Objects
Section 5.9. Things You Can't Do
Section 5.10. What You've Learned
Chapter 6. Writing Code for Use by Others
Section 6.1. Types of Applications

Section 6.2. The Development Process
Section 6.3. Determine Requirements
Section 6.4. Design
Section 6.5. Implement and Test
Section 6.6. Integrate
Section 6.7. Test Platforms
Section 6.8. Document
Section 6.9. Deploy
Section 6.10. What You've Learned
Section 6.11. Resources
Part II: Excel Objects
Chapter 7. Controlling Excel
Section 7.1. Perform Tasks
Section 7.2. Control Excel Options
Section 7.3. Get References
Section 7.4. Application Members
Section 7.5. AutoCorrect Members
Section 7.6. AutoRecover Members
Section 7.7. ErrorChecking Members
Section 7.8. SpellingOptions Members
Section 7.9. Window and Windows Members
Section 7.10. Pane and Panes Members
Chapter 8. Opening, Saving, and Sharing Workbooks
Section 8.1. Add, Open, Save, and Close
Section 8.2. Share Workbooks
Section 8.3. Program with Shared Workbooks
Section 8.4. Program with Shared Workspaces
Section 8.5. Respond to Actions
Section 8.6. Workbook and Workbooks Members
Section 8.7. RecentFile and RecentFiles Members



This document is created with a trial version of CHM2PDF Pilot

Section 8.7. RecentFile and RecentFiles Members
Chapter 9. Working with Worksheets and Ranges
Section 9.1. Work with Worksheet Objects
Section 9.2. Worksheets and Worksheet Members
Section 9.3. Sheets Members
Section 9.4. Work with Outlines
Section 9.5. Outline Members
Section 9.6. Work with Ranges
Section 9.7. Range Members
Section 9.8. Work with Scenario Objects
Section 9.9. Scenario and Scenarios Members
Section 9.10. Resources
Chapter 10. Linking and Embedding
Section 10.1. Add Comments
Section 10.2. Use Hyperlinks
Section 10.3. Link and Embed Objects
Section 10.4. Speak
Section 10.5. Comment and Comments Members
Section 10.6. Hyperlink and Hyperlinks Members
Section 10.7. OleObject and OleObjects Members
Section 10.8. OLEFormat Members
Section 10.9. Speech Members
Section 10.10. UsedObjects Members
Chapter 11. Printing and Publishing
Section 11.1. Print and Preview
Section 11.2. Control Paging

Section 11.3. Change Printer Settings
Section 11.4. Filter Ranges
Section 11.5. Save and Display Views
Section 11.6. Publish to the Web
Section 11.7. AutoFilter Members
Section 11.8. Filter and Filters Members
Section 11.9. CustomView and CustomViews Members
Section 11.10. HPageBreak, HPageBreaks, VPageBreak, VPageBreaks Members
Section 11.11. PageSetup Members
Section 11.12. Graphic Members
Section 11.13. PublishObject and PublishObjects Members
Section 11.14. WebOptions and DefaultWebOptions Members
Chapter 12. Loading and Manipulating Data
Section 12.1. Working with QueryTable Objects
Section 12.2. QueryTable and QueryTables Members
Section 12.3. Working with Parameter Objects
Section 12.4. Parameter Members
Section 12.5. Working with ADO and DAO
Section 12.6. ADO Objects and Members
Section 12.7. DAO Objects and Members
Section 12.8. DAO.Database and DAO.Databases Members
Section 12.9. DAO.Document and DAO.Documents Members
Section 12.10. DAO.QueryDef and DAO.QueryDefs Members
Section 12.11. DAO.Recordset and DAO.Recordsets Members
Chapter 13. Analyzing Data with Pivot Tables
Section 13.1. Quick Guide to Pivot Tables
Section 13.2. Program Pivot Tables


This document is created with a trial version of CHM2PDF Pilot


Section 13.3. PivotTable and PivotTables Members
Section 13.4. PivotCache and PivotCaches Members
Section 13.5. PivotField and PivotFields Members
Section 13.6. CalculatedFields Members
Section 13.7. CalculatedItems Members
Section 13.8. PivotCell Members
Section 13.9. PivotFormula and PivotFormulas Members
Section 13.10. PivotItem and PivotItems Members
Section 13.11. PivotItemList Members
Section 13.12. PivotLayout Members
Section 13.13. CubeField and CubeFields Members
Section 13.14. CalculatedMember and CalculatedMembers Members
Chapter 14. Sharing Data Using Lists
Section 14.1. Use Lists
Section 14.2. ListObject and ListObjects Members
Section 14.3. ListRow and ListRows Members
Section 14.4. ListColumn and ListColumns Members
Section 14.5. ListDataFormat Members
Section 14.6. Use the Lists Web Service
Section 14.7. Lists Web Service Members
Section 14.8. Resources
Chapter 15. Working with XML
Section 15.1. Understand XML
Section 15.2. Save Workbooks as XML
Section 15.3. Use XML Maps
Section 15.4. Program with XML Maps
Section 15.5. XmlMap and XmlMaps Members
Section 15.6. XmlDataBinding Members
Section 15.7. XmlNamespace and XmlNamespaces Members

Section 15.8. XmlSchema and XmlSchemas Members
Section 15.9. Get an XML Map from a List or Range
Section 15.10. XPath Members
Section 15.11. Resources
Chapter 16. Charting
Section 16.1. Navigate Chart Objects
Section 16.2. Create Charts Quickly
Section 16.3. Embed Charts
Section 16.4. Create More Complex Charts
Section 16.5. Choose Chart Type
Section 16.6. Create Combo Charts
Section 16.7. Add Titles and Labels
Section 16.8. Plot a Series
Section 16.9. Respond to Chart Events
Section 16.10. Chart and Charts Members
Section 16.11. ChartObject and ChartObjects Members
Section 16.12. ChartGroup and ChartGroups Members
Section 16.13. SeriesLines Members
Section 16.14. Axes and Axis Members
Section 16.15. DataTable Members
Section 16.16. Series and SeriesCollection Members
Section 16.17. Point and Points Members
Chapter 17. Formatting Charts
Section 17.1. Format Titles and Labels


This document is created with a trial version of CHM2PDF Pilot

Section 17.1. Format Titles and Labels
Section 17.2. Change Backgrounds and Fonts

Section 17.3. Add Trendlines
Section 17.4. Add Series Lines and Bars
Section 17.5. ChartTitle, AxisTitle, and DisplayUnitLabel Members
Section 17.6. DataLabel and DataLabels Members
Section 17.7. LeaderLines Members
Section 17.8. ChartArea Members
Section 17.9. ChartFillFormat Members
Section 17.10. ChartColorFormat Members
Section 17.11. DropLines and HiLoLines Members
Section 17.12. DownBars and UpBars Members
Section 17.13. ErrorBars Members
Section 17.14. Legend Members
Section 17.15. LegendEntry and LegendEntries Members
Section 17.16. LegendKey Members
Section 17.17. Gridlines Members
Section 17.18. TickLabels Members
Section 17.19. Trendline and Trendlines Members
Section 17.20. PlotArea Members
Section 17.21. Floor Members
Section 17.22. Walls Members
Section 17.23. Corners Members
Chapter 18. Drawing Graphics
Section 18.1. Draw in Excel
Section 18.2. Create Diagrams
Section 18.3. Program with Drawing Objects
Section 18.4. Program Diagrams
Section 18.5. Shape, ShapeRange, and Shapes Members
Section 18.6. Adjustments Members
Section 18.7. CalloutFormat Members
Section 18.8. ColorFormat Members

Section 18.9. ConnectorFormat Members
Section 18.10. ControlFormat Members
Section 18.11. FillFormat Members
Section 18.12. FreeFormBuilder
Section 18.13. GroupShapes Members
Section 18.14. LineFormat Members
Section 18.15. LinkFormat Members
Section 18.16. PictureFormat Members
Section 18.17. ShadowFormat
Section 18.18. ShapeNode and ShapeNodes Members
Section 18.19. TextFrame
Section 18.20. TextEffectFormat
Section 18.21. ThreeDFormat
Chapter 19. Adding Menus and Toolbars
Section 19.1. About Excel Menus
Section 19.2. Build a Top-Level Menu
Section 19.3. Create a Menu in Code
Section 19.4. Build Context Menus
Section 19.5. Build a Toolbar
Section 19.6. Create Toolbars in Code
Section 19.7. CommandBar and CommandBars Members


This document is created with a trial version of CHM2PDF Pilot

Section 19.8. CommandBarControl and CommandBarControls Members
Section 19.9. CommandBarButton Members
Section 19.10. CommandBarComboBox Members
Section 19.11. CommandBarPopup Members
Chapter 20. Building Dialog Boxes

Section 20.1. Types of Dialogs
Section 20.2. Create Data-Entry Forms
Section 20.3. Design Your Own Forms
Section 20.4. Use Controls on Worksheets
Section 20.5. UserForm and Frame Members
Section 20.6. Control and Controls Members
Section 20.7. Font Members
Section 20.8. CheckBox, OptionButton, ToggleButton Members
Section 20.9. ComboBox Members
Section 20.10. CommandButton Members
Section 20.11. Image Members
Section 20.12. Label Members
Section 20.13. ListBox Members
Section 20.14. MultiPage Members
Section 20.15. Page Members
Section 20.16. ScrollBar and SpinButton Members
Section 20.17. TabStrip Members
Section 20.18. TextBox and RefEdit Members
Chapter 21. Sending and Receiving Workbooks
Section 21.1. Send Mail
Section 21.2. Work with Mail Items
Section 21.3. Collect Review Comments
Section 21.4. Route Workbooks
Section 21.5. Read Mail
Section 21.6. MsoEnvelope Members
Section 21.7. MailItem Members
Section 21.8. RoutingSlip Members
Part III: Extending Excel
Chapter 22. Building Add-ins
Section 22.1. Types of Add-ins

Section 22.2. Code-Only Add-ins
Section 22.3. Visual Add-ins
Section 22.4. Set Add-in Properties
Section 22.5. Sign the Add-in
Section 22.6. Distribute the Add-in
Section 22.7. Work with Add-ins in Code
Section 22.8. AddIn and AddIns Members
Chapter 23. Integrating DLLs and COM
Section 23.1. Use DLLs
Section 23.2. Use COM Applications
Chapter 24. Getting Data from the Web
Section 24.1. Perform Web Queries
Section 24.2. QueryTable and QueryTables Web Query Members
Section 24.3. Use Web Services
Section 24.4. Resources
Chapter 25. Programming Excel with .NET
Section 25.1. Approaches to Working with .NET
Section 25.2. Create .NET Components for Excel


This document is created with a trial version of CHM2PDF Pilot

Section 25.2. Create .NET Components for Excel
Section 25.3. Use .NET Components in Excel
Section 25.4. Use Excel as a Component in .NET
Section 25.5. Create Excel Applications in .NET
Section 25.6. Resources
Chapter 26. Exploring Security in Depth
Section 26.1. Security Layers
Section 26.2. Understand Windows Security

Section 26.3. Password-Protect and Encrypt Workbooks
Section 26.4. Program with Passwords and Encryption
Section 26.5. Workbook Password and Encryption Members
Section 26.6. Excel Password Security
Section 26.7. Protect Items in a Workbook
Section 26.8. Program with Protection
Section 26.9. Workbook Protection Members
Section 26.10. Worksheet Protection Members
Section 26.11. Chart Protection Members
Section 26.12. Protection Members
Section 26.13. AllowEditRange and AllowEditRanges Members
Section 26.14. UserAccess and UserAccessList Members
Section 26.15. Set Workbook Permissions
Section 26.16. Program with Permissions
Section 26.17. Permission and UserPermission Members
Section 26.18. Add Digital Signatures
Section 26.19. Set Macro Security
Section 26.20. Set ActiveX Control Security
Section 26.21. Distribute Security Settings
Section 26.22. Using the Anti-Virus API
Section 26.23. Common Tasks
Section 26.24. Resources
Part IV: Appendixes
Appendix A. Reference Tables
Section A.1. Dialogs Collection Constants
Section A.2. Common Programmatic IDs
Appendix B. Version Compatibility
Section B.1. Summary of Version Changes
Section B.2. Macintosh Compatibility
About the Author

Colophon
Index


This document is created with a trial version of CHM2PDF Pilot


Programming Excel with VBA and .NET
by Jeff Webb and Steve Saunders
Copyright © 2006 O'Reilly Media, Inc. All rights reserved.
Printed in the United States of America.
Published by O'Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O'Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available
for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800)
998-9938 or
Editor:

Simon St.Laurent, John Osborn

Production Editor:

Sanders Kleinfeld

Copyeditor:

Norma Emory

Indexer:

Ellen Troutman-Zaig


Cover Designer:

Karen Montgomery

Interior Designer:

David Futato

Illustrators:

Robert Romano, Jessamyn Read, and Lesley Borash

Printing History:
April 2006:

First Edition.

Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks of O'Reilly Media, Inc.
Programming Excel with VBA and .NET, the image of a shoveler duck, and related trade dress are trademarks of
O'Reilly Media, Inc.
Microsoft, the .NET logo, Visual Basic .NET, Visual Studio .NET, ADO.NET, Excel, Windows, and Windows 2000 are
registered trademarks of Microsoft Corporation.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks.
Where those designations appear in this book, and O'Reilly Media, Inc. was aware of a trademark claim, the
designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors assume no
responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.
ISBN: 0-596-00766-3
[M]



This document is created with a trial version of CHM2PDF Pilot


Preface
I was lucky enough to be at Microsoft when Visual Basic was added to Excel. I had just wrapped up working on OLE
Automationthe technology used to make Excel objects programmableand I remember that meetings with the Excel
group were, at times, difficult. Why should a premier Microsoft product like Excel put so much effort into adding a lowprofit item like Visual Basic when it already had a macro language?
"Because BillG said so" takes you only so far, even at Microsoft. The facts are that programmability doesn't sell
products the way some other whizbang feature might, it adds risk to delivering the product bug-free and on time, and
(we found out) it poses a security hazard.
What programmability does do is make your product a platform for others. Today, Excel is the foundation for probably
millions of small spreadsheet-based software solutions and is used by certainly thousands of very large and
sophisticated applications. That sells products.
It also makes the skill of programming Excel extremely valuable. The community of Excel programmers is large,
knowledgeable, and (I hope) well paid.

Learn by Doing
There are always new Excel programmers joining our ranks. If you are new to Excel or new to programming, I welcome
you. This book isn't a beginner series, but if you read the early chapters and are motivated, I think you'll find this book
a great way to learn a lot very quickly.
If you are an experienced Excel user or a Visual Basic programmer, howdy! I've got a lot to show you.

Don't Force It
If you get stuck, there are a number of ways to resume your progress:
Try turning on macro recording (Tools
Macros
Record a New Macro), performing the task in Excel,
and then turning off recording and examining the code that Excel generates.

Search MSDN ( to see if Microsoft has addressed your problem.
Search newsgroups ( to see if someone else has solved your problem.
And of course, you can always check to see if I've solved the problem!
If something still seems too difficult, examine your approach. I generally go fishing in that situation and come back to
the problem later. If you don't live somewhere with good fishing, I guess you're just stuck.

Excel Versions
This book was developed with Excel 2003 Professional Edition and is designed to be compatible with Excel 2000 and
later. If a feature is not available in Excel 2000, I make an effort to note that, but if you are developing for a specific
version of Excel, please check Appendix B for specific version compatibility and read Chapter 6 for information on
developing design requirements and testing for compatibility.
If you are developing with .NET, I strongly recommend that you target Excel 2003 or later. The code shown in this book
is written in the Visual Basic Applications Edition, but parallel .NET samples are provided online (see the next section).

Get the Samples
The samples for this book are available at . You'll need them, so go get them now. The
examples come in a Windows compressed folder (.zip) that you'll need to expand on your computer.
The samples are organized by chapter, and each chapter has parallel samples written as Visual Studio .NET projects.
Each chapter uses one main workbook (ch01.xls, ch02.xls, etc.) as a starting point to provide instructions and
navigation.

What's in This Book


This document is created with a trial version of CHM2PDF Pilot


Chapters in this book are organized by programming task. I cover the most common tasks for each subject within a
chapter. Subjects usually correspond to one or more Excel objects, and I include important reference information for
those objects within each chapter, rather than pushing that information to the back of the book.

I don't expect this book will be your only resource, and I try not to duplicate stuff you
already have (like online Help), so I include cross-references to other sources. I've also
included those resources as hyperlinks in the sample workbooks (see the Resources
sheet). Mostly, those links deal with much more specific issues related to the topic, but
they also include links to toolkits and other software you may need.

Here is a brief overview of each chapter:
Chapter 1, Becoming an Excel Programmer, is meant for those new to Excel programming. It covers how to
record, change, run, and debug code in the Excel Visual Basic Editor. Experienced Excel programmers can skip
this chapter, although they may want to read the section "Write Bug-Free Code."
Chapter 2, Knowing the Basics, explains the parts of a program: classes, modules, procedures, properties,
events, variables, constants, and all the other programming fundamentals. Experienced programmers might
want to skip right to "Objects" and "Exceptions" in this chapter.
Chapter 3, Tasks in Visual Basic, teaches how to use core Visual Basic features to display simple dialog boxes,
perform calculations, work with text, read and write files, check results, and run other applications. Experienced
readers will be most interested in the section "Compare Bits."
Chapter 4, Using Excel Objects, shows you how objects work and helps you find the right object for any given
task in Excel. The object diagrams in this chapter are a road map to the many objects that Excel provides. This
is the first place to look when searching for the appropriate object for a particular task.
Chapter 5, Creating Your Own Objects, goes in-depth about object-oriented programming (OOP). You'll learn
how to construct classes, methods, properties, collections, and events. I also explain why it is important to
destroy your creations once you are done using them.
Chapter 6, Writing Code for Use by Others, is about taking your skills to the next level. I cover the types of
applications you can create, explain the development process, and show how to properly deploy a completed
application.
Chapter 7, Controlling Excel, begins the task-specific part of this book. It shows how to use the top-level
Application object to open and close Excel windows, display dialogs, and get references to other Excel objects.
Chapter 8, Opening, Saving, and Sharing Workbooks, teaches you how to work with Excel document files
(workbooks). As a bonus, I cover how to work with XML and use SharePoint workspaces from Excel.
Chapter 9, Working with Worksheets and Ranges, covers the two most-used objects in Excel. Almost everything

you do in Excel involves worksheets and ranges in some way.
Chapter 10, Linking and Embedding, discusses how to add comments, hyperlinks, and objects from other
applications to a worksheet. I also show how to make Excel speak out loudweird but true!
Chapter 11, Printing and Publishing, is about sending output to the printer or the Web. I show how to control
paging, change printer settings, filter output, preview results, and publish ranges to a web page.
Chapter 12, Loading and Manipulating Data, is all about connecting to databases. I show how to use Query
Tables and use the ADO and DAO object models.
Chapter 13, Analyzing Data with Pivot Tables, shows how to program with one of Excel's most celebrated
features. I show how to reorganize data from a wide variety of data sources, including OLAP data cubes.
Chapter 14, Sharing Data Using Lists, goes into detail on one of Excel's newest features: data lists. I show how
to use them to sort, filter, and even share lists across the network through SharePoint.
Chapter 15, Working with XML, is also a ground-breaker, by showing how to convert XML datafiles into Excel
workbooks and vice versa. I provide a brief introduction to XML and XSL, then dive to the heart of how to
import XML data to lists through XML maps.
Chapter 16, Charting, covers how to create different types of charts and control the main parts of a chart.
Charting is a large and complex topic in Excel, so I also include a road map to the chart objects.


This document is created with a trial version of CHM2PDF Pilot

Charting is a large and complex topic in Excel, so I also include a road map to the chart objects.
Chapter 17, Formatting Charts, explains how to control the fonts, backgrounds, and 3-D effects used on a chart.
It is the companion to Chapter 16.
Chapter 18, Drawing Graphics, is really just for fun. Excel's drawing tools let you create diagrams and other
graphics from data, but you need to know about a couple gotchas. I cover those here.
Chapter 19, Adding Menus and Toolbars, helps you hook your application into the Excel user interface. I also
show how to distribute the menus and toolbars with your code.
Chapter 20, Building Dialog Boxes, is about creating data entry and User Forms to get input or display results to
users. I cover the controls included in the Microsoft Forms libraries here.
Chapter 21, Sending and Receiving Workbooks, shows all the ways to send email from Excel.

Chapter 22, Building Add-Ins, covers how to create and distribute your program as an Excel Add-In. This
chapter begins the advanced programming material.
Chapter 23, Integrating DLLs and COM, shows how to use code from Windows itself or other applications within
your Excel programs.
Chapter 24, Getting Data From the Web, explains how to scrape data from web pages using web queries and
how to execute web services to perform tasks remotely across a network.
Chapter 25, Programming Excel with .NET, teaches how to use .NET code from within Excel, use Excel code
from .NET, or integrate between Excel and .NET using Visual Studio Tools for Office (VSTO).
Chapter 26, Exploring Security in Depth, discusses Windows security, encryption, passwords, protection, and
Information Rights Management (IRM) within Excel. I also show how well (or poorly) certain security features
perform.

Font Conventions
This book follows certain conventions for font usage. Understanding these conventions up front makes it easier to use
this book.
Italic is used for:
Pathnames, filenames, program names, compilers, options, and commands
New terms where they are defined
Internet addresses, such as domain names and URLs
Constant width is used for:

Anything that appears literally in a Visual Basic program, including keywords, data types, constants, method
names, variables, class names, and interface names
Command lines and options that should be typed verbatim on the screen
All code listings
HTML documents, tags, and attributes
Constant width italic is used for:

General placeholders that indicate that an item is replaced by some actual value in your own program
Constant width bold is used for:


Text in code examples that is typed by the user
Highlighting code additions or changes that should be noted by the reader
This icon designates a note, which is an important aside to the nearby text.


This document is created with a trial version of CHM2PDF Pilot

This icon designates a note, which is an important aside to the nearby text.

This icon designates a warning relating to the nearby text.

Syntax Conventions
Books about computer languages require a way to express the kinds of information you need to provide on one or more
lines as you type. That is called the syntax of the language and Backus-Naur Form (BNF) is the format used in this book
and most others. In BNF notation, the following conventions apply:
Example

Meaning

Keyword

Roman (non-italic) words are keywords that must be typed exactly as shown.

Argument

Italics indicate an item you must provide, such as an object variable a setting.

[]


Square brackets indicate an optional item.

choice1 | choice2

A straight bar indicates a choice between two or more items.

{choice1 | choice2}

Braces indicate that you must choose one of the indicated settings.

[choice1 | choice2]

Square brackets indicate that the choice is optional.

These conventions are used in headings within the reference sections of this book and also within the text sometimes.
You'll also see them in the online help from Microsoft.

Using Code Examples
This book is here to help you get your job done. In general, you may use the code in this book in your programs and
documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the
code. For example, writing a program that uses several chunks of code from this book does not require permission.
Selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Answering a question by
citing this book and quoting example code does not require permission. Incorporating a significant amount of example
code from this book into your product's documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For
example: "Programming Excel with VBA and .NET, by Jeff Webb and Steve Saunders. Copyright 2006 O'Reilly Media,
Inc., 0-596-00766-3."
If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at



Safari® Enabled

When you see a Safari® Enabled icon on the cover of your favorite technology book, that means the
book is available online through the O'Reilly Network Safari Bookshelf.
Safari offers a solution that's better than e-books. It's a virtual library that lets you easily search thousands of top tech
books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate,
current information. Try it for free at .

How to Contact Us


This document is created with a trial version of CHM2PDF Pilot


Please address comments and questions concerning this book to the publisher:
O'Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the United States or Canada)
(707) 829-0515 (international or local)
(707) 829-0104 (fax)
We have a web page for this book, where we list errata, examples, or any additional information. You can access this
page at:
/>To comment or ask technical questions about this book, send email to:

For more information about our books, conferences, Resource Centers, and the O'Reilly Network, see our web site at:
/>
Acknowledgments
It takes a long time and a great deal of help to write a book this big. I would like to thank Steve Saunders for joining
the effort and contributing Chapters 9 and 12. Steve and I go back a very long way, through years at Microsoft and

Digital Equipment Corp. Steve's an Access expert and a great writer, and he sings well, too.
I'd also like to thank Simon St.Laurent for his work throughout the project. We've done four books together nowthat's
close to 2000 pages. Finishing this together is like climbing a mountain: his company improved the ascent and it's great
to stand with him here at the summit. Nice view.


This document is created with a trial version of CHM2PDF Pilot


Part I: Learning VBA
These chapters teach you how to write professional-quality code using Excel Visual Basic (VBA). This is
more than an entry-level tutorial to a macro language: it's a full set of lessons for readers who are
serious about programming. Once you've finished these chapters, you'll be ready to program Excel,
Word, or any other application that exposes objects to Visual Basic.
Chapter 1, Becoming an Excel Programmer
Chapter 2, Knowing the Basics
Chapter 3, Tasks in Visual Basic
Chapter 4, Using Excel Objects
Chapter 5, Creating Your Own Objects
Chapter 6, Writing Code for Use by Others


This document is created with a trial version of CHM2PDF Pilot


Chapter 1. Becoming an Excel Programmer
How do you become an excellent Excel programmer? The first step for most folks is to buy a book. I'm glad you bought
this one. Next, you've got to learn the programming tools that Excel provides. Visual Basic is ideally suited as a learning
tool because it lets you get started without a lot of pedagogical preparation. That's an alliterative way of saying that you
can learn the rules as you go.

So let's go!
Code used in this chapter and additional samples are available in ch01.xls.


This document is created with a trial version of CHM2PDF Pilot


1.1. Why Program?
Excel is a mature product with every imaginable featuredoesn't it do everything it needs to already? Excel is amazingly
complete, but programming Excel isn't really about adding new features as much as it is about combining existing
features to solve specific problems.
Excel is a platform for solving complex calculations and presenting results. Programming transforms that general
platform into a task-specific piece of software. The phrase task-specific piece of software is kind of a mouthful, and
most folks use the word solution instead. In my opinion, that's awfully vague but probably better than a new acronym.
The reason to program Excel is to make some task easier or more reliable. Programming languages make things easier
because they are great at performing repetitive operations and following a logical path without getting tired or bored.
They make things more reliable because they slavishly follow your directions and never, ever get creative.
Having such a devoted servant comes with a lot of responsibility, however. For instance, if you tell Excel to "lather,
rinse, repeat" like it says on the back of a shampoo bottle, it's liable to scrub the hair right off your head since you
never told it when to stop repeating. (Hint: if that ever happens to you, press Ctrl-Break and step out of the shower.)
You need to understand the basic rules common to all programming languages before you can write real programs in
Excel (see Chapter 2). That's kind of dry stuff, though, so right now I'm going to jump ahead to something more fun.


This document is created with a trial version of CHM2PDF Pilot


1.2. Record and Read Code
The best way to learn about Excel objects, properties, and methods is by recording code . It's even better than online
Help. Recording will almost always tell you what you need to know if you know how to use it. When Excel records code,

it translates your actions into Visual Basic code. This lets you reverse-engineer recorded actions or simply cut and paste
recorded actions into other procedures.
For example, suppose that you have a workbook containing multiple sheets of sales data as shown in Figure 1-1. You
want to format the data on each of the sheets and add a chart comparing units sold and revenue. This is a great
opportunity to record some code.

Figure 1-1. An example for recording code

To record your code:
1. Choose Tools

Macros

Record New Macro. Excel displays the Record Macro dialog (Figure 1-2).

Figure 1-2. Step 1


This document is created with a trial version of CHM2PDF Pilot


2. Select the range A1:C16 and choose Format
3).

AutoFormat. Excel displays the AutoFormat dialog (Figure 1-

Figure 1-3. Step 2

3. Select the Simple format and click OK. Excel formats the range.
4. Press Shift-Up to deselect the Total row and then choose Insert

(Figure 1-4).

Figure 1-4. Step 4

Chart. Excel displays the Chart Wizard


This document is created with a trial version of CHM2PDF Pilot


5. Click Finish to insert a chart on the sheet as shown in Figure 1-5.
6. Finally, choose Tools

Macro

Stop Recording to turn off recording.

Now you could repeat this task by selecting one of the other worksheets and run the recorded code by pressing Alt-F8
and running Macro1, but the data would have to be in the same location on the active worksheet and the new chart
would appear on the 2002 worksheet, not the active one. Instead, press Alt-F8 and click Edit. Excel starts the Visual
Basic Editor (VBE) and displays your recorded code, as shown here:
Sub Macro1( ) '<---------- Name of procedure.
'
' Macro1 Macro <----------- Comments describing procedure.
' Macro recorded 5/26/2004 by Jeff
'
'
Range("A1:C16").Select '<---- Following lines record what you did.
Selection.AutoFormat Format:=xlRangeAutoFormatSimple, Number:=True, Font _
:=True, Alignment:=True, Border:=True, Pattern:=True, Width:=True

Range("A1:C15").Select
Charts.Add

ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData Source:=Sheets("2002").Range("A1:C15"), PlotBy:= _
xlColumns
' Long lines are continued using an underscore ---------^
ActiveChart.Location Where:=xlLocationAsObject, Name:="2002"
End Sub
'<---------- End of procedure.

Figure 1-5. Step 5

I added some labels in the recorded code to identify its parts:


This document is created with a trial version of CHM2PDF Pilot

I added some labels in the recorded code to identify its parts:
Each procedure in a workbook has a unique name. Excel assigns the names Macro1, Macro2, and so on to
recorded code.
Anything that appears after ' is a comment. Comments are descriptive text that don't run as code.
Lines of text that aren't comments are executable statements . Statements tell Visual Basic what to do in Excel.
Lines that are longer than about 80 characters are continued on the next line using the _ character. Excel does
that for readability. Actually, Visual Basic allows lines of code to be much longer if you don't mind horizontal
scrolling.
Procedures always include an End statement to tell Visual Basic where to stop.
So now that you've recorded code, what can you do with it? That's up next.



This document is created with a trial version of CHM2PDF Pilot


1.3. Change Recorded Code
Recorded code is a great way to learn, but it's not really a program. Real programs are much more flexible, and
recorded code always has the following limitations:

Follows a linear path
Excel can't infer logic from the user's actionseven if the user repeats an action, Excel only records the action
twice. It doesn't know how to record "repeat until end" or "do this task if..." Excel can "replace all" and perform
other global actions, but that's still linear logic.

Actions apply to the active item
Excel bases recorded actions on whatever worksheet, range, or chart is currently selected by the user. If you
want your code to work with other sheets or ranges, you need to either change the active selection or add
object references that tell the code which items to work with.

Uses cell addresses
For example, Range("A1:C16"). Although Excel keeps references on worksheets up-to-date, Excel can't update
addresses in code. That means if your data is moved on the worksheet, the code won't work correctly. To fix
this, use Excel range properties or named ranges instead of addresses in code.

Methods include all the default arguments
That means lines of code are sometimes longer and more complicated than they really need to be. You can
often simplify recording by removing unneeded default arguments.

Doesn't use variables
Most programs create names to identify things that can change as the code executes. These names are called
variables. Recorded code doesn't use variables because the logic is always linearvariables are required only if
the code repeats or makes decisions.

So if you want the code you just recorded to repeat the formatting and charting tasks for all worksheets in your
workbook, you'll need to make a few changes. I'll do that in a number of steps so it's clearer. First, add the logic to
repeat the formatting for each worksheet:
Sub Macro1( )
'
' Macro1 Macro
' Macro recorded 5/26/2004 by Jeff
'
'
For Each ws In Worksheets '<--- Added to repeat actions for each worksheet.
Range("A1:C16").Select
Selection.AutoFormat Format:=xlRangeAutoFormatSimple, Number:=True, Font _
:=True, Alignment:=True, Border:=True, Pattern:=True, Width:=True
Range("A1:C15").Select
Charts.Add
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData Source:=ws.Range("A1:C15"), PlotBy:= _
xlColumns
ActiveChart.Location Where:=xlLocationAsObject, Name:=ws.Name '"2002"
' Change Name to match the worksheet's name ----------^
Next '<--- End of actions to repeat.
End Sub

The preceding For Each statement tells Excel to repeat the following task for every worksheet in the workbook. The Next
statement ends the set of tasks to repeat. In programming, this kind of logic is called a loop because the flow of
execution runs around and around in a circle until told to stop. In this case, the loop stops after it reaches the last
worksheet in the workbook.


This document is created with a trial version of CHM2PDF Pilot


worksheet in the workbook.
There's something subtle about the previous code: the For Each statement gets a reference for each worksheet as it
loops and stores it using the name ws. We need to use that name (called a variable) to get the location where Excel
should insert the chart. Thus, ws replaces Sheets("2002"), so each time Excel creates a chart, it inserts it on the right
worksheet. Remember to search for literal references like this and replace them with variables any time you are adding
logic to recorded code.
That was step 1, adding logic. If you run the code now, Excel will repeat the task for each worksheet in your workbook
and it will work correctly as long as each worksheet has its sales figures in the range A1:C16. If that's not the case, the
code won't format or chart the right range. To handle data in other locations, change Range("A1:C16") to use Excel's
UsedRange property as shown here:
Sub Macro1b( )
'
' Macro1b Macro
' Change absolute ranges to relative ones.
'
'
For Each ws In Worksheets
'Range("A1:C16").Select
Set rng = ws.UsedRange '<-- Get all the cells with data.
'Selection.AutoFormat Format:=xlRangeAutoFormatSimple, Number:=True, Font _
' :=True, Alignment:=True, Border:=True, Pattern:=True, Width:=True
' Use reference (below) rather than Selection (above).
rng.AutoFormat Format:=xlRangeAutoFormatSimple, Number:=True, Font _
:=True, Alignment:=True, Border:=True, Pattern:=True, Width:=True
'Range("A1:C15").Select
' Remove the last row (Total) from the range.
Set rng = ws.Range(ws.Cells(rng.Row, rng.Column), _
rng.SpecialCells(xlCellTypeLastCell).Offset(-1, 0))
Charts.Add

ActiveChart.ChartType = xlColumnClustered
'ActiveChart.SetSourceData Source:=Sheets("2002").Range("A1:C15"), PlotBy:= _
' xlColumns
ActiveChart.SetSourceData Source:=rng, PlotBy:=xlColumns
' Use the range reference here ----^
ActiveChart.Location Where:=xlLocationAsObject, Name:=ws.Name
Next
End Sub

UsedRange was introduced in Excel 97, and it is one of those incredibly useful properties that

you'll be seeing over and over again.

The preceding changes use the UsedRange property to get all the cells on the worksheet that contain data. The hard part
comes with the second change that removes the Total row from the range to chart:
Set rng = ws.Range(ws.Cells(rng.Row, rng.Column), _
rng.SpecialCells(xlCellTypeLastCell).Offset(-1, 0))

Wow, that's complicated! To break it down a bit, ws.Cells (rng.Row, rng.Column) gets the first cell in the range, and
rng.SpecialCells(xlCellTypeLastCell).Offset(-1, 0) gets the last cell minus one row (omitting the Total row). The enclosing
ws.Range(...) method combines those start and end points into a rectangular block of cells. Don't worry if you don't
completely understand at this point; you'll find much more material on working with ranges of cells in later chapters.
Finally, I changed the chart's Source argument to use this new range. Now if you run the code, Excel will format and
chart sales data on each of the worksheets regardless of where the data is on each worksheet. The code is still a bit
rough, though, because it doesn't declare the variables it uses, it includes some arguments that aren't really needed,
and it is still named Macro1, which isn't descriptive at all. Here's a cleaned-up version with all the fixes:
Sub FormatAndChart( )
' AutoFormats and Charts all of the worksheets in a workbook.
' Designed to work with Sales Data tables.
' 5/28/04 by Jeff Webb

'
Dim rng As Range, ws As Worksheet
' Repeats actions for all Worksheets in the workbook.
For Each ws In Worksheets


This document is created with a trial version of CHM2PDF Pilot

For Each ws In Worksheets
' Get the cells with data in them.
Set rng = ws.UsedRange
' Apply AutoFormat
rng.AutoFormat Format:=xlRangeAutoFormatSimple
' Omit the Total row from the range.
Set rng = ws.Range(ws.Cells(rng.Row, rng.Column), _
rng.SpecialCells(xlCellTypeLastCell).Offset(-1, 0))
' Create a chart.
Charts.Add
' Set chart properties.
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData Source:=rng, PlotBy:=xlColumns
' Insert the chart on the worksheet.
ActiveChart.Location Where:=xlLocationAsObject, Name:=ws.Name
Next
End Sub

Declaring the variables enables handy Visual Basic features like Auto Complete (I discuss
that later).

You might notice that I also rewrote the comments in this final version. It's always a good idea to write out in words

what your code is doing. Even if the code is only for your personal use, it's surprising how easy it is to forget what you
did.


This document is created with a trial version of CHM2PDF Pilot


1.4. Fix Misteakes
Mistakes are a fact of life, and Visual Basic is fairly intolerant of them. If you followed along with the preceding lab, you
probably already encountered that fact. Sometimes it's pretty easy to tell what you've done wrong, and sometimes it's
almost impossibleeven for experienced programmers! What marks the difference between beginning and expert
programmers is how they go about solving those problems.
To help you understand fixing mistakes, you need to know that there are four different kinds of errors that are
generally identified by where or why they happen:

Syntax errors
Occur when you mistype a statement, such as omitting a closing parenthesis or omitting some part of the
statement that is required. Visual Basic detects these errors right away and highlights them in red as soon as
you move to the next line of code.

Semantic errors
Are also often the result of a typo, but they appear valid to Visual Basic as you type. Examples of this kind of
error include misspelling a method or property name or using a variable or procedure name that isn't defined
yet. Visual Basic checks for these errors the moment you run your code (for instance, when you press F5). At
that point, Visual Basic converts your code into a form that Excel understands (this is called compiling), and if
any of the names you used aren't found, compiling stops and Visual Basic highlights the error. Semantic errors
are sometimes called compile-time errors for that reason.

Logic errors
Can be the hardest to detect. These errors occur when your code simply doesn't do what you expected it to do.

Infinite loops (lather, rinse, repeat...) are an example, as are unexpected results such as formatting code that
doesn't format everything it should. Logic errors can sometimes halt your code while it is running, and for that
reason they are often called runtime errors .

Expected errors
Aren't your fault, but you need to deal with them all the same. These are another type of runtime error, and
they are usually the result of using resources outside of Excel, such as trying to get a file from disk or trying to
connect to a database somewhere. In those cases, you need to anticipate the possibility of a problem using a
technique called exception handling (which I cover in Chapter 2).
The real name for expected errors is exceptions . (Since you expect them, they aren't really errors, are they?)
For now, let's look at fixing the errors that are your fault.

1.4.1. Fix Syntax Errors
Visual Basic can detect many kinds of typos as you move from line to line in the code window. This is the most common
type of error you'll make as you learn programming. Fortunately, Visual Basic can generally tell what you did wrong, as
shown in Figure 1-6.

Figure 1-6. Visual Basic stops you when you make a syntax error


×