1. Trang chủ
  2. » Giáo Dục - Đào Tạo

excel programming weekend crash course®

458 723 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Tiêu đề Excel Programming Weekend Crash Course®
Tác giả Peter G. Aitken
Trường học Wiley Publishing, Inc.
Chuyên ngành Excel Programming
Thể loại Sách hướng dẫn
Năm xuất bản 2003
Thành phố New York
Định dạng
Số trang 458
Dung lượng 11,08 MB

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

Nội dung

Microsoft Excel is a powerful spreadsheet program; in fact, it’s the most widely usedspreadsheet program worldwide, but Excel is a lot more than just a spreadsheet gram.. Nearly any user

Trang 2

Excel Programming

Peter G Aitken

Trang 4

Excel Programming

Peter G Aitken

Trang 5

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 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: permcoordinator@wiley.com.

permit-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 pleteness of the contents of this book and specifically disclaim any implied warranties of merchantability

com-or fitness fcom-or a particular purpose No warranty may be created com-or extended by sales representatives com-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 out written permission All other trademarks are the property of their respective owners Wiley

with-Publishing, Inc., is not associated with any product or vendor mentioned in this book.

is a trademark of Wiley Publishing, Inc.

Trang 6

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, mia, and government since 1994

Trang 7

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

Trang 8

Microsoft 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 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 apowerful and full-featured programming language called Visual Basic for Applications (VBA)

pro-If you have recorded and played back an Excel macro, you have used VBA — perhaps out being aware of it

with-There’s much more to VBA programming than recording macros, however Nearly any usercan 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 entrysystem with custom forms and data validation Unfortunately, many users shy away fromtaking advantage of Excel’s programmability because it seems too complicated, and theycannot find a good source of information to guide them through the learning process Excelprogramming 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 Excelskills 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 haveany programming knowledge or experience to use this book because everything from squareone 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 utes Each session has a review section at the end and a list of questions so you can testyour knowledge The sessions are organized into six parts; the main purpose of each part is

min-Preface

Trang 9

to provide a convenient breaking point to help you in pacing your progress At the end ofeach part, you’ll find additional questions related to that part’s session topics The answersfor 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 inthis session

The second session teaches you how to use the VBA Code Editor This tool is part of theExcel 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 cation makes available for you to use in your programs

appli-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 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, andtext The final session in this part, Session 10, shows you how to work with Excel’s rangesand selections

lan-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 withfind 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 grams Then Sessions 19 and 20 present the basics of creating custom dialog boxes for yourprograms with Excel’s user forms

pro-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

Trang 10

Part VI: Sunday Afternoon

The remaining sessions deal with a variety of topics, including runtime errors, databasetasks, add-ins, and online help

I recommend that you work through the sessions in order At the very least you shouldcomplete 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 assessment test, which consists of over 80 multiple-choice and true or false questions Just

self-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 throughouteach 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 gramming Excel.

pro-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

Trang 11

Menu selections are indicated using the ➪ symbol Thus, File ➪ Save means to open theFile menu and then select the Save command.

Code and VBA keywords in the text are indicated by a special font like this Code 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:

list-SaveAs filename

When you enter this code, you do not actually type filename Rather, you replace

file-name with a specific filefile-name as explained in the text.

Trang 12

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 thanksalso go to Technical Editor, Ken Slovak, and the Copy Editor, Susan Hobbs

Acknowledgments

Trang 14

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

Trang 15

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

Trang 16

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

Trang 17

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

Trang 18

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

Trang 19

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

Trang 20

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

Trang 21

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

Trang 22

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

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

Creating Property Procedures 331 The Property Variable 332

Trang 23

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

Trang 24

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

Trang 26

Excel Programming

Trang 28

Part I — Friday Evening

Trang 29

Friday Evening

Trang 30

Session Checklist

✔The advantages of Excel programming

✔Fundamentals of programming

✔The Excel object model

✔Programming and macros

✔Designing your custom application

✔Your first Excel program

Most people think of Excel as merely a spreadsheet program, and with good reason —

Excel is a spreadsheet program As a spreadsheet program, Excel is a powerful

appli-cation that provides a wide range of tools for the manipulation, analysis, and play of data The majority of users never go beyond using Excel in this way — truth be told,many users have no need

dis-Under the surface, however, Excel is much more than an application program It provides

a sophisticated programming language that enables you to control any and all aspects of theprogram Anything you can do with the keyboard and mouse you can also do with program-ming For the power user, programming turns Excel into a flexible development tool for thecreation of custom solutions to your data manipulation and analysis needs This sessiontakes a look at the advantages of Excel programming, and provides necessary backgroundinformation on the technologies that are involved

Advantages of Programming

