Tải bản đầy đủ (.pdf) (458 trang)

excel programming weekend crash course®

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 (11.08 MB, 458 trang )

Excel Programming
Weekend Crash Course
®
Peter G. Aitken
540629 FM.qxd 9/2/03 4:10 PM Page i
540629 FM.qxd 9/2/03 4:10 PM Page x
Excel Programming
Weekend Crash Course
®
Peter G. Aitken
540629 FM.qxd 9/2/03 4:10 PM Page i
Excel Programming Weekend Crash Course®
Published by
Wiley Publishing, Inc.
909 Third Avenue
New York, NY 10022
www.wiley.com
Copyright © 2003 by Wiley Publishing, Inc., Indianapolis, Indiana. All rights reserved.
Library of Congress Cataloging-in-Publication Data: 2003101920
ISBN: 0-7645-4062-9
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
1O/RR/QY/QT/IN
Published by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or
by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permit-
ted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written
permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the
Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978)


646-8700. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley
Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447,
E-Mail:

.
Limit of Liability/Disclaimer of Warranty: While the publisher and author have used their best efforts
in preparing this book, they make no representations or warranties with respect to the accuracy or com-
pleteness of the contents of this book and specifically disclaim any implied warranties of merchantability
or fitness for a particular purpose. No warranty may be created or extended by sales representatives or
written sales materials. The advice and strategies contained herein may not be suitable for your situa-
tion. You should consult with a professional where appropriate. Neither the publisher nor author shall be
liable for any loss of profit or any other commercial damages, including but not limited to special, inci-
dental, consequential, or other damages.
For general information on our other products and services or to obtain technical support, please contact
our Customer Care Department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993 or fax
317-572-4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may
not be available in electronic books.
Trademarks: Wiley, the Wiley Publishing logo and Weekend Crash Course are trademarks or registered
trademarks of Wiley Publishing, Inc. in the United States and other countries and may not be used with-
out written permission. All other trademarks are the property of their respective owners. Wiley
Publishing, Inc., is not associated with any product or vendor mentioned in this book.
is a trademark of Wiley Publishing, Inc.
540629 FM.qxd 9/2/03 4:10 PM Page ii
About the Author
Peter G. Aitken has been writing about computers and programming for over 10 years, with
some 30 books as well as hundreds of magazine and trade publication articles to his credit.
His recent book titles include Visual Basic .NET Programming with Peter Aitken, Office XP
Development with VBA, XML the Microsoft Way, Windows Script Host, and Teach Yourself Visual
Basic .NET Internet Programming in 21 Days. For several years he was a Contributing Editor

at Visual Developer Magazine where he wrote a popular Visual Basic column. He is a regular
contributor to Microsoft OfficePro magazine and the DevX Web site. Peter is the proprietor of
PGA Consulting, providing custom application and Internet development to business, acade-
mia, and government since 1994.
540629 FM.qxd 9/2/03 4:10 PM Page iii
Credits
Acquisitions Editor
Jim Minatel
Project Editor
Mark Enochs
Technical Editor
Ken Slovak
Copy Editor
Susan Hobbs
Permissions Editor
Laura Moss
Media Development Specialist
Travis Silvers
Project Coordinator
Maridee Ennis
Graphics and Production Specialists
Beth Brooks, Sean Decker, Carrie Foster,
Lauren Goddard, LeAndra Hosier,
Kristin McMullan, Lynsey Osborn
Quality Control Technicians
Laura Albert, John Tyler Connoley,
John Greenough, Andy Hollandbeck,
Carl William Pierce, Dwight Ramsey,
Charles Spencer
Proofreading and Indexing

