1. Trang chủ
  2. » Công Nghệ Thông Tin

Excel 2002 Power Programming with VBA phần 1 docx

99 256 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 99
Dung lượng 4,04 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Offering plenty of detailed, well-thought-out examples, he walks you through the basics of Excel application development and VBA programming—and then gives you a lucid, wide-ranging semi

Trang 2

Develop Powerful, User-Oriented Excel 2002 Applications

With this unique guide, renowned spreadsheet authority John Walkenbach invites you to harness the full potential of Excel—and join the elite group of users and developers who truly understand what the product is capable of Offering plenty

of detailed, well-thought-out examples, he walks you through the basics of Excel application development and VBA programming—and then gives you a lucid, wide-ranging seminar on advanced programming techniques and application development issues It’s all you need to create user-oriented custom applications that leverage the power of Excel 2002

Your Road Map to Excel Application Development

• Take Excel to the next level with formula tricks and techniques

• Work with VBA sub procedures and function procedures

• Create stellar UserForms as well as custom dialog box alternatives

• Develop applications that maximize the power of PivotTables and charts

• Incorporate event-handling and interactions with other applications

• Build user-friendly toolbars, menus, and help systems

• Manipulate files and Visual Basic components and understand class modules

• Get advice on compatibility issues and answers to frequently asked Excel programming questions

• A trial version of the author’s

award-winning Power Utility

Pak 2000

• A demo of the author’s

Sound-Proof 2000

• Over 175 example Excel

workbooks from the book

BONUS CD-ROM INCLUDES

Programming with VBA

John Walkenbach

Author of Excel 2002 Bible

“An outstanding reference If you use Excel, you need this book.”

— Microsoft OfficePRO magazine on the previous edition

John Walkenbachis a

principal of JWalk and Associates, Inc.,a

consulting firm that specializes in

spreadsheet application development,

and is the author of more than two

dozen books, including, most

recently, Excel 2002 Bible and Excel

2002 Formulas He maintains “The

Spreadsheet Page,” a popular Web

System Requirements: Pentium PC with

Windows 98 or greater; 32 MB RAM; Microsoft

Excel 2002 See About the CD appendix for

details and complete system requirements.

Trang 3

Excel 2002 Power Programming with VBA

Trang 5

Excel 2002 Power Programming with VBA

John Walkenbach

M&T Books

An imprint of Hungry Minds, Inc

New York, NY ✦ Cleveland, OH ✦ Indianapolis, IN

Trang 6

909 Third Avenue New York, NY 10022 www.hungryminds.com Copyright © 2001 Hungry Minds, Inc All rights reserved No part of this book, including interior design, cover design, and icons, may be reproduced

or transmitted in any form, by any means (electronic, photocopying, recording, or otherwise) without the prior written permission of the publisher.

Library of Congress Control Number 2001089315 ISBN: 0-7645-4799-2

Printed in the United States of America

10 9 8 7 6 5 4 3 2 1 1O/SY/QW/QR/IN Distributed in the United States by Hungry Minds, Inc.

Distributed by CDG Books Canada Inc for Canada;

by Transworld Publishers Limited in the United Kingdom; by IDG Norge Books for Norway; by IDG Sweden Books for Sweden; by IDG Books Australia Publishing Corporation Pty Ltd for Australia and New Zealand; by TransQuest Publishers Pte Ltd for Singapore, Malaysia, Thailand, Indonesia, and Hong Kong; by Gotop Information Inc for Taiwan; by ICG Muse, Inc for Japan; by Intersoft for South Africa;

by Eyrolles for France; by International Thomson Publishing for Germany, Austria, and Switzerland;

by Distribuidora Cuspide for Argentina; by LR International for Brazil; by Galileo Libros for Chile;

by Ediciones ZETA S.C.R Ltda for Peru; by WS

Computadoras S.A de C.V for Mexico; by Editorial Norma de Panama S.A for Panama; by American Bookshops for Finland.

For general information on Hungry Minds’ products and services 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 For sales inquiries and reseller information, including discounts, premium and bulk quantity sales, and foreign-language translations, please contact our Customer Care department at 800-434-3422, fax 317-572-4002 or write to Hungry Minds, Inc., Attn: Customer Care Department, 10475 Crosspoint Boulevard, Indianapolis, IN 46256 For information on licensing foreign or domestic rights, please contact our Sub-Rights Customer Care department at 212-884-5000.

For information on using Hungry Minds’ products and services in the classroom or for ordering examination copies, please contact our Educational Sales department at 800-434-2086 or fax

317-572-4005.

For press review copies, author interviews, or other publicity information, please contact our Public Relations department at 317-572-3168 or fax 317-572-4168.

For authorization to photocopy items for corporate, personal, or educational use, please contact Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, or fax 978-750-4470.

LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK THE PUBLISHER AND AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE THERE ARE NO WARRANTIES WHICH EXTEND BEYOND THE DESCRIPTIONS CONTAINED IN THIS PARAGRAPH NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS THE ACCURACY AND COMPLETENESS OF THE INFORMATION PROVIDED HEREIN AND THE OPINIONS STATED HEREIN ARE NOT GUARANTEED OR WARRANTED TO PRODUCE ANY PARTICULAR RESULTS, AND THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY INDIVIDUAL NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES FULFILLMENT OF EACH COUPON OFFER IS THE SOLE RESPONSIBILITY OF THE OFFEROR.