Programming offers several important advantages to the Excel user As mentioned earlier inthis session, these advantages will not be relevant to all users, but they can apply to a sur-prisingly large percentage of situations

Microsoft Excel Programming —

Why and How

1

Trang 31

Saving Time

Just about anything that a program can do in Excel can also be accomplished by a user with

a keyboard and mouse In a race, however, the program is always faster Even if you are anexpert user and do not need to spend any time figuring out how to perform the requiredtasks, a program will still beat you by a huge margin What might take you half an hour toperform manually will be done in a few seconds by a program

Reducing Errors

Even the most skilled typist hits the wrong key now and then, and every “mouse master”has been known to click the wrong button or command once in a while In contrast, pro-grams do not make mistakes — they are reliable servants, carrying out your commands overand over again with complete accuracy

This is not to say that programs cannot contain errors A program will do exactly whatthe programmer tells it to do; if your instructions are wrong or incomplete, the resultingprogram can cause errors Dealing with program errors is an important topic, enough so that

an entire session is devoted to it

for-Integrating with Other Applications

Excel does not always work alone — it has the capability to share data and interact withother applications These capabilities are most developed with, but not restricted to, otherMicrosoft Office applications For example, an Excel program could use Outlook to create ane-mail message containing data from a spreadsheet and then send the message to a list ofrecipients Programming is not required for Excel to interact with other programs, but itmakes tasks possible that would be difficult or impractical to perform otherwise

Programming Fundamentals

What exactly is programming? It’s really not as mysterious as it may sound Perhaps youalready have some experience with computer programming of one sort of another If not, thissection gives you some background information about what programming is and how it works

Trang 32

Creating Instructions

Programming is really nothing more than creating instructions that tell the computer what

to do In an office, for example, you might ask your assistant to make copies — that’s aninstruction A computer program is the same — you tell the computer what to do Theprimary difference is that computers are really dumb and can’t figure out the fine points

on their own, so you must tell them exactly what to do in excruciating detail Explicitinstructions are at the heart of any program

Some instructions manipulate data This can be as simple as adding two numbers, or ascomplex as creating a chart Other instructions control the execution of the program itself.For example, a program could be designed to perform one task on weekdays and anothertask on weekends Still other instructions control how the program interacts with the user,such as how it responds to the user’s selections from a menu or dialog box

 Data stored outside the program For the most part, this category comprises data

that is stored in the cells of an Excel worksheet Your program does not need tocreate storage for such data, although the program can read and write it

 Data stored within the program For data that is not stored elsewhere, a program

needs to create a storage location A program uses variables to store internal data.

As you’ll see in later sessions, Excel programming offers a wide range of internaldata storage capabilities

When you are programming with Excel, the data-handling capabilities available to youare quite impressive They provide a variety of data types that are specialized for storingdifferent kinds of data You learn more about these data types in later sessions

The VBA Language

You will use the VBA language to write Excel programs VBA stands for Visual Basic forApplications, and it is one of the two essential parts of Excel programming The name VisualBasic for Applications reflects the fact that VBA is based on Microsoft’s Visual Basic program-ming language, and that it is designed for programming within applications — specifically,the applications that comprise the Microsoft Office suite (Excel, Word, Access, PowerPoint,and Outlook) VBA is relatively easy to learn, as programming languages go, but does notsacrifice power and flexibility

The task of programming in VBA is simplified by the VBA Editor, which is part of yourExcel installation You can open the VBA Editor by pressing Alt+F11 when in Excel, or by

Trang 33

selecting Tools ➪ Macro ➪ Visual Basic Editor from the menu The VBA Editor is shown inFigure 1-1 The blank window is where you enter your program’s VBA code Other elements

in the Editor provide tools for organizing, running, and debugging your programs Later sions cover these features

ses-Figure 1-1 The VBA Editor

The Excel Object Model

The other essential component of Excel programming is the Excel object model To stand the object model, it helps to have some background information about the innerworkings of programs such as Excel

under-Objects

As computer programming evolved over the years, programs have gotten more powerful and,unavoidably, more complicated With increasing complexity came an increased possibility oferrors, and programmers found themselves spending more and more time tracking down andfixing the causes of these errors It soon became apparent that many, if not most, programerrors were caused by unexpected and unintended interactions between various parts of aprogram If a programmer could reduce or eliminate these interactions, errors would be dras-tically curtailed

At the same time, programmers found themselves writing the same program functionalityover and over again Most Windows programs have a menu, for example, and programmers

Trang 34

would have to write the code for a menu from scratch for each new program It would bemuch better if the code for a menu could be written once and then reused as needed in newprograms.

These (and other) factors were the impetus behind the development of a programming

technique called object-oriented programming, or OOP With OOP, a program is viewed as a