TECHBOOKS Production Services
540629 FM.qxd 9/2/03 4:10 PM Page iv
M
icrosoft Excel is a powerful spreadsheet program; in fact, it’s the most widely used
spreadsheet program worldwide, but Excel is a lot more than just a spreadsheet pro-
gram. Unknown to many users, Excel is also a sophisticated platform for develop-
ment of custom applications. Lurking behind its mild-mannered spreadsheet disguise is a
powerful and full-featured programming language called Visual Basic for Applications (VBA).
If you have recorded and played back an Excel macro, you have used VBA — perhaps with-
out being aware of it.
There’s much more to VBA programming than recording macros, however. Nearly any user
can write VBA programs to perform a wide variety of tasks in Excel, ranging from the sim-
ple, such as automating financial calculations, to the complex, such as creating a data entry
system with custom forms and data validation. Unfortunately, many users shy away from
taking advantage of Excel’s programmability because it seems too complicated, and they
cannot find a good source of information to guide them through the learning process. Excel
programming can be somewhat complicated, which is unavoidable for such a powerful tool,
but the truth is that almost any reasonably computer-literate person can learn how to pro-
gram in Excel. That’s where this book comes in handy.
Who Should Read This Book
This book is aimed at anyone who wants to use programming to improve his or her Excel
skills. Perhaps you only want to write programs for your own use, or maybe you need to cre-
ate Excel programs for use by your coworkers. In either situation, this book is aimed at you.
The book was written specifically with the nonspecialist in mind. You do not need to have
any programming knowledge or experience to use this book because everything from square
one is explained. Of course, if you do have some programming experience, it will not hurt,
but the important point is that such experience is not required.
Weekend Crash Course Layout and Features
This book contains 30 sessions, each of which is designed to be completed in about 30 min-
utes. Each session has a review section at the end and a list of questions so you can test

your knowledge. The sessions are organized into six parts; the main purpose of each part is
Preface
540629 FM.qxd 9/2/03 4:10 PM Page v
to provide a convenient breaking point to help you in pacing your progress. At the end of
each part, you’ll find additional questions related to that part’s session topics. The answers
for the part review questions are provided in Appendix A.
Part I: Friday Evening
The first session provides an introduction to programming with Excel, including an overview
of many of the advantages. You’ll also find some basic information about programming in
this session.
The second session teaches you how to use the VBA Code Editor. This tool is part of the
Excel installation, and you use it to create, test, and run your programs.
Session 3 deals with the Excel Object Model. This is the set of tools that the Excel appli-
cation makes available for you to use in your programs.
Session 4 introduces you to the VBA language, your primary tool for writing programs.
Part II: Saturday Morning
Sessions 5 through 9 cover the VBA language. You need a good knowledge of the VBA lan-
guage’s elements and syntax to write programs. This includes learning about operators, con-
trol constructs, procedures, and modules, as well as how to work with dates, times, and
text. The final session in this part, Session 10, shows you how to work with Excel’s ranges
and selections.
Part III: Saturday Afternoon
Sessions 11 through 14 cover the fundamentals of controlling Excel through VBA code.
You’ll learn how to work with columns, rows, and cells; how to program with custom formu-
las and built-in functions; and how to format a worksheet. The last two sessions deal with
find and replace operations and creating custom toolbars.
Part IV: Saturday Evening
Sessions 17 and 18 show you how to use Excel’s powerful charting capabilities in your pro-
grams. Then Sessions 19 and 20 present the basics of creating custom dialog boxes for your
programs with Excel’s user forms.

Part V: Sunday Morning
Sessions 21 and 22 finish the coverage of user forms, including a complete example.
Sessions 23 through 26 deal with the topics of Excel events, security considerations,
and debugging distributing an application, and creating custom classes.
Prefacevi
540629 FM.qxd 9/2/03 4:10 PM Page vi
Part VI: Sunday Afternoon
The remaining sessions deal with a variety of topics, including runtime errors, database
tasks, add-ins, and online help.
I recommend that you work through the sessions in order. At the very least you should
complete Sessions 1 through 9 before branching off to other topics.
The Companion Web Site
On the book’s companion Web site, you’ll find code listings of sample programs and a self-
assessment test, which consists of over 80 multiple-choice and true or false questions. Just
go to
www.wiley.com/compbooks/aitken
.
Features
As I have mentioned, each session is designed to take about 30 minutes. It’s not a race,
however, so don’t worry if it takes you a bit longer. It’s what you learn that’s important.
The following time-status icons let you know how much progress you’ve made throughout
each session.
The following icons identify bits of information that are set apart from the text:
A note is an important bit of information that you should know about.
A tip is a suggestion for an easier or faster way to do something when pro-
gramming Excel.
This icon warns you of something you should never do.
This icon points you to other sessions where related material can be found.
Cross-Ref
Never