Trademarks: Professional Mindware is a trademark or registered trademark of Hungry Minds Microsoft is a

registered trademark or trademark of Microsoft Corporation All other trademarks are property of their respective owners Hungry Minds, Inc is not associated with any product or vendor mentioned in this book.

is a trademark of is a trademark of Hungry Minds, Inc Hungry Minds, Inc.

Trang 7

About the Author

John Walkenbach is a leading authority on spreadsheet software and is principal of

JWalk and Associates Inc., a small, San Diego-based consulting firm that specializes

in spreadsheet application development John is the author of more than two dozenspreadsheet books and has written more than 300 articles and reviews for a variety

of publications, including PC World, InfoWorld, Windows, and PC/Computing He also maintains The Spreadsheet Page, a popular Internet Web site (www.j-walk.com/ss),and is the developer of Power Utility Pak, an award-winning add-in for MicrosoftExcel John graduated from the University of Missouri and earned a master’s and aPh.D from the University of Montana

In addition to computers and spreadsheet software, John’s other interests includeguitar, music, novels, digital photography, and puttering around in the garden

Trang 8

Quality Control Technicians

Andy HollandbeckCarl PierceDwight RamseyCharles Spencer

Senior Permissions Editor

Proofreading and Indexing

TECHBOOKS Production Services

Cover Image

© Noma/Images.com

Trang 9

This one’s for Michelle.

Trang 11

Welcome to Excel 2002 Power Programming with VBA If your job involves

developing spreadsheets that others will use — or if you simply want toget the most out of Excel — you’ve come to the right place

Why I Wrote This Book

Quite a few advanced Excel books are available, but this book is still the only onethat deals with spreadsheet application development from a larger perspective.VBA is just one component (albeit a fairly large component) of application develop-ment Excel is an extremely deep software product: It has many interesting featuresthat lurk in the background, unbeknownst to the typical user And you can usesome of the well-known features in novel ways

Millions of people throughout the world use Excel I monitor the spreadsheet-relatednewsgroups on the Internet, and it’s very clear to me that people need (and want)help in the areas that this book covers My guess is that only five percent of Excelusers really understand what the product is capable of In this book, I attempt tonudge you into that elite company Are you up to it?

What You Need to Know

This is not a book for beginning Excel users If you have no experience with Excel, Irecommend that you read either of the following books:

✦ Excel 2002 for Windows For Dummies, by Greg Harvey, is written for users who

want to know just enough to get by, and want to be entertained in the process

✦ Excel 2002 Bible (by yours truly) provides comprehensive coverage of all the

features of Excel It is meant for users of all levels

To get the most out of this book, you should be a relatively experienced Excel user

I didn’t spend much time writing basic how-to information In fact, I assume thatyou know the following:

✦ How to create workbooks, insert sheets, save files, and so on

✦ How to navigate through a workbook

✦ How to use the menus and shortcut menus

Trang 12

✦ How to manage Excel’s toolbars

✦ How to enter formulas

✦ How to use Excel’s worksheet functions

✦ How to name cells and ranges

✦ How to use basic Windows features, such as file management techniques andthe clipboard

If you don’t know how to perform the preceding tasks, you may find some of thismaterial over your head, so consider yourself warned If you’re an experiencedspreadsheet user who hasn’t used Excel 2002, Chapter 2 presents a short overview

of what this product offers

What You Need to Have

To make the best use of this book, you need a copy of Excel Although the book waswritten with Excel 2002 in mind, most of the material also applies to Excel 2000 andExcel 97 If you use an earlier version of Excel, you’re reading the wrong book Most

of the material in this book also applies to Excel for Macintosh However, I did nocompatibility testing with the Mac version, so you’re on your own

Any computer system that can run Windows will suffice, but you’ll be much betteroff with a fast Pentium-based machine with plenty of memory Excel is a large pro-gram, and using it on a slower system or a system with minimal memory can beextremely frustrating

I recommend using a high-resolution video driver (800 ×600 is okay, 1024 ×768 isexcellent, and 1600 ×1024 is sheer heaven) A standard VGA resolution will do in apinch, but it just doesn’t let you see enough on-screen

To make use of the examples on the companion CD, you will also need a CD-ROMdrive

Conventions in This Book

Take a minute to skim this section and learn some of the typographic conventionsused throughout this book

Trang 13

Keyboard conventions

You need to use the keyboard to enter data In addition, you can work with menusand dialog boxes directly from the keyboard — a method you may find easier if yourhands are already positioned over the keys

Input

Input that you type from the keyboard appears in boldface — for example, enter

=SUM(B2: B50) into cell B51.

More lengthy input usually appears on a separate line in a monospace font Forexample, I may instruct you to enter the following formula:

=VLOOKUP(STOCKNUMBER,PRICELIST,2)

VBA code

This book contains many snippets of VBA code, as well as complete procedurelistings Each listing appears in a monospace font; each line of code occupies a separate line (I copied these listings directly from the VBA module and pastedthem into my word processor.) To make the code easier to read, I often use one ormore tabs to create indentations Indentation is optional, but it does help to delin-eate statements that go together

If a line of code doesn’t fit on a single line in this book, I use the standard VBA linecontinuation sequence: At the end of a line, a space followed by an underscorecharacter indicates that the line of code extends to the next line For example, thefollowing two lines are a single line of code:

If Right(ActiveCell, 1) = “!” Then ActiveCell _

= Left(ActiveCell, Len(ActiveCell) - 1)

You can enter this code either on two lines, exactly as shown, or on a single linewithout the underscore character

Functions, filenames, and named ranges

Excel’s worksheet functions appear in uppercase monospace font, like so: “Enter a

SUMformula in cell C20.” VBA procedure names, properties, methods, and objectsappear in monospace font: “Execute the GetTotalsprocedure.” I often use mixedupper- and lowercase to make these names easier to read

Mouse conventions

If you’re reading this book, you’re well versed in mouse usage The mouse ogy I use is all standard fare: pointing, clicking, right-clicking, dragging, and so on

Trang 14

terminol-What the Icons Mean

Throughout the book, I’ve used icons in the left margin to call your attention topoints that are particularly important

I use this icon to indicate that the material discussed is new to Excel 2002 Ifyou’re developing an application that will be used for earlier versions of Excel, payparticular attention to these icons

I use Note icons to tell you that something is important — perhaps a concept thatmay help you master the task at hand or something fundamental for understand-ing subsequent material

Tip icons indicate a more efficient way of doing something or a technique thatmay not be obvious

These icons indicate that an example file is on the companion CD-ROM (see

“About the Companion CD-ROM,” later in the introduction) This CD holds many ofthe examples that I cover in the book, as well as a trial copy of my popular PowerUtility Pak software

I use Caution icons when the operation that I’m describing can cause problems ifyou’re not careful

I use the Cross Reference icon to refer you to other chapters that have more tosay on a subject

How This Book Is Organized

The chapters of this book are grouped into seven main parts In addition, I’veincluded a few appendixes that provide supplemental information

Part I: Some Essential Background

In this part, I set the stage for the rest of the book Chapter 1 presents a brief history

of spreadsheets so that you can see how Excel fits into the big picture In Chapter 2,

I offer a conceptual overview of Excel 2002 — quite useful for experienced sheet users who are switching to Excel In Chapter 3, I cover the essentials of formulas, including some clever techniques that may be new to you Chapter 4 covers the ins and outs of the various files used and generated by Excel

spread-

Cross-Reference

Caution

On the CD-ROM Tip Note New

Feature

Trang 15

Part II: Excel Application Development

This part consists of just two chapters In Chapter 5, I broadly discuss the concept

of a spreadsheet application Chapter 6 goes into more detail and covers the stepstypically involved in a spreadsheet application development project

Part III: Understanding Visual Basic for Applications

Chapters 7 through 11 make up Part III, and these chapters include everything youneed to know to learn VBA In this part, I introduce you to VBA, provide program-ming fundamentals, and detail how to develop VBA subroutines and functions

Chapter 11 contains tons of useful VBA examples

Part IV: Working with UserForms

The four chapters in this part cover custom dialog boxes (also known as UserForms)

Chapter 12 presents some built-in alternatives to creating custom UserForms

Chapter 13 provides an introduction to UserForms and the various controls youcan use Chapters 14 and 15 present many examples of custom dialog boxes, rang-ing from basic to advanced

Part V: Advanced Programming Techniques

Part V covers additional techniques that are often considered advanced The firstthree chapters discuss how to develop utilities and how to use VBA to work withpivot tables and charts Chapter 19 covers the topic of event-handling, whichenables you to execute procedures automatically when certain events occur

Chapter 20 discusses various techniques that you can use to interact with otherapplications (such as Word) Chapter 21 concludes Part V with an in-depth discus-sion of creating add-ins

Part VI: Developing Applications

The chapters in Part VI deal with important elements of creating user-orientedapplications Chapters 22 and 23 provide information on creating custom toolbarsand menus Chapter 24 presents several different ways to provide online help foryour applications In Chapter 25, I present some basic information about develop-ing user-oriented applications, and I describe such an application in detail

Part VII: Other Topics

The five chapters in Part VII cover additional topics that you may find helpful

Chapter 26 presents information regarding compatibility In Chapter 27, I discussvarious ways to use VBA to work with files In Chapter 28, I explain how to use VBA

Trang 16

to manipulate Visual Basic components such as UserForms and modules Chapter

29 covers the topic of class modules I finish the part with a useful chapter thatanswers many common questions about Excel programming

Appendixes

Five appendixes round out the book Appendix A contains useful information aboutExcel resources online Appendix B is a reference guide to all of VBA’s keywords(statements and functions) I explain VBA error codes in Appendix C, and Appendix

D is a handy ANSI code reference chart The final appendix describes the files able on the companion CD-ROM

avail-About the Companion CD-ROM

The inside back cover of this book contains a CD-ROM that holds many usefulexamples that I discuss in the text When I write about computer-related material,

I emphasize learning by example I know that I learn more from a well-thought-outexample than from reading a dozen pages in a book I assume that this is true formany other people Consequently, I spent more time developing the examples onthe CD-ROM than I did writing chapters

The files on the companion CD-ROM are not compressed, so you can access themdirectly from the CD

Refer to Appendix E for a description of each file on the CD-ROM

All CD-ROM files are read-only files Therefore, if you open a file from the CD-ROMand make any changes to it, you need to save it to your hard drive In addition, ifyou copy a file from the CD-ROM to your hard drive, the file retains its read-onlyattribute To change this attribute after copying a file, right-click the filename oricon and select Properties from the shortcut menu In the Properties dialog box,click the General tab and remove the check mark from the Read-only checkbox