collection of related sections, or modules, that have different functions Some of thesemodules are part of the program’s interface, such as menus, toolbars, and dialog boxes.Other modules relate to the data with which the program works, such as (for Excel) work-books, worksheets, and cells Each of these modules is an object; see the “Objects andClasses” sidebar for more information on nomenclature

OOP offers numerous advantages compared with older traditional methods of programming.These include:

 Reduced errors By design, objects are self-contained units that are isolated from

each other as much as possible An object’s interactions with the rest of the programare tightly controlled, and unintended interactions (and the resulting errors) areeliminated

 Code reuse An object — or more accurately, a class — is by its very nature reusable,

not only in the same program, but in other programs as well

Excel, as well as the other Office programs, was created using OOP techniques Under theskin, therefore, Excel consists of a large collection of objects that work together to provide theprogram’s functionality You’ll see how this relates to programming Excel in the next section

Components and Automation

The objects that are part of the Excel application are written so that they are available to

other programs In computer talk, the objects are said to be exposed This is part of the

Component Object Model (COM) technology that is central to the Windows operating system

itself as well as to most applications that run on Windows The term component or COM

com-ponent is used to refer to objects that are exposed in this manner; therefore, the objects

that are exposed by Excel are sometimes referred to as components Note that a singlecomponent may expose more than one class

How does a programmer make use of exposed components? The answer is another COM

technology called automation (called OLE — object linking and embedding — automation

in the past) Automation permits an external program to access and control exposed

Objects and Classes

You’ll see the words object and class used in discussions of object-oriented

programming, often interchangeably Technically, they have different ings A class is a plan or definition, where an object is an implementation of

mean-that plan (sometimes called an instance) To use an analogy, the blueprints for

a car would be the class, while an actual car built from those plans would be

an object You can create multiple objects from the same class

Trang 35

components Automation also permits components to interact with each other — for ple, you could embed an Excel spreadsheet in a Word document For the present purposes,automation permits a VBA program to use the Excel components Other programming lan-guages, such as C++ or Java, can use automation too, but that is not relevant here.

exam-The COM components that your VBA programs can use exist as files on your hard disk andwere installed as part of the Office or Excel installation A component can operate in two ways:

 An automation client controls and makes use of classes exposed by other components

 An automation server exposes classes for use by other components

An automation component can act in one or both of these roles For programming Excel,VBA is acting as a client, and the Excel components are acting as servers Some Excel com-ponents act as clients to manipulate other components

The result of this arrangement is that an Excel programmer has VBA, a powerful ming language, as well as access to all of the components that comprise the Excel applica-tion This is an extremely powerful combination — Excel is your well-trained and capableservant, and VBA is the means you use to tell it what to do The sum of all the componentsexposed by Excel is referred to as the Excel object model

program-The Excel object model is covered in detail later in the book, primarily in Session 3.

Macros and Programming

If you have ever used Excel’s macro feature, you have already done some Excel ming A macro is a sequence of user actions that is recorded and can be played back later toduplicate the original actions This saves time because you don’t have to manually redo thesteps each time To record a macro, select Macro from Excel’s Tools menu and then selectRecord New Macro As you perform actions in Excel, they are translated into the correspond-ing VBA commands When you stop the recording, the resulting VBA is saved and can beplayed back as needed Recording macros can be a useful tool for the Excel programmer

program-Recording macros is covered in more detail in Session 2.

Designing Your Custom Application

When creating a custom Excel program, as with all programming, it is important to do someplanning before you start writing code The importance of planning cannot be overempha-sized For a simple project it may take only a few minutes; for a large, complex project, itmay take days In either case it is going to save you time and hassles down the road.Before you begin, make certain that you know what is needed A lot of problems canarise when there is a misunderstanding between the client and the programmer You may

Cross-Ref Cross-Ref

Trang 36

write a great program, but if it is not what the customer needs you have wasted your time!Don’t assume that you know what is wanted — make sure, in detail.

After you know your goal, start planning the details of the program For simple programsthis step may be trivial because there is only one way to accomplish the desired ends Withmore complex programs, you have choices to make How many worksheets and workbookswill be needed? Will any user forms be required? How will the functionality be divided up?Should you define any classes for the project? Of course, plans that you make at this stageare not set in stone — you can always modify them later as circumstances dictate Even so,having some plan at the outset, even if it is an incomplete plan, is a real help

Your First Excel Program

To give you a taste for Excel programming, this section presents a short program that trates some of the basic principles You are not expected to understand all the details of theprogram at this point, but working through the required procedures will help in under-standing the material in the following sessions

illus-This program does not do anything complicated The desired goal is to create a programthat does the following:

1 Starts with a blank worksheet.

2 Enables the user to enter a series of numbers in specified cells.