Tip
Note
Preface vii
540629 FM.qxd 9/2/03 4:10 PM Page vii
Menu selections are indicated using the ➪ symbol. Thus, File ➪ Save means to open the
File menu and then select the Save command.
Code and VBA keywords in the text are indicated by a special font
like this
. Code list-
ings that are separate from the text are also in this font. Italics are used to indicate place-
holders in code. Here’s an example:
SaveAs filename
When you enter this code, you do not actually type filename. Rather, you replace file-
name with a specific filename as explained in the text.
Prefaceviii
540629 FM.qxd 9/2/03 4:10 PM Page viii
I appreciate the efforts of all the people at Wiley who have helped make this book happen,
in particular Acquisitions Editor, Jim Minatel and Project Editor, Mark Enochs. My thanks
also go to Technical Editor, Ken Slovak, and the Copy Editor, Susan Hobbs.
Acknowledgments
540629 FM.qxd 9/2/03 4:10 PM Page ix
540629 FM.qxd 9/2/03 4:10 PM Page x
FRIDAY 2
PART I—Friday Evening 4
SESSION 1–Microsoft Excel Programming — Why and How 5
SESSION 2–The VBA Code Editor 17
SESSION 3–The Excel Object Model 31
SESSION 4–Syntax and Data in VBA 47
SATURDAY 66
PART II–Saturday Morning 68

SESSION 5–Operators 69
SESSION 6–Control Constructs 77
SESSION 7–Procedures and Modules 87
SESSION 8–Working with Dates and Times 97
SESSION 9–Working with Text 107
SESSION 10–Using Ranges and Selections 121
PART III–Saturday Afternoon 140
SESSION 11–Working with Columns, Rows, and Cells 141
SESSION 12–Programming with Custom Formulas 151
SESSION 13–Programming with Excel’s Built-In Functions 161
SESSION 14–Formatting a Worksheet 171
SESSION 15–Find and Replace Operations 187
SESSION 16–Creating Custom Toolbars 195
PART IV–Saturday Evening 208
SESSION 17–Introduction to Charts 209
SESSION 18–Advanced Charting Techniques 225
SESSION 19–Creating Custom Dialog Boxes with User Forms 239
SESSION 20–Controls for User Forms 251
Contents at a Glance
540629 FM.qxd 9/2/03 4:10 PM Page xi
SUNDAY 268
PART V–Sunday Morning 270
SESSION 21–Advanced User Form Techniques 271
SESSION 22–A User Form Example 283
SESSION 23–Working with Events 295
SESSION 24–Security Considerations 311
SESSION 25–Debugging and Distributing an Application 321
SESSION 26–Defining and Using Custom Classes 329
PART VI–Sunday Afternoon 346
SESSION 27–Handling Runtime Errors 347

SESSION 28–Database Tasks 357
SESSION 29–Creating Add-Ins 367
SESSION 30–Adding Online Help to Your Application 379
Appendix A–Answers to Part Reviews 391
Appendix B–What’s on the Web Site 397
Index 399
Contents at a Glancexii
540629 FM.qxd 9/2/03 4:10 PM Page xii
Preface v
Acknowledgments xiii
FRIDAY 2
PART I–Friday Evening 4
SESSION 1–Microsoft Excel Programming — Why and How 5
Advantages of Programming 5
Saving Time
6
Reducing Errors
6
Enforcing Standards
6
Integrating with Other Applications
6
Programming Fundamentals
6
Creating Instructions
7
Handling Data
7
The VBA Language
7