About the Power Utility Pak Offer

Toward the back of the book, you’ll find a coupon that you can redeem for a freecopy of my popular Power Utility Pak software (normally $39.95) PUP is an award-winning collection of useful Excel utilities and many new worksheet functions Ideveloped this package exclusively with VBA

Note Cross-

Reference

Trang 17

I think you’ll find this product useful in your day-to-day work with Excel, and I urgeyou to take advantage of this free offer You can also purchase the complete VBAsource code for a nominal fee Studying the code is an excellent way to pick upsome useful programming techniques.

You can take Power Utility Pak for a test drive by installing the 30-day trial versionfrom the companion CD-ROM

How to Use This Book

You can use this book any way you please If you choose to read it cover to cover, be

my guest But because I’m dealing with intermediate-to-advanced subject matter, thechapter order is often immaterial I suspect that most readers will skip around, pick-ing up useful tidbits here and there If you’re faced with a challenging task, you mighttry the index first to see whether the book specifically addresses your problem

Reach Out

The publisher and I want your feedback After you have had a chance to use thisbook, please take a moment to visit the Hungry Minds, Inc Web site to register yourbook and give us your comments (See the “my2cents.hungryminds.com” page atthe back of this book for more details.) Please be honest in your evaluation If youthought a particular chapter didn’t tell you enough, let me know Of course, I wouldprefer to receive comments like “This is the best book I’ve ever read,” or “Thanks tothis book, I was promoted and now make $90,000 a year.”

I get at least a dozen questions every day, via e-mail, from people who have read

my books I appreciate the feedback Unfortunately, I simply don’t have the time to

reply to questions Appendix A provides a good list of sources that can answer your

questions

I also invite you to visit my Web site, which contains lots of Excel-related material

Despite the massive attempts to make this book completely accurate, a few errorshave probably crept into its pages My Web site includes a list of any such errors

The URL is

http://www.j-walk.com/ss/

Trang 20

Contents at a Glance

Preface ix

Acknowledgments xvii

Part I: Some Essential Background 1

Chapter 1: Excel 2002: Where It Came From 3

Chapter 2: Excel in a Nutshell 17

Chapter 3: Formula Tricks and Techniques 37

Chapter 4: Understanding Excel’s Files 61

Part II: Excel Application Development 79

Chapter 5: What is a Spreadsheet Application? 81

Chapter 6: Essentials of Spreadsheet Application Development 95

Part III: Understanding Visual Basic for Applications 117

Chapter 7: Introducing Visual Basic for Applications 119

Chapter 8: VBA Programming Fundamentals 177

Chapter 9: Working with VBA Sub Procedures 219

Chapter 10: Creating Function Procedures 257

Chapter 11: VBA Programming Examples and Techniques 291

Part IV: Working with UserForms 353

Chapter 12: Custom Dialog Box Alternatives 355

Chapter 13: Introducing UserForms 377

Chapter 14: UserForm Examples 411

Chapter 15: Advanced UserForm Techniques 439

Part V: Advanced Programming Techniques 475

Chapter 16: Developing Excel Utilities with VBA 477

Chapter 17: Working with Pivot Tables 505

Chapter 18: Working with Charts 521

Chapter 19: Understanding Excel’s Events 571

Chapter 20: Interacting with Other Applications 603

Chapter 21: Creating and Using Add-Ins 625

Trang 21

Part VI: Developing Applications 651

Chapter 22: Creating Custom Toolbars 653

Chapter 23: Creating Custom Menus 685

Chapter 24: Providing Help for Your Applications 719

Chapter 25: Developing User-Oriented Applications 739

Part VII: Other Topics 751

Chapter 26: Compatibility Issues 753

Chapter 27: Manipulating Files with VBA 767

Chapter 28: Manipulating Visual Basic Components 789

Chapter 29: Understanding Class Modules 811

Chapter 30: Frequently Asked Questions about Excel Programming 825

Appendix A: Excel Resources Online 861

Appendix B: VBA Statements and Functions Reference 867

Appendix C: VBA Error Codes 877

Appendix D: ANSI Code Reference 881

Appendix E: What’s on the CD-ROM 891

Index 907

End-User License Agreement 943

CD-ROM Installation Instructions 946

Trang 23

Chapter 1: Excel 2002: Where It Came From 3

A Brief History of Spreadsheets 3

It all started with VisiCalc 3Lotus 1-2-3 4Quattro Pro 7Microsoft Excel 8Spreadsheets Today 13Why Excel Is Great for Developers 14Excel’s Role in Microsoft’s Strategy 15

Chapter 2: Excel in a Nutshell 17

Thinking in Terms of Objects 17Workbooks 18Worksheets 19Chart sheets 20XLM macro sheets 20Excel 5/95 dialog sheets 20Excel’s User Interface 21Menus 21Dialog boxes 21Toolbars 22Drag-and-drop 23Keyboard shortcuts 24Customizing the Display 24Data Entry 24Selecting Objects 26Formatting 26Numeric formatting 26Stylistic formatting 27Formulas 27Names 27Functions 28Shapes 28Charts 30Macros 31Database Access 31Worksheet databases 32External databases 32

Trang 24