3 Calculates the sum of the numbers.

4 Saves the workbook to disk.

The following sections guide you through the process of creating and running this program

Creating and Naming the Program

These first steps create the basic program structure and assign a name to it

1 Start Excel As usual, it starts with three blank workbooks displayed.

2 Press Alt+F11 to open the VBA Editor.

3 At the top left of the VBA Editor, there is a window labeled “Project - VBAProject”

that lists the currently open worksheets: Sheet1, Sheet2, and Sheet3, as shown inFigure 1-2 Double-click the Sheet1 entry, and a code-editing window opens

4 Select Procedure from the Insert menu The Add Procedure dialog box displays.

Enter a name for your program, such as MyFirstProgram You can use letters andnumbers, but no spaces (some programmers use an underscore in place of spaces

to separate words)

5 Click OK The VBA Editor inserts the first and last lines of the procedure (program)

in the code-editing window (see Figure 1-3)

At this point, you have created the empty “skeleton” of your program Next, you add thecode that provides its functionality

Trang 37

Figure 1-2 Double-click the Sheet1 entry to open a code-editing window.

Figure 1-3 The VBA Editor inserts the first and last lines of the program.

Programs and Procedures

Is a program the same thing as a procedure? Not really Some simple programssuch as this one are contained in a single procedure More complex programscontain multiple procedures

Trang 38

Writing the Code

The tasks that the program’s code needs to perform are as follows:

1 Move the cursor to cell B2.

2 Accept a number from the user, and enter it in the cell.

3 Move to cell B3.

4 Repeat until numbers have been entered in five cells: B2 through B6.

5 Enter a formula in cell B7 to add the column of numbers.

6 Save the workbook to disk.

The code uses several elements of VBA and the Excel object model Before entering thecode, you should have some idea of how it works:

Range(“B2”).Select

This code uses the Rangeobject to move the Excel cursor to the indicated cell — in thiscase, cell B2

ActiveCell.Value = InputBox(“Enter Value”)

This code has two parts The InputBoxfunction displays a dialog box on the screen andprompts the user to enter data, using the supplied text “Enter Value” as the prompt text.The ActiveCellobject is then used to take the value entered by the user and insert it intothe currently active worksheet cell (the cell that the cursor is on)

The above two code elements repeat five times to enter values in cells B2 through B6.After moving the cursor to the cell B7, the following code executes:

ActiveCell.Formula = “=Sum(B2 B6”)

Here, the ActiveCellobject is used again, this time to enter a formula into the activeworksheet cell The formula uses Excel’s built-in Sumfunction to calculate the sum of thevalues in cells B2 through B6

Trang 39

Public Sub MyFirstProgram() Range(“B2”).Select

ActiveCell.Value = InputBox(“Enter value”) Range(“B3”).Select

ActiveCell.Value = InputBox(“Enter value”) Range(“B4”).Select

ActiveCell.Value = InputBox(“Enter value”) Range(“B5”).Select

ActiveCell.Value = InputBox(“Enter value”) Range(“B6”).Select

ActiveCell.Value = InputBox(“Enter value”) Range(“B7”).Select

ActiveCell.Formula = “=Sum(B2 B6)”

ActiveWorkbook.SaveAs Filename:=”MyFirstProgram.xls”

End Sub

Running the Program

After the code has been entered, you can run the program and see how it works Here arethe steps required:

1 Use the Windows taskbar to activate Excel.

2 Press Alt+F8 to open the Macros dialog box, shown in Figure 1-4 (You can also

dis-play this dialog box by selecting Tools ➪ Macro ➪ Macros from the Excel menu.)

Figure 1-4 Selecting the program to run

3 In the Macros dialog box, select Sheet1.MyFirstProgram (this name indicates that

the program is stored in Sheet1); then click the Run button

4 The program prompts you to enter a value, repeating this action five times.

When the program finishes, your worksheet should look like Figure 1-5 (although youentered different numbers, of course)

Trang 40

Even though this is a simple program, it illustrates some of the advantages of Excel gramming as related to accuracy and consistency Specifically, it ensures that:

pro- Data is entered into the proper worksheet cells

 The correct formula is used

 The workbook is saved under the correct name

With the fundamentals under your belt, you are ready to move on to the next sessionand start learning the details of Excel programming

Figure 1-5 The worksheet after the program runs

REVIEW

In this session you learned some of the fundamentals and background of Excel programming,including:

 There are several advantages of programming Excel

 You use the VBA language to write Excel programs

 Excels makes its functionality available to VBA as components

 The components that Excel exposes are collectively called the Excel object model

 Excel macros are a simple form of programming

 Planning ahead is important when designing a program

Ngày đăng: 01/06/2014, 09:41

TỪ KHÓA LIÊN QUAN