The Excel Object Model
8
Objects
8
Components and Automation
9
Macros and Programming
10
Designing Your Custom Application
10
Your First Excel Program
11
Creating and Naming the Program
11
Writing the Code
12
Running the Program
14
SESSION 2–The VBA Code Editor 17
Code and Project Organization 17
The Project Explorer
19
Importing and Exporting Modules
19
Editing Tools
20
The Property Window
22
The VBA Editor Menus
23

Contents
540629 FM.qxd 9/2/03 4:10 PM Page xiii
Using Macros in Programming 24
Recording a Macro
25
Cell References in Macros
26
Viewing and Running Macros
27
Online Help
27
SESSION 3–The Excel Object Model 31
Understanding Properties and Methods 31
The Importance of Object References
32
Working with Collections
33
The Object Hierarchy
35
The Workbook Object
36
Creating and Opening Workbooks
36
Saving and Closing Workbooks
37
Referencing Workbooks
38
Printing Workbooks
39
E-Mailing a Workbook

39
Other Workbook Methods and Properties
40
The Worksheet Object
41
Adding and Deleting Worksheets
41
Referencing Worksheets
43
Copying and Moving Worksheets
44
SESSION 4–Syntax and Data in VBA 47
VBA Syntax Fundamentals 47
Comments
48
Source Code Formatting
49
Employing Constants
49
Declaring and Using Variables
50
Numeric Variables
51
String Variables
52
Date Variables
53
Object Variables
53
Boolean Variables

54
The Variant Type
54
Using Arrays
55
Static Arrays
55
Dynamic Arrays
56
User-Defined Types
59
Enumerations
60
Understanding Variable Scope
61
SATURDAY 66
PART II–Saturday Morning 68
SESSION 5–Operators 69
The Assignment Operator 69
Numerical Operators
70
Contentsxiv
540629 FM.qxd 9/2/03 4:10 PM Page xiv
String Operators 71
Logical Operators
71
Comparison Operators
72
Operator Precedence
74

SESSION 6–Control Constructs 77
The If Then Statement 78
The Select Case Statement
80
The Do Loop Statement
81
The For Next Statement
83
The For Each Next Statement
84
The Goto Statement
85
SESSION 7–Procedures and Modules 87
Sub Procedures 88
Procedure Arguments
89
Optional Arguments
89
ParamArray Arguments
90
ByVal and ByRef Arguments
90
Calling Procedures
91
Argument Type Checking
92
Function Procedures
93
Variables in Procedures
94

Procedure Scope
95
Storing Procedures
95
SESSION 8–Working with Dates and Times 97
The Date Data Type 97
Date/Time Values
98
Date Calculations
99
Date and Time Details
100
Formatting Date/Time Values
103
SESSION 9–Working with Text 107
Text Input and Output 107
The MsgBox Function
107
InputBox Function
110
Searching for Text
111
Comparing Strings
112
String Conversions
112
The StrConv Function
112
The LCase and UCase Functions
113

The Val Function
113
The Str Function
114
Working with ASCII Values
114
The Asc, AscB, and AscW Functions
115
The Chr Function
117
Extracting or Modifying Parts of Strings
117
The Left and Right Functions
117
The Mid Function
118
Contents xv
540629 FM.qxd 9/2/03 4:10 PM Page xv
The Mid Statement 118
Other String Functions
119
SESSION 10–Using Ranges and Selections 121
The Range Object 121
Manipulating Ranges
122
Relative Ranges
123
Other Range References
127
Working with Comments