Internet Features 33Analysis Tools 33Outlines 33Automatic subtotals 33Scenario management 34Analysis ToolPak 34Pivot tables 34Auditing 35Solver 35Add-Ins 35Compatibility 36

Chapter 3: Formula Tricks and Techniques 37

About Formulas 37Calculating Formulas 38Cell and Range References 39Why use references that aren’t relative? 39About R1C1 notation 40Referencing other sheets or workbooks 41Using Names 42Naming cells and ranges 42Applying names to existing references 43Intersecting names 44Naming columns and rows 45Scoping names 45Naming constants 46Naming formulas 46Naming objects 48Formula Errors 48Array Formulas 49

An array formula example 50

An array formula calendar 51Array formula pros and cons 52Counting and Summing Techniques 52Using the COUNTIF or SUMIF function 52Using array formulas to count and sum 53Other counting tools 54Working with Dates and Times 55Entering dates and times 55Using pre-1900 dates 56Creating Megaformulas 56

Chapter 4: Understanding Excel’s Files 61

Starting Excel 61Excel’s File Extensions 63Spreadsheet File Formats Supported 64Lotus 1-2-3 spreadsheet files 64Quattro Pro spreadsheet files 65

Trang 25

Database file formats 66Text file formats 66Other file formats 66Files Written by Excel 67XLS files 67Workspace files 68Template files 68Toolbar files 69Add-in files 69Excel and HTML 70

So how does it work? 70Adding some complexity 71What about interactivity? 72Excel Settings in the Registry 74About the Registry 74Excel’s settings 75

Chapter 5: What Is a Spreadsheet Application? 81

Spreadsheet Applications 81The Developer and the End User 83Who are developers? What do they do? 83Classifying spreadsheet users 84The audience for spreadsheet applications 85Why people use spreadsheets 86Solving Problems with a Spreadsheet 88Basic Spreadsheet Types 89Quick-and-dirty spreadsheets 90For-your-eyes-only spreadsheets 90Single-user applications 90Spaghetti applications 91Utility applications 91Add-ins that contain worksheet functions 92Single-block budgets 92What-if models 93Data storage and access spreadsheets 93Database front ends 94Turnkey applications 94

Chapter 6: Essentials of Spreadsheet Application Development 95

Determining User Needs 96Planning an Application That Meets User Needs 97

Trang 26

Determining the Most Appropriate User Interface 100Creating custom dialog boxes 100Using ActiveX controls on a worksheet 101Customizing menus 103Customizing toolbars 105Creating shortcut keys 106Executing the development effort 107Concerning Yourself with the End User 107Testing the application 107Making the application bulletproof 109Making the application aesthetically appealing and intuitive 110Documenting the development effort 111Distributing the application to the user 112Updating the application when necessary 113Other Development Issues 113The user’s installed version of Excel 114Language issues 114System speed 114Video modes 115Directory structure 115

Part III: Understanding Visual Basic for Applications 117

Chapter 7: Introducing Visual Basic for Applications 119

Some BASIC Background 119About VBA 120Object models 120VBA versus XLM 120VBA versus Lotus macros 121VBA versus LotusScript 122The Basics of VBA 122Introducing the Visual Basic Editor 125Activating the VBE 125The VBE windows 126Working with the Project Explorer 128Adding a new VBA module 129Removing a VBA module 129Exporting and importing objects 129Working with Code Windows 130Minimizing and maximizing windows 130Storing VBA code 131Entering VBA code 132Customizing the VBE Environment 138Using the Editor tab 138Using the Editor Format tab 141Using the General tab 142Using the Docking tab 143

Trang 27

The Macro Recorder 143What is recorded 144Relative or absolute? 145Recording options 149Cleaning up recorded macros 150About Objects and Collections 152The object hierarchy 152About collections 153Object referral 153Properties and Methods 154Object properties 154Object methods 155The Comment Object: A Case Study 157Online help for the Comment object 157Properties of a Comment object 158Methods of a Comment object 158The Comments collection 159About the Comment property 160Objects within a Comment object 161Determining whether a cell has a comment 163Adding a new Comment object 163Some useful application properties 163Working with Range Objects 165The Range property 166The Cells property 167The Offset property 169Things to Know about Objects 170Esoteric but essential concepts to remember 170Learn more about objects and properties 171

Chapter 8: VBA Programming Fundamentals 177

VBA Language Elements: An Overview 177Comments 178Variables, Data Types, and Constants 181Defining data types 182Declaring variables 184Scoping variables 186Working with constants 190Working with strings 191Working with dates 192Assignment Statements 193Arrays 195Declaring arrays 195Declaring multidimensional arrays 196Object Variables 196User-Defined Data Types 198Built-in Functions 198

Trang 28

Manipulating Objects and Collections 201With-End With constructs 202For Each-Next constructs 202Controlling Execution 204GoTo statements 205If-Then constructs 205Select Case constructs 208Looping blocks of instructions 212

Chapter 9: Working with VBA Sub Procedures 219

About Procedures 219Declaring a Sub procedure 220Scoping a procedure 221Executing Procedures 222Executing a procedure with the Run Í Run Sub/

