definitive guide to excel vba, second edition978-1-4302-0666-8/1.pdf · definitive guide to excel...
TRANSCRIPT
Definitive Guide to Excel VBA, Second Edition
MICHAEL KOFLER TRANSLATED BY DAVID KRAMER
APress Media, LLC
Definitive Guide to Excel VBA, Secend Edition Copyright ©2003 by Michael Kofler Originally published by Apress in 2003
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.
ISBN 978-1-59059-103-1 ISBN 978-1-4302-0666-8 (eBook) DOI 10.1007/978-1-4302-0666-8
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 intendon of infringement of the trademark.
Translator and Editor: David Kramer
Editorial Board: Dan Appleman, Craig Berry, Gary Cornell, Tony Davis, Steven Rycroft, Julian Skinner, Mardn Streicher, Jim Sumser, Karen Watterson, Gavin Wright, John Zukowski
Assistant Publisher and Project Manager: Grace Wong
Copy Editor: Rebecca Rider
Producdon Manager: Kari Brooks
Producdon Editor: Janet Vail
Proofreader: Lori Bring
Compositor: Diana Van Wmkle, vwdesign.com
Indexer: Kevin Broccoli
Cover Designer: Kurt Krames
Manufacturing Manager: Tom Debolski
In the United States: phone 1-800-SPRlNGER, email orders@springer -ny. com, or visit http: 1 lwww. springer-ny. com. Outside the United States: fax +49 6221 345229, email orders@springer. de, or visit http: I lwww. springer. de.
For informadon on translations, please contact Apress directly at 2560 Ninth Street, Suite 219, Berkeley, CA 94710. Phone 510-549-5930, fax 510-549-5939, email [email protected], or visit http: I lwww. apress. com.
The information in this book is distributed on an "as is" basis, without warranty. Although every precaudon has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liabillty to any personor endty with respect to any loss or darnage caused or alleged to be caused directly or indirectly by the informadon contained in this work.
Contents at a Glance
Preface ............................................................ ....................................................... xzzz The Idea Behind This Book ............................................................................. xv
Part One An Intuitive Approach .................................................................................. 1
Chapter 1
Chapter 2
Part Two
Writing Your First Macro ................................................... 3
What)s New in Excel 2000 ................................................ .47
Fundamentals ...................................................................................................... 65
Chapter 3 Chapter 4 Chapter 5 Chapter 6
Chapter 7
Chapter 8
Part Three
The Development Environment ........................................... 67
VBA Concepts ............................................................................ 85
Techniques of Programming ............................................. 185
Debugging) Protection When Errors Arise ............... 371
Forms (Microsoft Forms Library) ................................ 387
Menus and Toolbars ............................................................. 457
Application ...................................................................................................... 493
Chapter 9 Templates) Smart Forms .................................................... 495
Chapter 10 Charts and Drawing Objects (Shapes) ........................ 527
Chapter 11
Chapter 12
Chapter 13 Chapter 14
Part Four
Data Management in Excel ............................................... 569
Access to External Data .................................................. 619
Data Analysis in Excel .................................................... 687
VBA Programming for Pros ................................................ 731
Reference ........................................................................................................... 791
Chapter 15 Object Reference ................................................................. 793
Appendix Excel 2003 Beta 2 ................................................................ 863
References ............................................................................................................ 879
Index ...................................................................................................................... 881
üi
Contents
Preface ........................................................................................................... ........ xiii
The Idea Behind This Book ............................................................................. xv
Part One An Intuitive Approach .................................................................. 1
Chapter 1 Writing Your First Macro .......................................... 3
1.1 Definition of Terms .................................................................................. 4
1. 2 What Is Visual Ba sie for Applications? ......................................... 6
1.3 Linking a Custom Style with a Tool .................................................. 9
1.4 A Macro for Simplifying Input .......................................................... 15
1.5 A Simple Literature Database ............................................................ 17 1. 6 A Form for Computing Interest in a Savings Account ............. 24 1. 7 User-Defined Functions .......................................................................... 30
1.8 Analysis of Complex Tables ................................................................. 31
1. 9 A Vocabulary Tutor .................................................................................. 32 1.10 Example Programs for You to Try .................................................... 40
Chapter 2 What~s New in Excel 2000 ....................................... .47
2.1 New in Excel 2002 ..................................................................................... 48
2. 2 New in Excel 2000 .................................................................... " ............... 51 2.3 New in Excel 97 ........................................................................................ ,54 2. 4 New in Excel 7 .......................................................................................... ,59
2. 5 Problems and Incompatibilities ........................................................ 59
V
Contents
Part Two Fundamentals ............................................................................................. 65
Chapter 3 The Development Environment ................................. 67
Chapter Overview ................................................................................................ 67 3.1 The Components of a VBA Program ...................................................... 68 3. 2 The Components of the Development Environment ....................... 69
Object Browser ................................................................................................. 72 3. 3 Code Input in Modules ............................................................................ 76 3.4 Executing Macros ....................................................................................... 80 3. 5 Recording Macros ....................................................................................... 82 3. 6 Keyboard Shortcuts .................................................................................. 83
Chapter 4 VBA Concepts ........................................................................ 85
4.1 Variables and Fields .............................................................................. 86 ManagingVariables .......................................................................................... 86 Syntax Summary ............................................................................................... 95
4.2 Procedural Programming .......................................................................... 97 Procedures and Parameters ............................................................................. 97 Realm ofValidity ofVariables and Procedures ............................................. 107 Branching (Tests) ........................................................................................... 112 Loops ............................................................................................................... 115 Syntax Summary ............................................................................................. 119
4.3 Objects ......................................................................................................... 123 Workingwith Objects, Methods, and Properties ......................................... 123 The Object Browser (References) .................................................................. 129 Accessing Objects Clarified with Keyword With .......................................... 134 ObjectVariables .............................................................................................. 135 Syntax Summary ............................................................................................. 138
4.4 Events ........................................................................................................... 139 Event Procedures ............................................................................................ 140 Overview of Important Excel Events ............................................................. 144 Receiving Events of Arbitrary Objects ........................................................... 150 Generating Event Procedures with Program Code ...................................... 152 Syntax Summary ............................................................................................. 156
4.5 Programming Your Own Classes ........................................................... 159 Custom Methods, Properties, and Events .................................................... 161 Collection Object ............................................................................................ 165 Example for a Class Module .......................................................................... 167
vi
Contents
Example for Derived Classes (Implements) ................................................. 168
Syntax Summary .............................................................................. ............... 173
4.6 Operators in VBA ..................................................................................... 175
4. 7 Virus Protection ..................................................................................... 178
Chapter 5 Techniques of Programming ..................................... 185
5.1 Cells and Ranges of Cells ................................................................. 186
Objects, Methods, Properties ........................................................................ 186
ProgrammingTechniques .............................................................................. 201
Syntax Summary ............................................................................. ................ 212
5. 2 Workbooks, Windows, and Worksheets .............................................. 215
Objects, Methods, and Properties ................................................................. 215
Programming Techniques .......................................................... .................... 221
Syntax Summary .......................................................................................... ... 226
5. 3 Data Transfer via the Clipboard .................................................... 228
Copying, Cutting, and Pasting Ranges of Cells ......................................... ... 228
Access to the Clipboard with the DataObject .............................................. 230
Syntax Summary .......................................................................................... ... 231
5.4 Warking with Numbers and Character Strings ............................ 232
Numerical Functions, Random Numbers ............................................ ........ 232
Character Strings ........................................................................................... . 235
Transformation Functions ............................................................................. 241
Syntax Summary .......................................................................................... ... 243
5.5 Warking with Dates and Times ........................................................... 246
VBA Functions ...................................................................................... .......... 250
Worksheet Functions ..................................................................... ................ 253
Application and Programming Techniques ................................................ . 254
Holidays .................................................................................................... ...... 257
Syntax Summary ............................................................................... .............. 265
5.6 Warking with Files; Text Import and Export ............................ 267 File System Objects: An Overview ................................................................. 267
Drives, Polders, and Files .............................................................................. . 269
Text Files (TextStream) ........................................................................... ........ 276
Binary Files (Open) ......................................................................................... 278
Excel-Specific Methods and Properties ........................................................ 283
Importing and Exporting Text Files ................................................... .......... .286
Text Exportation for Mathematica Lists ..................................................... .. 296
Syntax Summary ............................................................................................. 301
5. 7 User-Defined Worksheet Functions .................................................. 306
Fundamentals ................................................................................................. 306 Examples ......................................................................................................... 314
vii
Contents
5. 8 Protection Mechanisms .......................................................................... 317 Restricting the Field of Action ....................................................................... 318 Protecting Cells and Worksheets from Changes .......................................... 319 Protection Mechanism for Shared Workbooks ............................................ 324 Protecting Program Code and ToolBars .............................................. ......... 324 Syntax Summary ......................................................................................... .... 326
5.9 Configuration Files, Custom Configuration .............................. 327 Options ..................................................................................................... ....... 327 Setting Options with Program Code ............................................................ . 328 Configuration Files ....................................................................................... .. 332
5.10 Excel Meets the Euro .......................................................................... 339 The Euroconvert Function ...................................................................... ...... 340 Converting Excel Files to the Euro ................................................................ 343
5.11 Tips and Tricks ..................................................................................... 356 Speed Optimization ....................................................................................... 356 Time-Intensive Calculations ...................................................................... ... 357 Warking Efficiently with Worksheets ............................... ............................. 362 Interplay with Excel-4 Macras ....................................................................... 365 Determining the Version of Excel ................................................................ .. 366 HelpingYou to Help Yourself ......................................................................... 366 Syntax Summary ........................................................................................... .. 368
Chapter 6 Debugging~ Protection When Errors Arise .. 371
Chapter Overview .............................................................................................. 371 6.1 Debugging Aids ......................................................................................... 372
Syntax Control ................................................................................................ 372 Reaction to Errors ........................................................................................... 373 Contralied Program Execution ...................................................................... 376
6.2 Error- Tolerant Behavior of Programs ........................................... 380 6.3 Response to Program Interrupts ...................................................... 385 6. 4 Syntax Summary ......................................................................................... 386
Chapter 7 Forms (Microsoft Forms Library) ..................... 387
7.1 Predefined Dialogs ................................................................................ 388 Standard Excel Dialogs ................................................................................... 388 The Functions MsgBox and InputBox ........................................................ .. 392 The Method Application.InputBox ............................................................. .. 393
7. 2 User-Defined Forms ................................................................................ 395 Changes with Respect to ExcelS/7 ............................................................... 396 Introductory Example ....................................................................... ............. 398
vili
Contents
7.3 The Form Editor ....................................................................................... 402 7. 4 The MS Forms Controls .......................................................................... 406
Label ................................................................................................................ 408 TextBox ............................................................................................................ 409 ListBox and ComboBox .................................................................................. 412 Check Box and OptionButton ....................................................................... 419 Command Buttons and Toggle Buttons ...................................................... .421
Frames ............................................................................................................. 422 MultiPage, TabStrip ........................................................................................ 424 Scrollbar and SpinButton .............................................................................. 429 Image ............................................................................................................... 431 Formulas (RefEdit) ......................................................................................... 432 The UserForm Object ..................................................................................... 434
7.5 Placing Controls Directly into Worksheets ............................. .438
7. 6 Programming Techniques ....................................................................... .447 Numerical Input ............................................................................................. 447 Reciprocal Calling ofForms ........................................................................... 449 Editing Forms Dynamically ........................................................................... 451 Working with Spin Buttons ............................................................................ 453
Chapter 8 Menus and Toolbars ...................................................... .457
8.1 Menu Bars and Toolbars ........................................................................ 458 Manual Editing of Menus and Toolbars ....................................................... .458 Saving Changes ............................................................................................... 464 Object Hierarchy ............................................................................................ 466 ProgrammingTechniques .............................................................................. 472 Changing Sheets via a Toolbar ...................................................................... 479 Differences Compared to Excel5/7 ............................................................. .482 Syntax Summary ............................................................................................. 483
8.2 Formatting the Interface for Freestanding Excel Applications ......................................................................................... 485
Extending the Standard Menu ....................................................................... 486 Hiding and Unhiding Custom Toolbars ....................................................... .489
Using a Custom Standard Menu ................................................................... 490
ix
Contents
Part III Application .............................................................................................. 493
Chapter 9 Templates, Smart Forms .......................................... .495
9.1 Fundamentals .............................................................................................. 496 Design Elements for Smart Forms ................................................................ 497 Templates Linked to Databases ................................... ................................. 505
9. 2 Example: The ((SpeedyJJ Invoice Form .............................................. 509
9.3 Example: Balance Sheet for a Car-Sharing Club ..................... 518
9.4 The Limits of Smart Forms ................................................................. 525
Chapter 10 Charts and Drawing Objects (Shapes) ........... 527
10.1 Charts ......................................................................................................... 528 Fundamentals ................................................................................................. 528 Chart Types ..................................................................................................... 529 Chart Elements (Chart Objects) and Formatting Options .......................... 530
Printing ............................................................................................................ 534 10.2 Programming Charts .............................................................................. 535
Object Hierarchy ............................................................................................ 536 ProgrammingTechniques .............................................................................. 540
10.3 Example: Automatie Data Reporting .............................................. 544
Using the Example Program ......................................................................... . 544
Program Code ................................................................................................. 547 10.4 Syntax Summary for Charts ............................................................... 558 10.5 Drawing Objects (Shapes) ................................................................. 560 10.6 Diagrams .................................................................................................... 565
Chapter 11 Data Management in Excel ....................................... 569
11.1 Fundamentals ........................................................................................... 570
Introduction: What Is a Database? ................................................................ 570 ABrief Database Glossary .............................................................................. 571 Excel Versus Database Systems ................................................................. .... 572
11.2 Data Management Within Excel ........................................................ 575 Creating a Database in Excel ......................................................................... 576 Input, Alteration, and Deletion of Data with the Database Form .............. 579
Sorting, Searching, and Filtering Data .............................. ............................ 581
11.3 Data Processing in VBA Code ........................................................... 588 Programming Techniques .............................................................................. 588
X
Contents
Example: A Form Letter in Microsoft Word .................................................. 591
Syntax Summary ............................................................................................. 594
11.4 Database Worksheet Functions ........................................................ 595
11.5 Consolidating Tables .......................................................................... 599
Fundamentals ................................................................................................. 599
Consolidation via VBA Code .......................................................................... 601
11.6 Example: Balance Sheet for a Car-Sharing Club ................... 602
Running the Program ..................................................................................... 603
Overview of the Components of the Application ........................................ 607
Program Code ................................................................................................. 608
Chapter 12 Access to External Data .......................................... 619
12.1 Fundamental Concepts About Relational Databases ............... 620
12.2 Importing External Data ................................................................... 626
Importing Data from Databases (MS Query) ............................................... 627
The QueryTable Object .................................................................................. 639
Exporting Excel Data ...................................................................................... 643
12.3 Database Access with the ADO Library ....................................... 645
Introduction .................................................................................................... 645
Connections .................................................................................................... 650
Recordset ......................................................................................................... 654
SQL Commands (Command) ........................................................................ 662 SQL Basics ....................................................................................................... 663
Syntax Summary ............................................................................................. 666
12.4 Example: Evaluating a Questionnaire ......................................... 669 Overview ......................................................................................................... 669
Construction ofthe Database ....................................................................... 674 Program Code ................................................................................................. 675
Chapter 13 Data Analysis in Excel ............................................ 687
13.1 Grouping Data (Subtotals) ............................................................... 688
Introducdon .................................................................................................... 688
Programming .................................................................................................. 689
13.2 Pivot Tables ........................................................................................... 692
Introduction .................................................................................................... 692
Layout Options ............................................................................................... 697
Pivot Tables for External Data ....................................................................... 703
Pivot Table Options ........................................................................................ 708
Pivot Charts ..................................................................................................... 709
xi
Contents
13.3 Programming Techniques ...................................................................... 710 Generating and Deleting Pivot Tables .......................................................... 711
Construction and Reconstruction of Existing Pivot Tables ......................... 716 Internal Management (PivotCache) ............................................................. 720
Syntax Summary ............................................................................................. 728
Chapter 14 VBA Programming for Pros ....................................... 731
14.1 Add-Ins ....................................................................................................... 732
14.2 Excel and the Internet ...................................................................... 737
Sending Excel Files as E-Mail ........................................................................ 737
HTML Import ................................................................................................. 739
HTML Export, Web Components .................................................................. 740
14.3 Smart Tags ................................................................................................ 744
14.4 Using Web Services .............................................................................. 747
14.5 Using Dynamic Link Libraries (DLLs) ......................................... 754
14.6 ActiveX Automation ............................................................................. 759
Excel as Client (Controlling External Programs) .......................................... 761
Excel as Server (Control by an External Pro gram) ....................................... 767 New Objects for Excel ( ClipBoard Example) ................................................ 772 Object Linking and Embedding (OLE) ......................................................... 775
Automation and Visual Basic .NET ............................................................... 780 Launehing and Controlling Programs Without ActiveX .............................. 786 Syntax Summary ............................................................................................. 789
Part Four Reference ..................................................................................................... 791
Chapter 15 Object Reference ............................................................ 793
15.1 Object Hierarchy ................................................................................... 794
15. 2 Alphabetical Reference ...................................................................... 801
Appendix Excel 2003 Beta 2 ......................................................... 863
References ........................................................................................................ 879
Index .................................................................................................................... 881
xii
Preface
ExCEL OPFERS RIGHT OUT OF THE BOX an enormaus 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 Excel97, the VBA programming modeland the most important object libraries became fairly stable. Excel 2000 and 2002 introduced a hast 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 Excel97). The
most important innovations are the Scripting and ADO libraries, both of which have been available since Excel2000, simplifying access to files, directories, and
extemal 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 sametime in 2003 will not be based on .NET, according to
current ward from Microsoft. But that is no reason for tears. If Microsoft were
xiii
Preface
xiv
someday to decide actually to convert the Officesuite to .NET and the new pro
gramming 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 Excel2000 and 2002 without compatibility problems. The
Web Services Toolkit, a simple and freely distributed extension of the VBA devel
opment environment, makes this possible. (Details on the use of this toolkit
appear in Chapter 14.)
Why This Book?
The real problern in VBA programming is not VBA itself. The formulation of a loop
ortest, the use of methods and properties, are easily understood as in any pro
gramming language and will cause you no trouble after a couple of days. The
problern 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.
In cantrast to Excel's Help, the goal of this book is not to offer merely a refer
ence-often one that says next to nothing-of 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 pointout problems with Excel where they exist, in order to spare you, the
reader, from a fruitless search for errors ofwhich 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 gatten 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
The Idea Behind This Book
VrsuAL BASIC FOR APPUCATIONS is, to be sure, a modern object -oriented programming language that offers an incredible number ofkeywords, but at the sametime it offers many difficulties. At the beginning one has no hope of gaining even an overview ofVBA. 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, a11 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 a11 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
Keyboardshortcuts are given in the form Ctri+F2. Menu commands appear as follows: FrLEIÜPEN, CA.NcEL, or OK. The instruction EorriDELETEISHIFI' cells left means that you first execute the menu command EorriDELETE and then in the dialogthat appears select the button Shift cells left.
XV
The Idea Behind This Book
xvi
VBA keywords as weil as variables and procedures are written in italics, for
example, "Application object" or "Visible property." Worksheet functions are writ
ten 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 work
sheet functions must be given in the locallanguage.) Keywords that appear in the
text for the firsttime with an explanation orthat are particularly important are
printed in hold italics.
The Example Files
The example flies for this book are available at http: I lwww. 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 Excel2002.
In any case, they are the same. Excel2002 = Excel XP. This book uses the names
Excel2002 and Office 2002.