128
Range Columns, Rows, and Size
130
Reading Data from Ranges
130
Naming Ranges
132
The Selection Property
134
PART II–Saturday Morning Part Review 137
Saturday Afternoon 140
SESSION 11–Working with Columns, Rows, and Cells 141
Referencing Cells with the Cells Property 141
Referencing All Cells
142
Referencing by Row and Column
142
Referencing by Cell Position
145
The SpecialCells Method
145
Manipulating Columns and Rows
147
Adding and Deleting Rows and Columns
149
SESSION 12–Programming with Custom Formulas 151
Cell References in Formulas 151
Relative Cell References
152
Absolute Cell References

152
Named Range References
154
Referencing Cells in Other Worksheets and Workbooks
155
Operators
156
Mathematical Operators
156
Comparison Operators
156
Logical Operators
156
Avoiding Circular References
157
Controlling Formula Calculation
158
SESSION 13–Programming with Excel’s Built-In Functions 161
Excel’s Built-in Functions 161
Using Excel Functions in Formulas
162
Excel Function Overview
163
Financial Functions
163
Date and Time Functions
166
Math and Trig Functions
167
Text Functions

168
The WorksheetFunction Object
169
Contentsxvi
540629 FM.qxd 9/2/03 4:10 PM Page xvi
SESSION 14–Formatting a Worksheet 171
Cell Formatting 171
Number Formatting
173
Font Formatting
175
Alignment and Orientation of Data
176
Cell Borders
178
Cell Backgrounds
181
Changing Row and Column Size
184
SESSION 15–Find and Replace Operations 187
Finding Data 187
The Find Method
188
The FindNext and FindPrevious Methods
189
Replacing Data
192
SESSION 16–Creating Custom Toolbars 195
Customizing Toolbars in Excel 195
Displaying and Hiding Toolbars

195
Creating a New Toolbar
197
Adding and Removing Toolbar Buttons
198
Running Programs from Toolbar Buttons
199
Distributing Toolbars
202
Hiding and Displaying Toolbars in VBA Code
203
PART IV–Saturday Evening 208
SESSION 17–Introduction to Charts 209
Embedded Charts and Chart Sheets 209
Embedded Charts
211
Chart Sheets
211
The Chart Object
212
Identifying Data to Be Plotted
212
Specifying Chart Type
214
Controlling Chart Appearance
216
Displaying Chart Titles
216
Chart Axis Titles
217

Working with Fonts in a Chart
219
The ChartWizard Method
222
SESSION 18–Advanced Charting Techniques 225
Naming and Referencing Charts 225
Locking Charts
226
The ChartObject Object
227
Using Scatter Charts
231
Scatter Chart Types
233
Changing Axis Range
234
Printing Charts
235
Contents xvii
540629 FM.qxd 9/2/03 4:10 PM Page xvii
SESSION 19–Creating Custom Dialog Boxes with User Forms 239
Overview of User Forms 239
Form Designer Basics
240
Designing the Interface
241
Setting Properties
242
Form Properties
243

Appearance Properties
243
Behavior and Position Properties
244
Form Methods
245
Displaying, Using, and Hiding Forms
246
A Simple User Form Example
247
SESSION 20–Controls for User Forms 251
A Summary of Controls 251
Common Control Properties
252
User Form Control Details
253
The CheckBox Control
253
The ComboBox Control
253
The CommandButton Control
256
The Frame Control
258
The Label Control
258
The OptionButton Control
258
The RefEdit Control
260

The TextBox Control
262
The ToggleButton Control
263
SUNDAY 268
PART V–Sunday Morning 270
SESSION 21–Advanced User Form Techniques 271
Using Control Events 271
Advanced Form Design
273
The Form Grid
273
Control Placement and Alignment Tools
274
Overlapping Controls and the Z-Order
278
Focus and the Tab Order
278
SESSION 22–A User Form Example 283
Planning the Project 283
Part 1: Creating the Workbook
285
Part 2: Designing the Form
285
Part 3: Writing the Initialization Code
286
Part 4: Restricting Zip Code Entry to Digits
287
Part 5: Writing the Data Validation Code
288