UserForm command 223Executing a procedure from the Macro dialog box 223Executing a procedure using a Ctrl+shortcut key combination 224Executing a procedure from a custom menu 225Executing a procedure from another procedure 227Executing a procedure from a toolbar button 230Executing a procedure by clicking an object 231Executing a procedure when an event occurs 233Executing a procedure from the Immediate window 233Passing Arguments to Procedures 234Error-Handling Techniques 237Trapping errors 238Error-handling examples 239

A Realistic Example 241The goal 241Project requirements 242What you know 242The approach 243What you need to know 243Some preliminary recording 243Initial setup 245Code writing 246Sort procedure writing 247More testing 250Fixing the problems 251Utility availability 254Evaluating the project 254

Chapter 10: Creating Function Procedures 257

Sub Procedures versus Function Procedures 257Why Create Custom Functions? 258

Trang 29

An Introductory Example 258

A custom function 258Using the function in a worksheet 259Using the function in a VBA procedure 260Analyzing the custom function 260Function Procedures 262Declaring a function 262

A function’s scope 263Executing function procedures 263Function Arguments 266Function Examples 266

A function with no argument 266Another function with no argument 267

A function with one argument 268

A function with two arguments 271

A function with an array argument 272

A function with optional arguments 273

A function that returns a VBA array 274

A function that returns an error value 276

A function with an indefinite number of arguments 278Emulating Excel’s SUM function 279Debugging Functions 281Dealing with the Insert Function Dialog Box 282Specifying a function category 283Adding a function description 284Using Add-ins to Store Custom Functions 286Using the Windows API 287Windows API examples 287Determining the Windows directory 288Detecting the Shift key 289Learning more about API functions 290

Chapter 11: VBA Programming Examples and Techniques 291

Working with Ranges 292Copying a range 292Moving a range 293Copying a variably sized range 293Selecting or otherwise identifying various types of ranges 294Prompting for a cell value 296Entering a value in the next empty cell 298Pausing a macro to get a user-selected range 299Counting selected cells 300Determining the type of selected range 301Looping through a selected range efficiently 302Deleting all empty rows 305Determining whether a range is contained in another range 305Determining a cell’s data type 306

Trang 30

Reading and writing ranges 307

A better way to write to a range 308Transferring one-dimensional arrays 310Transferring a range to a variant array 310Selecting the maximum value in a range 311Selecting all cells with a particular format 312Working with Workbooks and Sheets 314Saving all workbooks 314Saving and closing all workbooks 315Accessing workbook properties 315Synchronizing worksheets 316VBA Techniques 317Toggling a Boolean property 317Determining the number of printed pages 318Displaying the date and time 318Getting a list of fonts 320Sorting an array 321Processing a series of files 323Some Useful Functions for Use in Your Code 325The FileExists function 325The FileNameOnly function 325The PathExists function 326The RangeNameExists function 326The SheetExists function 326The WorkbookIsOpen function 327Retrieving a value from a closed workbook 328Some Useful Worksheet Functions 329Returning cell formatting information 329Displaying the date a file was saved or printed 330Understanding object parents 331Counting cells between two values 332Counting visible cells in a range 332Determining the last nonempty cell in a column or row 333Does a string match a pattern? 335Extracting the nth element from a string 336

A multifunctional function 337The SHEETOFFSET function: Version 1 338The SHEETOFFSET function: Version 2 339Returning the maximum value across all worksheets 339Returning an array of nonduplicated random integers 340Randomizing a range 342Windows API Calls 344Determining file associations 344Determining default printer information 345Determining the current video mode 346Adding sound to your applications 347Reading from and writing to the Registry 349

Trang 31

Part IV: Working with UserForms 353

Chapter 12: Custom Dialog Box Alternatives 355

Before You Create That UserForm 355Using an Input Box 355VBA’s InputBox function 356Excel’s InputBox method 357VBA’s MsgBox Function 359Excel’s GetOpenFilename Method 364Excel’s GetSaveAsFilename Method 367Prompting for a Directory 368Using a Windows API function to select a directory 368Using the FileDialog object to select a directory 370Displaying Excel’s Built-In Dialog Boxes 371Using the Dialogs collection 371Learning more about built-in dialog boxes 373Using arguments with built-in dialog boxes 373Executing a menu item directly 374

Chapter 13: Introducing UserForms 377

How Excel Handles Custom Dialog Boxes 377Inserting a New UserForm 378Displaying a UserForm 378Adding Controls to a UserForm 379Controls Available to You 380CheckBox 380ComboBox 380CommandButton 380Frame 380Image control 380Label 381ListBox 381MultiPage 381OptionButton 381RefEdit 381ScrollBar 381SpinButton control 382TabStrip 382TextBox 382ToggleButton 382Adjusting UserForm Controls 382Adjusting a Control’s Properties 385Using the Properties window 385Common properties 386Learning more about properties 387Accommodating keyboard users 387

Trang 32

Displaying and Closing UserForms 389Displaying a UserForm 389Closing a UserForm 389About event-handler procedures 391Creating a UserForm: An Example 391Creating the UserForm 391Writing code to display the dialog box 394Trying it out 395Adding event-handler procedures 396Validating the data 398Now it works 398UserForm Events 398Learning about events 399UserForm events 399Example: SpinButton events 400Pairing a SpinButton with a TextBox 402Referencing UserForm Controls 404Customizing the Toolbox 406Changing icons or tip text 406Adding new pages 406Customizing or combining controls 406Adding new ActiveX controls 407Creating UserForm “Templates” 408

A UserForm Checklist 408

Chapter 14: UserForm Examples 411

Creating a UserForm “Menu” 411Using CommandButtons 411Using a ListBox 412Selecting Ranges 413Creating a “Splash Screen” 414Disabling a UserForm’s Close Button 416Changing a Dialog Box’s Size 417Zooming and Scrolling a Sheet from a UserForm 418ListBox Techniques 420About the ListBox control 421Adding items to a ListBox control 421Determining the selected item 425Determining multiple selections 426Multiple lists in a single ListBox 426ListBox item transfer 427Moving items in a ListBox 428Working with multicolumn ListBox controls 430Using a ListBox to select worksheet rows 432Using a ListBox to activate to a sheet 434Using the MultiPage Control 436

Trang 33

Chapter 15: Advanced UserForm Techniques 439

Displaying a Progress Indicator 439Creating a standalone progress indicator 440Showing progress using a MultiPage control 442Showing progress without using a MultiPage control 445Creating Wizards 445Setting up the MultiPage control 446Adding the buttons 447Programming the buttons 447Programming dependencies 449Performing the task 450Final steps 451Emulating the MsgBox Function 452MyMsgBox code 452How it works 453Using the MyMsgBox function 455

A Modeless Dialog Box 455Multiple Buttons, One Event-Handler 458Procedure 459Adapting this technique 461

A Color Picker Dialog 461Displaying a Chart in a UserForm 463Method 1: Save the chart as a file 463Method 2: Use the OWC ChartSpace control 464Displaying a Spreadsheet in a UserForm 467

An Enhanced Data Form 471Description 472Installing the add-in 473Using the Enhanced Data Form 473

Chapter 16: Developing Excel Utilities with VBA 477

About Excel Utilities 477Using VBA to Develop Utilities 478What Makes a Good Utility? 478Text Tools: The Anatomy of a Utility 479Background 479Project goals for Text Tools 480How it works 480The Text Tools workbook 481The FormMain UserForm 481The modMain module 483The ApplyButton_Click procedure 486The “task” procedures 488The undo technique 497The ShowStats procedure 498

Trang 34

User help technique 500Create menu and delete menu procedures 500Evaluation of the project 501Understand the Text Tools utility 502More About Excel Utilities 502

Chapter 17: Working with Pivot Tables 505

An Introductory Example 505Creating a pivot table 506Examining the recorded code 508Cleaning up the recorded code 508Creating a More Complex Pivot Table 509The data 509The pivot table 510The code that created the pivot table 511How it works 513Creating a Pivot Table from an External Database 513Creating Multiple Pivot Tables 515Modifying Pivot Tables 518

Chapter 18: Working with Charts 521

About Charts 521Chart locations 521The Chart object model 522Recording Chart Macros 524Macro recorder output 524The “cleaned up” macro 526Common VBA Charting Techniques 527Activating a chart 527Deactivating a chart 529Determining whether a chart is activated 529Deleting from ChartObjects or charts 530Applying chart formatting 530Looping through all charts 531Sizing and aligning ChartObjects 532More Charting Examples 533Using names in a SERIES formula 534Specifying the data used by a chart 535Determining a chart’s source data: Method 1 538Determining a chart’s source data: Method 2 543Displaying arbitrary data labels on a chart 546Displaying a chart in a UserForm 549Understanding Chart Events 551

An example of using Chart events 552Enabling events for an embedded chart 555Example: Using Chart events with an embedded chart 557

Trang 35

Charting Tricks 559Printing embedded charts on a full page 559Creating a “dead chart” 560Controlling a data series by hiding data 560Storing multiple charts on a chart sheet 562Using linked pictures in a chart 563Animated charts 565Creating a hypocycloid chart 566Creating a “clock” chart 567Drawing with an XY chart 569

Chapter 19: Understanding Excel’s Events 571

Event Types That Excel Can Monitor 572What You Should Know about Events 572Understanding event sequences 572Where to put event-handler procedures 573Disabling events 574Entering event-handler code 576Event-handler procedures that use arguments 577Workbook-Level Events 578The Open event 579The Activate event 580The SheetActivate event 580The NewSheet event 581The BeforeSave event 581The Deactivate event 581The BeforePrint event 582The BeforeClose event 583Worksheet Events 585The Change event 585Monitoring a specific range for changes 586The SelectionChange event 590The BeforeRightClick event 591Chart Events 592Application Events 592Enabling Application-level events 595Determining when a workbook is opened 595Monitoring Application-level events 597UserForm Events 598Events Not Associated with an Object 599The OnTime event 599The OnKey event 600

Chapter 20: Interacting with Other Applications 603

Starting Another Application 603Activating Another Application 607Running Control Panel Dialog Boxes and Wizards 608

Trang 36

Automation 609Working with foreign objects 609Early versus late binding 610

A simple example 613Controlling Word from Excel 613Controlling Excel from another application 616Working with ADO 619Using SendKeys 621

Chapter 21: Creating and Using Add-Ins 625

What Is an Add-In? 625Comparing an add-in to a standard workbook 625Why create add-ins? 626Understanding Excel’s Add-In Manager 627Creating an Add-In 628