Part 6: Completing the Project
289
Part 7: Testing the Project
292
Contentsxviii
540629 FM.qxd 9/2/03 4:10 PM Page xviii
SESSION 23–Working with Events 295
Event Categories 295
Event Handler Code
296
Event Sequences
297
Enabling and Disabling Events
297
Workbook Events
298
The Open Event
299
The NewSheet Event
300
Worksheet Events
300
The Change Event
301
Using the Change Event for Data Validation
301
Application Events
303
Writing Application Event Procedures
304

The WorkbookBeforeClose Event
305
Other Events
306
The OnTime Event
307
The OnKey Event
308
SESSION 24–Security Considerations 311
Workbook Protection 311
Worksheet Protection
312
VBA Code and Worksheet Protection
314
Protecting the Loan Calculator Worksheet
315
Protecting Your VBA Code
315
Macro Security
316
Adding a Trusted Source
317
Removing a Trusted Source
317
Using Digital Certificates to Sign Macros
317
SESSION 25–Debugging and Distributing an Application 321
Debugging an Application 321
What Are Bugs?
321

Avoiding Bugs
322
Debugging Tools
323
Breakpoints
323
Step Commands
324
Using Watches
325
Using Quick Watches
327
Distributing an Application
327
SESSION 26–Defining and Using Custom Classes 329
Class Fundamentals 329
The Advantages of Classes
330
Instantiating Classes
330
Class Properties
331
Creating Property Procedures
331
The Property Variable
332
Contents xix
540629 FM.qxd 9/2/03 4:10 PM Page xix
Connecting the Property to the Property Procedures 333
Array Properties

334
Read-Only Properties
335
Accessing Properties in Code
336
Class Methods
336
Property Validation
336
Class Events
337
Reusing a Class
337
A Class Demonstration
337
PART VI–Sunday Afternoon 346
SESSION 27–Handling Runtime Errors 347
What’s a Runtime Error? 347
The Causes of Errors
348
Preventing Errors
349
Trapping Errors
350
The Err Object
351
Error-Handling Code
352
Deferring Error Handling
353

Some Error-Handling Examples
353
Ignoring an Error
354
Notifying the User of an Error
354
Using an Error as a Programming Tool
355
SESSION 28–Database Tasks 357
Databases and Excel 357
Database Fundamentals
358
Sorting Data
359
Filtering Data
360
Data Entry Forms
363
Database Functions
364
SESSION 29–Creating Add-Ins 367
Add-Ins versus Workbooks 367
Creating an Add-In
369
Distributing an Add-In
370
Using Excel’s Add-In Manager
370
Events in Add-Ins
371

Functions in Add-Ins
371
Using VBA to Manipulate Add-Ins
372
An Add-In Demonstration
373
Code the Function
374
Code the Program
375
Create the Toolbar
375
Securing the Code and Saving the Add-In
377
Testing the Add-In
377
Contentsxx
540629 FM.qxd 9/2/03 4:10 PM Page xx
SESSION 30–Adding Online Help to Your Application 379
Online Help for Excel 379
Using Excel Components for Help
380
Putting Help in the Worksheet
380
Putting Help in a Separate Worksheet
381
Putting Help in a User Form
384
Using External Components for Help
384

HTML Help
384
Web-Based Help
386
Appendix A–Answers to Part Reviews 391
Friday Evening Review Answers 391
Saturday Morning Review Answers
392
Saturday Afternoon Review Answers
393
Saturday Evening Review Answers
394
Sunday Morning Review Answers
395
Sunday Afternoon Review Answers
396
Appendix B–What’s on the Web Site 397
The Self-Assessment Test 397
Downloadable Examples from the Exercises in the Book
397
Troubleshooting
397
Index 399
Contents xxi
540629 FM.qxd 9/2/03 4:10 PM Page xxi
540629 FM.qxd 9/2/03 4:10 PM Page xxii

×