An Add-In Example 629Setting up the workbook 629Testing the workbook 630Adding descriptive information 630Creating the add-in 631Installing the add-in 632Distributing the add-in 633Modifying the add-in 633Comparing XLA and XLS Files 635File size and structure 635Collection membership 635Windows 635Sheets 636Accessing VBA procedures in an add-in 637Manipulating Add-Ins with VBA 639The AddIns collection 639AddIn object properties 641AddIn object events 644Optimizing the Performance of Add-ins 644Code speed 644File size 645Special Problems with Add-Ins 646Ensuring that an add-in is installed 646Referencing other files 648Specifying the proper Excel version 649

Chapter 22: Creating Custom Toolbars 653

About Command Bars 653Toolbar Manipulations 654

Trang 37

How Excel Handles Toolbars 654Storing toolbars 654When toolbars don’t work correctly 655Manipulating Toolbars and Buttons Manually 655About command bar customization mode 656Distributing toolbars 660Manipulating the CommandBars Collection 661Command bar types 662Listing all CommandBar objects 662Creating a command bar 664Referring to command bars 665Deleting a command bar 665Properties of command bars 666Referring to controls in a command bar 671Listing the controls on a command bar 672Listing all controls on all toolbars 672Adding a control to a command bar 673Deleting a control from a command bar 674Properties of command bar controls 675

Chapter 23: Creating Custom Menus 685

A Few Words about Excel’s Menu Bar 685What You Can Do with Excel’s Menus 686Menu terminology 686Removing menu elements 687Adding menu elements 688Changing menu elements 688VBA Examples 689Listing menu information 689Adding a new menu to a menu bar 690Deleting a menu from a menu bar 694Adding menu items to a menu 694Displaying a shortcut key with a menu item 698Fixing a menu that has been reset 700Working with Events 701Adding and deleting menus automatically 701Disabling or hiding menus 702Working with checked menu items 703The Easy Way to Create Custom Menus 706Creating a Substitute Worksheet Menu Bar 708Working with Shortcut Menus 710Adding menu items to shortcut menus 712Deleting menu items from shortcut menus 713Disabling shortcut menu items 713Disabling shortcut menus 714Resetting shortcut menus 714Creating new shortcut menus 714

Trang 38

Chapter 24: Providing Help for Your Applications 719

Help for Your Excel Applications? 719Help Systems That Use Excel Components 721Using cell comments for help 722Using a Text Box for help 722Using a worksheet to display help text 722Displaying help in a UserForm 723Using the Office Assistant to display help 727Using the WinHelp and HTML Help Systems 730About WinHelp 730About HTML Help 731Associating a Help File with Your Application 732Other Ways of Displaying WinHelp or HTML Help 736Using the Help method 736Displaying Help from a message box 736Displaying Help from an input box 737

Chapter 25: Developing User-Oriented Applications 739

What is a User-Oriented Application? 739the Loan Amortization Wizard 739Using the application 740The workbook structure 742How it works 743Potential enhancements 748Application Development Concepts 748Some Final Words 748

Chapter 26: Compatibility Issues 753

What Is Compatibility? 753Types of Compatibility Problems 754Excel File Formats Supported 755Avoid Using New Features 756Applications That Use Windows API Calls 757But Will It Work on a Mac? 758Creating an International Application 759Multilanguage applications 761VBA language considerations 762Using “local” properties 762Identifying system settings 763Date and time settings 766

Trang 39

Chapter 27: Manipulating Files with VBA 767

Performing Common File Operations 767VBA file-related commands 768Using the FileSearch object 771Locating files that contain specific text 773Using the FileSystemObject object 773Working with Text Files 775Opening a text file 776Reading a text file 777Writing a text file 777Getting a file number 777Determining or setting the file position 778Statements for reading and writing 778Text File Manipulation Examples 779Importing data in a text file 779Exporting a range to a text file 779Importing a text file to a range 781Logging Excel usage 782Filtering a text file 783Importing more than 256 columns of data 783Exporting a range to HTML format 786

Chapter 28: Manipulating Visual Basic Components 789

Introducing the IDE 789The IDE Object Model 791The VBProjects collection 791

An Introductory Example 794Replacing a Module with an Updated Version 795Using VBA to Write VBA Code 797Adding Controls to a UserForm at Design Time 800Design-time versus runtime UserForm manipulations 800Adding 100 CommandButtons at design time 802Creating UserForms Programmatically 804

A simple example 804

A useful (but not so simple) example 806

Chapter 29: Understanding Class Modules 811

What is a Class Module? 811Example: Creating a NumLock Class 812Inserting a class module 813Adding the VBA code 813Using the NumLock class 814More about Class Modules 815Naming the object class 815Programming properties 816Programming methods 817Class module events 818

Trang 40

Example: A CSV File Class 818Class module-level variables 819Property procedures 819Method procedures 820Using the CSVFileClass object 822

Chapter 30: Frequently Asked Questions about Excel Programming 825

General Excel Questions 826The Visual Basic Editor 830Procedures 834Functions 839Objects, Properties, Methods, and Events 842UserForms 851Add-Ins 856CommandBars 858

Appendix A: Excel Resources Online 861 Appendix B: VBA Statements and Functions Reference 867 Appendix C: VBA Error Codes 877 Appendix D: ANSI Code Reference 881 Appendix E: What’s on the CD-ROM 891

Index 907 End-User License Agreement 943 CD-ROM Installation Instructions 946

Ngày đăng: 14/08/2014, 02:20

TỪ KHÓA LIÊN QUAN