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

(Business solutions) bill jelen, tracy syrstad VBA and macros for microsoft excel que pub (2004)

570 579 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 570
Dung lượng 16,25 MB

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

Nội dung

Bill Jelen, “Mr. Excel,” is an accomplished Excel author and the principal behind the leading Excel Web site, MrExcel.com. As an Excel consultant, he has written Excel VBA solutions for hundreds of clients around the Englishspeaking world. His Web site hosts more than 10 million page views annually. Prior to founding MrExcel.com, Jelen spent 12 years in the trenches—working as a financial analyst for finance, marketing, accounting, and operations departments of a 500 million public company. He lives near Akron, Ohio, with this wife Mary Ellen and sons Josh and Zeke.

Trang 2

C o n t e n t s a t a G l a n c e

Introduction .1

I First Steps up the VBA Learning Curve 1 Unleash the Power of Excel with VBA! .11

2 This Sounds Like BASIC, So Why Doesn’t It Look Familiar? .29

3 Referring to Ranges .61

4 User-Defined Functions .75

5 Looping .103

6 R1C1 Style Formulas .117

7 Names .131

8 Event Programming .141

9 UserForms—An Introduction .161

II Automating Excel Power in VBA 10 Charts .175

11 Data Mining with Advanced Filter .207

12 Pivot Tables .235

13 Excel Power .291

14 Reading from and Writing to the Web .331

15 XML in Excel 2003 Professional .349

16 Automating Word .359

III Techie Stuff You Will Need to Produce Applications for the Administrator to Run 17 Arrays .379

18 Text File Processing .387

19 Using Access as a Back End to Enhance Multi-User Access to Data .401

20 Creating Classes, Records, and Collections .415

21 Advanced UserForm Techniques .433

22 Windows Application Programming Interface (API) .453

23 Handling Errors .467

24 Using Custom Menus to Run Macros .481

25 Add-Ins .497

26 Case Study—Designing an Excel Application .505

Index .517

Bill Jelen, Mr Excel Tracy Syrstad

800 East 96th Street

Indianapolis, Indiana 46240

for

Excel

?

Trang 3

VBA and Macros for Microsoft Excel

Copyright  2004 by Sams Publishing

All rights reserved No part of this book shall be reproduced,

stored in a retrieval system, or transmitted by any means,

elec-tronic, mechanical, photocopying, recording, or otherwise,

with-out written permission from the publisher No patent liability is

assumed with respect to the use of the information contained

herein Although every precaution has been taken in the

prepara-tion of this book, the publisher and author assume no

responsibil-ity for errors or omissions Nor is any liabilresponsibil-ity assumed for

damages resulting from the use of the information contained

herein

International Standard Book Number: 0-7897-3129-0

Library of Congress Catalog Card Number: 2004102247

Printed in the United States of America

First Printing: April 2004

Trademarks

All terms mentioned in this book that are known to be trademarks

or service marks have been appropriately capitalized Sams

Publishing cannot attest to the accuracy of this information Use

of a term in this book should not be regarded as affecting the

validity of any trademark or service mark

Warning and Disclaimer

Every effort has been made to make this book as complete and as

accurate as possible, but no warranty or fitness is implied The

information provided is on an “as is” basis The authors and the

publisher shall have neither liability nor responsibility to any

per-son or entity with respect to any loss or damages arising from the

information contained in this book

Bulk Sales

Sams Publishing offers excellent discounts on this book when

ordered in quantity for bulk purchases or special sales For more

information, please contact

U.S Corporate and Government Sales 1-800-382-3419

corpsales@pearsontechgroup.com

For sales outside of the U.S., please contact

International Sales 1-317-428-3341 international@pearsontechgroup.com

Trang 4

iii Contents

Contents

Introduction 1

Getting Results with VBA .1

What Is in This Book .3

Getting Up the Learning Curve .3

Excel VBA Power .3

The Techie Stuff Needed to Produce Applications for Others 3

Will This Book Teach Excel? .4

A Brief History of Spreadsheets and Macros .4

The Future of VBA and Excel 5

Special Elements and Typographical Conventions .6

Next Steps .7

I FIRST STEPS UP THE VBA LEARNING CURVE 1 Unleash the Power of Excel with VBA! 11

The Power of Excel .11

Barriers to Entry .11

The Macro Recorder Doesn’t Work! .11

Visual Basic Is Not Like BASIC .12

The Good News—It Is Easy to Climb the Learning Curve .12

The Great News—Excel with VBA Is Worth the Effort 12

Knowing Your Tools—The Visual Basic Toolbar .13

Macro Security .14

Very High Security .14

High Security .15

Medium Security .15

Low Security .15

Overview of Recording, Storing, and Running a Macro .15

Filling Out the Record Macro Dialog .15

Running a Macro 16

Creating a Macro Button .16

Assigning a Macro to a Form Control .17

Understanding the Visual Basic Editor (VBE) .18

VBE Settings .18

The Project Explorer .19

The Properties Window .20

Trang 5

Examining Code in the Programming Window 22

Running the Macro on Another Day Produces Undesired Results .24

A Possible Solution: Using Relative References when Recording .25

Frustration 28

Next Steps: Learning VBA Is the Solution .28

2 This Sounds Like BASIC, So Why Doesn’t It Look Familiar? 29

I Can’t Understand This Code .29

Understanding the Parts of VBA “Speech” 30

Is VBA Really This Hard? No! 33

VBA Help Files—Using F1 to Find Anything .33

Using Help Topics .35

Examining Recorded Macro Code—Using the VB Editor and Help .36

Optional Parameters .37

Defined Constants .37

Properties Can Return Objects 41

Using Debugging Tools to Figure Out Recorded Code 42

Stepping Through Code .42

More Debugging Options—Breakpoints .44

Backing Up or Moving Forward in Code .45

Not Stepping Through Each Line of Code .45

Querying Anything While Stepping Through Code 45

Using a Watch to Set a Breakpoint .50

Using a Watch on an Object 50

The Ultimate Reference to All Objects, Methods, Properties .51

Five Easy Tips for Cleaning Up Recorded Code .53

Tip 1: Don’t Select Anything .53

Tip 2: Ride the Range from the Bottom to Find Last Row .54

Tip 3: Use Variables to Avoid Hard-coding Rows and Formulas .55

Tip 4: Learn to Copy and Paste in a Single Statement .55

Tip 5: Use With End WithIf You Are Performing Multiple Actions to the Same Cell or Range of Cells .56

Putting It All Together—Fixing the Recorded Code 56

Next Steps .59

Trang 6

Contents

3 Referring to Ranges 61

TheRangeObject 61

Using the Top-Left and Bottom-Right Corners of a Selection to Specify a Range 62

Shortcut for Referencing Ranges 62

Named Ranges .62

Referencing Ranges in Other Sheets .63

Referencing a Range Relative to Another Range .63

Using the CellsProperty to Select a Range .64

Using the CellsProperty in the RangeProperty .65

Using the OffsetProperty to Refer to a Range .65

Using the ResizeProperty to Change the Size of a Range .67

Using the ColumnsandRowsProperties to Specify a Range 68

Using the UnionMethod to Join Multiple Ranges .68

Using the IntersectMethod to Create a New Range from Overlapping Ranges .69

Using the IsEmptyFunction to Check Whether a Cell Is Empty 69

Using the CurrentRegionProperty to Quickly Select a Data Range .70

Using the Areas Collection to Return a Non-contiguous Range 74

Next Steps .74

4 User-Defined Functions 75

Creating User-Defined Functions .75

Useful Custom Excel Functions 77

Set the Current Workbook’s Name in a Cell 77

Set the Current Workbook’s Name and File-Path in a Cell .77

Check Whether a Workbook Is Open .77

Check Whether a Sheet in an Open Workbook Exists 78

Count the Number of Workbooks in a Directory 79

Retrieve UserID 79

Retrieve Date and Time of Last Save .81

Retrieve Permanent Date and Time .81

Validate an Email Address .82

Sum Cells Based on the Interior Color .83

Retrieve Interior Cell Color Name or Index .84

Retrieve Text Color Index .87

Count Unique Values .88

Remove Duplicates from a Range .89

Find the First Non-Zero-Length Cell in a Range .91

Substitute Multiple Characters .92

Retrieve Numbers from Mixed Text 93

Trang 7

Convert Week Number into Date 94

Separate Delimited String .94

Sort and Concatenate 95

Sort Numeric and Alpha Characters .97

Search for a String Within Text .98

Reverse the Contents of a Cell .99

Multiple Max .99

Return Hyperlink Address .100

Return the Column Letter of a Cell Address .101

Static Random .101

Using Select Case on a Worksheet 101

Next Steps .102

5 Looping 103

For NextLoops .103

Using Variables in the ForStatement .106

Variations on the For NextLoop .106

Exiting a Loop Early After a Condition Is Met .107

Nesting One Loop Inside Another Loop .107

DoLoops .108

Using the WhileorUntilClause in DoLoops .111

While WendLoops .113

The VBA Loop:For Each 113

Object Variables .113

Next Steps .116

6 R1C1 Style Formulas 117

Referring to Cells: A1 Versus R1C1 References 117

Why Care About R1C1 Style? .117

Not Just an Annoyance .117

Switching Excel to Display R1C1 Style References .118

The Miracle of Excel Formulas .119

Enter a Formula Once and Copy 1,000 Times .119

The Secret—It Is Not That Amazing 120

Explanation of R1C1 Reference Style 121

Using R1C1 with Relative References .121

Using R1C1 with Absolute References .122

Using R1C1 with Mixed References 123

Referring to Entire Columns or Rows with R1C1 Style 123

Replacing Many A1 Formulas with a Single R1C1 Formula .124

Remembering Column Numbers Associated with Column Letters .125

Trang 8

vii Contents

Conditional Formatting—R1C1 Required .126

Setting Up Conditional Formatting in the User Interface .126

Setting Up Conditional Formats in VBA .127

Array Formulas Require Conditional Formatting .129

Next Steps .130

7 Names 131

Global Versus Local Names 131

Adding Names 132

Deleting Names .134

Types of Names .134

Formulas .134

Strings 135

Numbers .136

Using Arrays in Names .136

Reserved Names 137

Hiding Names .138

Checking for the Existence of a Name .138

Next Steps .140

8 Event Programming 141

Levels of Events 141

Using Events .141

Event Parameters .142

Enabling Events .142

Workbook Events .143

Workbook_Activate() .143

Workbook_Deactivate() .143

Workbook_Open() 143

Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) .144

Workbook_BeforePrint(Cancel As Boolean) 144

Workbook_BeforeClose(Cancel As Boolean) 145

Workbook_NewSheet(ByVal Sh As Object) .146

Workbook_WindowResize(ByVal Wn As Window) 146

Workbook_WindowActivate(ByVal Wn As Window) .146

Workbook_WindowDeactivate(ByVal Wn As Window) .146

Workbook_AddInInstall() 147

Workbook_AddInUninstall 147

Workbook_SheetActivate(ByVal Sh As Object) 147

Workbook_SheetBeforeDoubleClick (ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) 147

Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) 147

Workbook_SheetCalculate (ByVal Sh As Object) 147

Trang 9

Workbook_SheetChange (ByVal Sh As Object, ByVal Target As Range)148

Workbook_SheetDeactivate (ByVal Sh As Object) 148

Workbook_SheetFollowHyperlink (ByVal Sh As Object, ByVal Target As Hyperlink) 148

Workbook_SheetSelectionChange (ByVal Sh As Object, ByVal Target As Range) 148

Worksheet Events .148

Worksheet_Activate() 149

Worksheet_Deactivate() 149

Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) 149

Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean) 150

Worksheet_Calculate() .150

Worksheet_Change(ByVal Target As Range) 150

Worksheet_SelectionChange(ByVal Target As Range) 152

Worksheet_FollowHyperlink(ByVal Target As Hyperlink) .152

Chart Sheet Events .152

Embedded Charts 153

Chart_Activate() 153

Chart_BeforeDoubleClick(ByVal ElementID As Long, ByVal Arg1 As Long, ByVal Arg2 As Long, Cancel As Boolean) 154

Chart_BeforeRightClick(Cancel As Boolean) 154

Chart_Calculate() 154

Chart_Deactivate() 154

Chart_DragOver() 154

Chart_DragPlot() 154

Chart_MouseDown(ByVal Button As Long, ByVal Shift As Long, ByVal x As Long, ByVal y As Long) 154

Chart_MouseMove(ByVal Button As Long, ByVal Shift As Long, ByVal x As Long, ByVal y As Long) 155

Chart_MouseUp(ByVal Button As Long, ByVal Shift As Long, ByVal x As Long, ByVal y As Long) 155

Chart_Resize() 155

Chart_Select(ByVal ElementID As Long, ByVal Arg1 As Long, ByVal Arg2 As Long) .155

Chart_SeriesChange(ByVal SeriesIndex As Long, ByVal PointIndex As Long) 156

Application-Level Events .156

AppEvent_NewWorkbook(ByVal Wb As Workbook) 157

AppEvent_SheetActivate(ByVal Sh As Object) 157

AppEvent_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) 158

AppEvent_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) 158

AppEvent_SheetCalculate(ByVal Sh As Object) .158

AppEvent_SheetChange(ByVal Sh As Object, ByVal Target As Range) 158 AppEvent_SheetDeactivate(ByVal Sh As Object) .158

Trang 10

ix Contents

AppEvent_SheetFollowHyperlink(ByVal Sh As Object,

ByVal Target As Hyperlink) .158

AppEvent_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range) 158

AppEvent_WindowActivate(ByVal Wb As Workbook, ByVal Wn As Window) .158

AppEvent_WindowDeactivate(ByVal Wb As Workbook, ByVal Wn As Window) .159

AppEvent_WindowResize(ByVal Wb As Workbook, ByVal Wn As Window) 159 AppEvent_WorkbookActivate(ByVal Wb As Workbook) 159

AppEvent_WorkbookAddinInstall(ByVal Wb As Workbook) 159

AppEvent_WorkbookAddinUninstall(ByVal Wb As Workbook) 159

AppEvent_WorkbookBeforeClose(ByVal Wb As Workbook, Cancel As Boolean) 159

AppEvent_WorkbookBeforePrint(ByVal Wb As Workbook, Cancel As Boolean) .160

AppEvent_WorkbookBeforeSave(ByVal Wb As Workbook, ByVal SaveAsUI As Boolean, Cancel As Boolean) .160

AppEvent_WorkbookNewSheet(ByVal Wb As Workbook, ByVal Sh As Object) .160

AppEvent_WorkbookOpen(ByVal Wb As Workbook) .160

Next Steps .160

9 UserForms—An Introduction 161

User Interaction Methods 161

InputBox 161

MsgBox .161

Creating a Userform .162

Calling and Hiding a Userform 163

Programming the UserForm .164

Using Basic Form Controls .165

Deciding Whether to Use ListBoxes or ComboBoxes in Your Forms 166

Adding Option Buttons to a UserForm .167

Adding Graphics to a UserForm 168

Using Spinbutton on a Userform 169

Using the Multipage Control to Combine Forms 170

Verifying Field Entry 170

Illegal Window Closing .171

Next Steps .172

II AUTOMATING EXCEL POWER IN VBA 10 Charts 175

Overview .175

Embedded Charts Versus ChartSheets 176

Embedded Charts in a ChartObjectContainer .176

Charts on a Chart Sheet Have No Container .178

Trang 11

Creating a Chart with VBA .178

Moving from Embedded to Chart Sheet and Vice-Versa .181

The Default Chart Type 181

Using Object Variables to Streamline Code .182

The Anatomy of a Chart .183

The Chart Area—VBA Name:ChartArea 183

The Plot Area—VBA Name:PlotArea 186

The Data Series—VBA Name:Series 188

The Chart Axes—VBA Name:Axis 189

Grid Lines—VBA Name:HasMajorGridlinesandHasMinorGridlines 191

Data Labels—VBA Name:DataLabelsandDataLabel 191

Chart Title, Legend, and Data Table—VBA Name:ChartTitle,HasLegend, and HasDataTable 192

Trendlines and Error Bars—VBA Name:TrendlinesandErrorBar 193

Table of Chart Types .195

Details of Various Chart Types .198

Settings for 3D Charts .198

Settings for Pie Charts .199

Interactive Charts .201

Using Events with Charts 201

Exporting Charts as Images .202

Drawing with X-Y Charts .203

Custom Charts with VBA 204

Pie Bubble Chart .204

Speedometer Chart .204

Supply Curve Chart 205

Hierarchical Donut Chart .205

Next Steps .206

11 Data Mining with Advanced Filter 207

Advanced Filter Is Easier in VBA Than in Excel 207

Using Advanced Filter to Extract a Unique List of Values .208

Extracting a Unique List of Values with the User Interface .208

Extracting a Unique List of Values with VBA Code .209

Getting Unique Combinations of Two or More Fields 214

Using Advanced Filter with Criteria Ranges .215

Joining Multiple Criteria with a Logical OR 217

Joining Two Criteria with a Logical AND .217

Other Slightly Complex Criteria Ranges .218

Trang 12

xi Contents

The Most Complex Criteria—Replacing the List of Values with a Condition Created as

the Result of a Formula .218

Being Prepared for No Records After the Filter 224

Using “Filter in Place” in Advanced Filter .225

Catching No Records When Using Filter In Place .225

Showing All Records After Filter In Place .226

Using Filter In Place with Unique Records Only .226

The Real Workhorse:xlFilterCopywith All Records Instead of Unique Records Only .226

Copying All Columns .227

Copying a Subset of Columns and Reordering .228

AutoFilters 233

Next Steps .234

12 Pivot Tables 235

Versions .235

Creating a Vanilla Pivot Table in Excel Interface .236

Building a Pivot Table in Excel VBA .238

Getting a Sum Instead of Count .240

Cannot Move or Change Part of a Pivot Report .241

Figuring the Size of a Finished Pivot Table .241

Revenue by Customer for a Product Line Manager .243

Eliminating Blank Cells in the Data Area .245

Using AutoSort to Control the Sort Order .246

Controlling the Sort Order Manually .247

Changing the Default Number Format .247

Suppressing Subtotals for Multiple Row Fields .249

Suppressing Grand Total for Rows 250

Handling Additional Annoyances .250

Creating a New Workbook to Hold the Report .250

Moving the Summary to a Blank Report Worksheet .251

Filling in the Outline View .252

Final Formatting 253

Adding Subtotals .254

Putting It All Together .255

Product Profitability—Issues with Two or More Data Fields 258

Defining Calculated Data Fields .260

Avoid Calculated Items 263

Summarizing Date Fields with Grouping .264

Grouping by Week .267

Measuring Order Lead Time by Grouping Two Date Fields 269

Trang 13

Advanced Pivot Table Techniques .271

Using the Top 10 AutoShow Feature to Produce Executive Overviews .271

Using Pivot Table ShowDetailto Filter a Recordset .274

Using a Page Field to Create Reports for Each Region or Product .276

Manually Filtering to Two or More Items in a PivotField 280

Sum, Average, Count, Min, Max, and More 284

Reporting Percentages .286

Percentage of Total 286

Percentage Growth from Previous Month .286

Percentage of a Specific Item .287

Running Total .287

Next Steps .289

13 Excel Power 291

Using VBA to Extend Excel .291

Conditional Formatting with More Than Three Conditions .291

AutoFilter with More Than Two Conditions 292

File Operations .293

List Files in a Directory 293

Delete a Workbook After a Specific Date 295

Close and Delete 295

Import CSV .297

Read Entire CSV to Memory and Parse .298

Combining and Separating Workbooks .299

Separate Worksheets into Workbooks 299

Combine Workbooks .300

Filter and Copy Data to Separate Worksheets 301

Export Data to Word 302

Working with Cell Comments 303

List Comments .303

Resize Comments .304

Resize Comments with Centering .305

Place a Chart in a Comment .306

Utilities to Wow Your Clients .308

Using Conditional Formatting to Highlight Selected Cell .308

Highlight Selected Cell Without Using Conditional Formatting .309

Custom Transpose Data .310

Select/Deselect Non-contiguous Cells .311

Techniques for VBA Pros .313

Speedy Page Setup .313

Calculating Time to Execute Code .315

Disable Cut, Copy, and Paste 316

Custom Sort Order .318

Trang 14

xiii Contents

Cell Progress Indicator .319

Protected Password Box 320

Change Case .322

Custom Delete Event .323

Selecting with SpecialCells 324

Delete Rows with Conditions 325

Hide the Formula Bar 326

Cool Application .327

Historical Stock/Fund Quotes 327

Disable Cut, Copy, and Paste 328

Next Steps .330

14 Reading from and Writing to the Web 331

Getting Data from the Web .331

Manually Creating a Web Query and Refreshing with VBA .332

Using VBA to Update an Existing Web Query .333

Building a New Web Query with VBA .334

Using Streaming Data 336

UsingApplication.OnTimeto Periodically Analyze Data .337

Scheduled Procedures Require Ready Mode .337

Specifying a Window of Time for an Update .338

Cancelling a Previously Scheduled Macro 338

Closing Excel Cancels All Pending Scheduled Macros 339

Scheduling a Macro to Run x Minutes in the Future .339

Scheduling a Macro to Run Every Two Minutes .339

Publishing Data to a Web Page .341

Using VBA to Create Custom Web Pages .343

Using Excel as a Content Management System .344

Bonus—FTP from Excel .347

Next Steps .347

15 XML in Excel 2003 Professional 349

What Is XML? .349

Simple XML Rules .350

Universal File Format .350

XML as the New Universal File Format .351

The Alphabet Soup of XML 352

Using XML to Round-Trip a Workbook from Excel to HTML and Back .353

Next Steps .358

Trang 15

16 Automating Word 359

Early Binding 359

Compile Error: Can’t Find Object or Library .361

Late Binding .362

Creating and Referencing Objects .363

Keyword New 363

CreateObjectFunction .363

GetObjectFunction .363

Word’s Objects 364

DocumentObject .365

SelectionObject .367

RangeObject .368

Bookmarks .371

Next Steps .376

III TECHIE STUFF YOU WILL NEED TO PRODUCE APPLICATIONS FOR THE ADMINISTRATOR TO RUN 17 Arrays 379

Declare an Array .379

Multidimensional Arrays .380

Fill an Array .380

Empty an Array .382

Arrays Can Make It Easier to Manipulate Data, But Is That All? .383

Dynamic Arrays 385

Passing an Array .386

Next Steps .386

18 Text File Processing 387

Importing from Text Files .387

Importing Text Files with Less Than 65,536 Rows .387

Reading Text Files with More Than 65,536 Rows .394

Writing Text Files .398

Next Steps .399

19 Using Access as a Back End to Enhance Multi-User Access to Data 401

ADO Versus DAO .402

The Tools of ADO .404

Adding a Record to the Database .404

Retrieving Records from the Database .406

Updating an Existing Record .408

Trang 16

Deleting Records via ADO 410

Summarizing Records via ADO 410

Other Utilities via ADO .411

Checking for Existence of Tables .411

Checking for Existence of a Field .412

Adding a Table on the Fly 413

Adding a Field on the Fly .413

Next Steps .414

20 Creating Classes, Records, and Collections 415

Inserting a Class Module .415

Trapping Application and Embedded Chart Events .416

Application Events .416

Embedded Chart Events 418

Creating a Custom Object 420

Using a Custom Object .421

UsingProperty LetandProperty Getto Control How Users Utilize Custom Objects 422

Collections 424

Creating a Collection in a Standard Module .424

Creating a Collection in a Class Module .425

User-Defined Types (UDTs) .429

Next Steps .432

21 Advanced UserForm Techniques 433

Using the UserForm Toolbar in the Design of Controls on UserForms .433

Controls and Collections .434

More UserForm Controls 436

Toggle Buttons .436

Tabstrip .436

RefEdit .438

Modeless Userforms .438

Hyperlinks in Userforms .439

Adding Controls at Runtime 440

Resizing the Userform on the Fly .441

Adding a Control on the Fly .442

Sizing on the Fly 442

No AutoComplete Funtionality .442

Adding Other Controls .442

Adding an Image on the Fly .443

Putting It All Together .444

xv Contents

Trang 17

Using a Scrollbar as a Slider to Select Values .446

Adding Help Tips to Controls .447

Accelerator Keys .447

Control Tip Text .448

Tab Order .448

Coloring the Active Control 448

Transparent Forms .451

Next Steps .452

22 Windows Application Programming Interface (API) 453

What Is the Windows API? .453

Understanding an API Declaration .453

Using an API Declaration .454

API Examples .455

GetComputerName 455

FileIsOpen 456

Retrieve Display Resolution Information .457

Disable the Excel X for Closing the Application .458

Disable the X for Closing a Userform 459

Running Timer .460

Clickable Links on Forms .461

Playing Sounds 462

Retrieving a File Path 462

Finding More API Declarations 466

Next Steps .466

23 Handling Errors 467

What Happens When an Error Occurs .467

Debug Error Inside Userform Code Is Misleading 468

Basic Error Handling with the On Error GoToSyntax 470

Multiple Error Handlers .472

Generic Error Handlers .472

Handling Errors by Choosing to Ignore Them 472

Suppressing Excel Warnings .473

Encountering Errors on Purpose .474

Train Your Clients 474

Errors While Developing Versus Errors Months Later .475

Runtime Error 9: Subscript out of Range 475

RunTime Error 1004: Method ‘Range’ of Object ‘_Global’ Failed .476

The Ills of Protecting Code .477

Trang 18

More Problems with Passwords 478

Errors Caused by Different Versions .478

Next Steps .479

24 Using Custom Menus to Run Macros 481

Creating a Custom Menu .481

Deleting and Creating the Custom Menu .482

Adding a Single Menu Item 483

Breaking Items into Groups .484

Adding a Fly-out Menu .485

Creating a Custom Toolbar .487

Deleting and Creating the Toolbar .487

Adding Buttons to the Toolbar .488

UsingFaceIDCodes to Add Icons to the Toolbar .489

Adding Drop-downs to the Toolbar 489

Remembering a Toolbar’s Position .490

Other Ways to Run a Macro .491

Keyboard Shortcut .491

Attach a Menu to a Command Button .492

Attach a Macro to an ActiveX Control .494

Next Steps .496

25 Add-Ins 497

Characteristics of Standard Add-Ins .497

Converting an Excel Workbook to an Add-In 498

Using Save As to Convert a File to an Add-In .499

Using the VB Editor to Convert a File to an Add-In 499

Having Your Client Install the Add-In .500

Standard Add-Ins Are Not Secure .502

Closing Add-Ins .502

Removing Add-Ins .502

Using a Hidden Workbook as an Alternative to an Add-In 503

Next Steps .504

26 Case Study: Designing an Excel Application 505

About Tushar Mehta .505

Using Excel for More Than Number Crunching .506

The Solution .506

Implementing the Solution in Excel and VBA .507

Pass 1—Top-Down Concepts .508

Pass 1—Key Components Defined 509

Pass 2—Top-Down Code .510

xvii Contents

Trang 19

Pass 2—Key Components 511

Pass 3—Top-Down Code Completed .513

Pass 3—Key Components Completed .515

Summary 516

Next Steps .516

Index 517

Trang 20

About the Authors

About the Authors

Bill Jelen, “Mr Excel,” is an accomplished Excel author and the principal behind the

lead-ing Excel Web site, MrExcel.com As an Excel consultant, he has written Excel VBA tions for hundreds of clients around the English-speaking world His Web site hosts morethan 10 million page views annually Prior to founding MrExcel.com, Jelen spent 12 years

solu-in the trenches—worksolu-ing as a fsolu-inancial analyst for fsolu-inance, marketsolu-ing, accountsolu-ing, andoperations departments of a $500 million public company He lives near Akron, Ohio, withhis wife Mary Ellen and sons Josh and Zeke

Tracy Syrstad works as a programmer and consultant for the MrExcel Consulting team.

She remembers the painful trek up the VBA learning curve while developing applications

for co-workers at a former job She is co-editor of Holy Macro! It’s 1,900 Excel VBA Examples

CD and editor of Dreamboat On Word She lives on an arboreous acreage in eastern South

Dakota with her husband John and dog General

Trang 21

Thank you to Mala Singh of XLSoft Consulting for expertise with Chapter 10 Tom Urtisfor technical editing Jerry Kohl for many of the ideas in this book Jeanette Garcia, BarbJelen, and Doug and Stacy Jefferies for technical assistance Zeke, Josh, and Mary EllenJelen for their patience Tom Macioszek for peer review Chad Rothschiller at Microsoft forteaching me everything there is to know about Excel XML Dave Gainer, Steve Zaske, EricPatterson, and Joe Chirilov at Microsoft Loretta Yates, Sean Dixon, Margo Catts, AndyBeaster, Greg Wiegand, Amy Sorokas, Kim Spilker, Erika Millen, Kathy Bidwell, CindyTeeters, Michelle Mitchell, and Gary Adair at Pearson Ivana Taylor for her marketing bril-liance All the MrExcel.com readers and MVPs and clients Dan Bricklin, Bob Frankston,and Mitch Kapor for being spreadsheet pioneers William Brown at Waterside Pam Genselfor macro lesson number 1 Robert F Jelen for being my first programming fan Robert K.Jelen for inspiration Bonnie Hilliard for P.R Laurelle Riippa at PW Leo LaPorte andFawn Luu at TechTV Dan Poynter Craig Crossman at Computer America Walter

Mossberg at the Wall Street Journal.

—Bill

Thank you to Cort Chilldon-Hoff for offering support and being a sounding board when Iwas stumped Juan Pablo González Ruiz for offering his expertise, especially with the func-tions found in Chapter 4 Daniel Klann, Dennis Wallentin, Ivan F Moala, Juan PabloGonzález, Masaru Kaji, Nathan P Oliver, Richie Sills, Russell Hauf, Suat Mehmet Ozgur,Tom Urtis, Tommy Miles, Wei Jiang for their contributions to Chapter 13 Chris Lemairfor introducing me to Excel and the power of its macros Anne Troy who introduced Billand I in the first place The Computer America chat room for distracting me when I wassupposed to be working on the book

—Tracy

Trang 22

We Want to Hear from You!

We Want to Hear from You!

As the reader of this book, you are our most important critic and commentator We value

your opinion and want to know what we’re doing right, what we could do better, what areasyou’d like to see us publish in, and any other words of wisdom you’re willing to pass ourway

As an associate publisher for Sams, I welcome your comments You can email or write medirectly to let me know what you did or didn’t like about this book—as well as what we can

do to make our books better

Please note that I cannot help you with technical problems related to the topic of this book We do have a User Services group, however, where I will forward specific technical questions related to the book.

When you write, please be sure to include this book’s title and author as well as your name,email address, and phone number I will carefully review your comments and share themwith the authors and editors who worked on the book

Email: feedback@samspublishing.com

Mail: Michael Stephens

Associate PublisherSams Publishing

800 East 96th StreetIndianapolis, IN 46240 USAFor more information about this book or another Sams title, visit our Web site at

www.samspublishing.com Type the ISBN (0789731290) or the title of a book in the Searchfield to find the page you’re looking for

Trang 24

I N T H I S I N T R O D U C T I O N Introduction

Getting Results with VBA 1 What Is in This Book 3

A Brief History of Spreadsheets and Macros 4 The Future of VBA and Excel 5 Special Elements and Typographical

Conventions 6 Next Steps 7

Getting Results with VBA

As the macro language for Microsoft Excel, VisualBasic for Applications enables you to achievetremendous efficiencies in your day-to-day use ofExcel

As corporate IT departments have found selves with long backlogs of requests, Excel usershave found that they can produce the reportsneeded to run their business themselves This isboth a good and bad thing On the good side, with-out waiting for resources from IT, you’ve probablybeen able to figure out how to import data and pro-duce reports in Excel On the bad side, you are nowstuck importing data and producing reports inExcel

them-I N T R O D U C T them-I O N

Trang 25

C A S E S T U DY

Case Study: Monthly Accounting Reports

This is a true story.Valerie is a business analyst in the accounting department of a medium-size corporation Her companyrecently installed an over-budget $16 million ERP system As the project ground to a close, there were no resources left inthe IT budget to produce the monthly report that this corporation used to summarize each department

Valerie, however, had been close enough to the implementation process to think of a way to produce the report herself.She understood that she could export General Ledger data from the ERP system to a text file with comma-separated val-ues Using Excel,Valerie was able to import the G/L data from the ERP system into Excel

Creating the report was not easy Like many companies, there were exceptions in the data.Valerie knew that certainaccounts in one particular cost center needed to be reclassed as an expense She knew that other accounts needed to beexcluded from the report entirely.Working carefully in Excel,Valerie made these adjustments She created one pivot table

to produce the first summary section of the report She cut the pivot table results and pasted them into a blank sheet.Then she created a new pivot table report for the second section of the summary After about three hours, she hadimported the data, produced five pivot tables, arranged them in a summary, and had neatly formatted the report in color

work-Becoming the Hero

Valerie handed this report to her manager.The manager had just heard from the IT department that it would be monthsbefore they could get around to producing “that convoluted report.”Valerie walked in, handed the Excel report over, andbecame the instant hero of the day In three hours,Valerie had managed to do the impossible.Valerie was on cloud nineafter a well-deserved “atta-girl.”

More Cheers

The next day, this manager attended the monthly department meeting.When the department managers started plaining that they couldn’t get the report from the ERP system, this manager pulled out his department report and placed

com-it on the table.The other managers were amazed How was he able to produce this report? Everyone was greatly relieved

to hear that someone had cracked the code.The company president asked Valerie’s manager if he could have the reportproduced for each department

The Cheers Turn to Dread

You can certainly see this coming.This particular company had 46 departments.That means 46 one-page summaries had

to be produced once a month Each required importing data from the ERP system, backing out certain accounts, producingfive pivot tables, and then formatting in color It had taken Valerie three hours to produce the first report She found thatafter she got into the swing of things, she was able to produce the 46 reports in 40 hours.This is horrible.Valerie had a job

to do before she won the responsibility of spending 40 hours a month producing these reports in Excel

VBA to the Rescue

Valerie found my company, MrExcel Consulting, and explained her situation In the course of about a week, I was able toproduce a series of macros in Visual Basic that did all the mundane tasks It imported the data It backed out certainaccounts It did five pivot tables and applied the color formatting From start to finish, the entire 40-hour manual processwas reduced to two button clicks and about four minutes

Trang 26

What Is in This Book

Right now, either you or someone in your company is probably stuck doing manual tasks inExcel that can be automated with VBA I am confident that I can walk into any companywith 20 or more Excel users and find a case as amazing as Valerie’s

What Is in This Book

You’ve taken the right step by purchasing this book I can help you get up the learning curve

so you can write your own VBA macros and put an end to the burden of generating reportsmanually

Getting Up the Learning Curve

This introduction provides a brief history of spreadsheets Chapter 1 introduces the toolsand confirms what you probably already know: The macro recorder does not work Chapter

2 helps you understand the crazy syntax of VBA Chapter 3 breaks the code on how to ciently work with ranges and cells

effi-By the time you get to Chapter 4, you will know enough to put to immediate use the 25sample user-defined functions in that chapter

Chapter 5 covers the power of looping using VBA In Valerie’s case study, after we wrote theprogram to produce the first department report, it took only another minute to wrap thatreport routine in a loop that produced all 46 reports

Chapters 6 and 7 cover R1C1 style formulas and names Chapter 8 has some great tricksthat use event programming Chapter 9 introduces custom dialog boxes that you can use tocollect information from the human using Excel

Excel VBA Power

Chapters 10–12 provide an in-depth look at charting, Advanced Filter, and pivot tables Anyreport automation tool is going to rely heavily on these concepts

Chapter 13 includes another 25 code samples designed to exhibit the power of Excel VBA.Chapters 14–16 handle Web queries, XML, and automating another Office program such asWord

The Techie Stuff Needed to Produce Applications for Others

Chapter 17 shows you how to use arrays to build fast applications Chapters 18 and 19 dle reading and writing to text files and Access databases The techniques for using Accessdatabases enable you to build an application with the multi-user features of Access yet keepthe friendly front-end of Excel

han-Chapter 20 covers VBA from the point of view of a Visual Basic programmer It teaches youabout classes and collections Chapter 21 discusses advanced userform topics Chapter 22teaches you some tricky ways to achieve tasks using the Windows Application ProgrammingInterface Chapters 23–25 deal with error handling, custom menus, and add-ins Chapter 26closes with a case study of a full-blown VBA application

Trang 27

Will This Book Teach Excel?

At the Microsoft Office 2003 launch event, Microsoft revealed that they think the averageOffice user touches only 10% of the features in Office I realize everyone reading this book

is above average I think that I have a pretty smart audience at MrExcel.com A poll of 2000MrExcel.com readers shows that only 42% of smarter-than-average users are using any one

of the top 10 power features in Excel I regularly do an Excel seminar for accountants.These are hard-core Excelers who use Excel 30–40 hours every week Again, two thingscome out in every seminar First, half the audience gasps when they see how quickly you can

do tasks with a particular feature (such as automatic subtotals or pivot tables) Second, I amroutinely trumped by someone in the audience Someone will ask a question, I will answer,and someone in the second row will raise a hand and give a better answer The point? Youand I both really know a lot about Excel However, I will assume that in any given chapter,maybe 58% of the people haven’t used pivot tables before and maybe even less have usedthe “Top 10 Autoshow” feature of pivot tables Before I show you how to automate some-thing in VBA, I will briefly cover how to do the same task in the Excel interface This bookdoes not teach you how to do pivot tables, but it does alert you that you might want to goexplore something and learn it elsewhere

A Brief History of Spreadsheets and Macros

Up through 1978, any accountant could tell you that a spreadsheet comprised green ledgerpaper, a mechanical pencil, and an eraser Daily sales were recorded in pencil and a runningtotal was kept with an adding machine If you discovered on the 30th of the month that thesales figure for the 5th of the month was wrong, you had a lot of erasing and recalculating

to do

Two guys changed everything in 1979 They produced what they called a “visual calculator”

to run on the Apple II computer Dan Bricklin and Bob Frankston’s VisiCalc was the firstspreadsheet program It was eventually ported to several platforms, including the first IBM

PC In 1981, they released an extended version of VisiCalc for the Apple III that supportedcommand-line macros Legal wrangling hurt VisiCalc and the company was dead by 1985

Bob Frankston and Dan

Bricklin invented

VisiCalc, the first

spread-sheet, in 1979.Two years

later, extended VisiCalc

offered the first

spread-sheet macros

Trang 28

The Future of VBA and Excel

Mitch Kapor designed Lotus 1-2-3 in 1983 It ran in DOS, but it ran circles aroundVisiCalc Sales in the first year were an astounding $53 million Lotus 1-2-3 dominated thespreadsheet market throughout the 80s and early 90s There were other minor players—

Quattro, Multiplan, and others—but Lotus 1-2-3 was the de facto standard in accountingdepartments everywhere

In 1985, Lotus release 2 offered an unprecedented 8,192 rows and 256 columns—more than

2 million cells You could easily record simple macros In 1990, I would have been 100%

convinced that Lotus 1-2-3 would absolutely own the spreadsheet market for always andeternity

However, in the early 90s, Lotus bet the farm by producing a version of Lotus for theCP/M operating system At the same time, Microsoft was improving their spreadsheet prod-uct, now named Excel Excel version 3.0 in 1990 wasn’t as good as Lotus 1-2-3 But every1–2 years, Microsoft improved Excel 4 in 1992 started to become popular and offered amacro language called XLM In 1993, Excel 5 introduced multiple worksheets in a work-book and offered the first support for VBA macros Microsoft offered a Lotus 1-2-3 transi-tion mode and their sales force began making serious inroads The mid-90s were the gloryyears in Excel development Excel 95 and Excel 97 were loaded with new features such aspivot tables, autofilter, and automatic subtotals The new VBA development environmentwas introduced in Excel 97 Microsoft was brilliant in their ability to chip away at Lotus 1-2-3’s dominance They have put together a winning combination of Excel and VBA thatsits on 400 million desktops around the world Today, I am 100% convinced that Excel willabsolutely own the spreadsheet market for always and eternity Of course, I was wrongbefore

The Future of VBA and Excel

Star Office is not as good as Excel, but with every release, they get closer For someone whodoesn’t need every feature of Excel, Star Office is good enough The problem, as I see it, isthat Star Office does not offer VBA or any real macro language To me, a spreadsheet with-out a macro language is useless and therefore Star Office is not a credible threat to Excel

Perhaps you’ve heard the rumblings from inside Microsoft that someday VBA may go away

On one hand, this doesn’t seem possible Microsoft is still supporting XLM macros (the oldExcel version 4 macro language) 11 years after VBA was introduced Microsoft is on therecord that VBA will be supported in Excel 2005 Given that most people tend to upgradeevery second version of Office, that means that Excel VBA will be running on a majority ofdesktops until at least 2009 Is this a reason for us to be concerned that our VBA knowledgewill be useless?

No rational person would believe that Microsoft would remove support for the most tant feature that differentiates Excel from Star Office: VBA

Trang 29

impor-Security has moved to the forefront for Microsoft In October 2003, Microsoft announcednew security initiatives that make it clear that security is job 1 at Microsoft This is relevantbecause the infamous Melissa virus spread rapidly by using VBA in Word The press andpowers that be took this situation and moved VBA over to the endangered species list IfMicrosoft continues to take more heat for security, then the company may indeed be forcedinto removing VBA from Office.

Office 2003 now offers Visual Basic NET Office System Tools Visual Basic 6 offered theability to automate Excel XP tasks from Visual Basic With the release of Office 2003, wenow have major new features that can only be automated from NET If you want to pro-gram a smart document or publish content for the research pane, you cannot do so if youare using VBA

So, Microsoft has to do something to combat the security issues in VBA The NET team atMicrosoft is certainly making a pitch that NET Tools for Office could be the replacement.However, I think this would be an incredible mistake Right now, all the 400 million Officeusers could buy this book and within a week start developing VBA solutions in Excel Whitecollar productivity would skyrocket and our reliance on the MIS department would dimin-ish If Microsoft would switch over to NET, then VBA and the ability to write macro code

is removed from the inside of Excel At that point, there is less of a compelling reason tobuy Excel over Star Office, who will certainly have a macro language by 2007 These con-cerns over security could be the distraction that causes Microsoft to lose their hold on thespreadsheet market

However, in the meantime, feel safe in knowing that VBA is with us for the rest of thisdecade Also, the knowledge that you gain in Excel VBA is directly portable to the NETframework Code in NET looks remarkably like code in VBA

Special Elements and Typographical Conventions

The following typographical conventions are used in this book:

Italic Indicates new terms when they are defined, special emphasis, non-English words

or phrases, and letters or words used as words

■ Monospace Indicates parts of VBA code, such as object or method names, and filenames

Italic Monospace Indicates placeholder text in code syntax

Bold Monospace Indicates user input

In addition to these text conventions, there are also several special elements Each chapterhas at least one Case Study, which shows you real-world solutions to common problems andpractical applications of topics discussed in the text In addition to these case studies, youwill also see Notes, Tips, and Cautions

Trang 32

1 Unleash the Power of Excel with VBA! 11

2 This Sounds Like BASIC, So Why Doesn’t It Look Familiar? 29

Trang 34

I N T H I S C H A P T E R

Unleash the Power of Excel with VBA!

1 The Power of Excel

Visual Basic for Applications combined withMicrosoft Excel is probably the most powerful toolavailable to you This tool is sitting on the desktops

of 400 million users of Microsoft Office and mosthave never figured out how to harness the power ofVBA in Excel Using VBA, you can speed the pro-duction of any task in Excel If you regularly useExcel to produce a series of monthly charts, you canhave VBA do the same task for you in a matter ofseconds

Barriers to Entry

There are two barriers to learning successful VBAprogramming First, Excel’s macro recorder isflawed and does not produce workable code for you

to use as a model Second, for many who learned aprogramming language such as BASIC, the syntax

of VBA is horribly frustrating

The Macro Recorder Doesn’t Work!

Microsoft began to dominate the spreadsheet ket in the mid-90s Although they were wildly suc-cessful in building a powerful spreadsheet programtoward which any Lotus 1-2-3 user could easilytransition, the macro language was just too differ-ent Anyone proficient in recording Lotus 1-2-3macros who tried recording a few macros in Excelmost likely failed Although the Microsoft VBAprogramming language is far more powerful thanthe Lotus 1-2-3 macro language, the one funda-mental flaw is that the macro recorder does notwork

mar-The Power of Excel 11 Barriers to Entry 11 Knowing Your Tools—The Visual Basic Toolbar 13 Macro Security 14 Overview of Recording, Storing, and

Running a Macro 15 Running a Macro 16 Understanding the Visual Basic Editor (VBE) 18 Case Study 20 Examining Code in the Programming Window 22 Running the Macro on Another Day Produces Undesired Results 24 Case Study 25 Frustration 28 Next Steps: Learning VBA Is the Solution 28

Trang 35

With Lotus 1-2-3, you could record a macro today, play it back tomorrow, and it wouldfaithfully work When you attempt the same feat in Microsoft Excel, the macro might worktoday but not tomorrow I was horribly frustrated in 1995 when I tried to record my firstExcel macro

Visual Basic Is Not Like BASIC

The code generated by the macro was unlike anything that I had ever seen It said this was

“Visual Basic.” I had the pleasure of learning half of dozen programming languages at ous times; this bizarre-looking language was horribly unintuitive and did not at all resemblethe BASIC language that I had learned in high school

vari-To make matters worse, even in 1995, I was the spreadsheet wizard in my office My pany had just forced everyone to convert from Lotus 1-2-3 to Excel I was now faced with amacro recorder that didn’t work and a language that I could not understand This was not agood combination of events

com-My assumption in writing this book is that you are pretty talented with a spreadsheet Youprobably know more than 90% of the people in your office I will assume that you are not aprogrammer, but that you might have taken a class in BASIC in high school This isn’t arequirement—it actually is a barrier to entry into the ranks of being a successful VBA pro-grammer There is a pretty good chance that you’ve recorded a macro in Excel and a similarchance that you were not happy with the results

The Good News—It Is Easy to Climb the Learning Curve

Even if you’ve been frustrated with the macro recorder before, it is really just a small speedbump on your road to writing powerful programs in Excel This book will teach you whythe macro recorder fails, but also will show how to easily change the recorded code intosomething useful For all the former BASIC programmers in the audience, I will decode thisbizarre-looking language so that you can easily pick through recorded macro code andunderstand what is going on

The Great News—Excel with VBA Is Worth the Effort

Although you’ve probably been frustrated with Microsoft over your inability to recordmacros in Excel, the great news is that Excel VBA is powerful Absolutely anything that youcan do in the Excel interface can be duplicated with stunning speed in Excel VBA If youfind yourself routinely creating the same reports manually day after day or week after week,Excel VBA will greatly streamline those tasks

The authors work for MrExcel Consulting In this role, we get to help automate reports forhundreds of clients The stories are often similar: The M.I.S department has a several-month backlog of requests Someone in accounting or engineering discovers that he or shecan import some data into Excel and get the reports necessary to run the business This is aliberating event—you no longer need to wait months for the I.T department to write a pro-gram However, the problem is that after you import the data into Excel and win accolades

1

Trang 36

Knowing Your Tools—The Visual Basic Toolbar

from your manager for producing the report, you then find yourself producing the samereport every month or every week This becomes very tedious

Again, the great news is that with a few hours of VBA programming, you can automate thereporting process and turn it into a few button clicks The reward is great Hang with me as

we cover a few of the basics

This chapter is going to expose why the macro recorder does not work I will walk through

a simple example of recorded code and demonstrate why it will work today but fail row You will be seeing code here, and I realize that this code may not be familiar to you yet.That’s OK The point of this chapter is to demonstrate the fundamental problem with themacro recorder We’ll also cover the fundamentals of the Visual Basic Environment

tomor-Knowing Your Tools—The Visual Basic Toolbar

We’ll start with a basic overview of the tools needed to get around with VBA In Excel,select View, Toolbars, Visual Basic to display the Visual Basic toolbar (see Figure 1.1)

1

Security Settings

Microsoft Script Editor Design Mode

Visual Basic Editor

Excel’s Visual Basic toolbar provides these seven actions:

Run Macro—Displays a list of available macros.

Record Macro—Begins the process of recording a macro and displays the Stop

Recording toolbar as shown in Figure 1.2

Figure 1.2

The Stop Recording bar is one of the smallesttoolbars in Excel, yet therelative reference button

tool-on the right is tool-one of themost important in get-ting your recordedmacros close to working

Visual Basic Editor—Opens up the Visual Basic Editor.

Control Toolbox—Displays the controls that can be added to a worksheet.

Trang 37

Design Mode—Turns on the design mode, enabling the user to edit controls on the

worksheet If you attempt to edit a control before you are in design mode, you willcause the action associated with that control to be performed

Microsoft Script Editor—Opens the Script Editor, useful for creating scripts for Web

sites This isn’t related to VBA, so we won’t be discussing it

When you click the Record button, the Stop Recording toolbar appears As shown inFigure 1.2, it provides these two actions:

Stop Recording—Ends the current recording session.

Relative Reference—Tells Excel to record with relative reference rather than the

absolute reference

Macro Security

After VBA macros were used as the delivery method for some high-profile viruses,Microsoft changed the default security settings to prevent macros from running Thus,before we can begin discussing the recording of a macro, we need to show you how to adjustthe default settings

The macro security settings can be found under Tools, Macro, Security There are four els of security: Very High, High, Medium, and Low By default, Excel sets the security toHigh (see Figure 1.3) This setting will prevent all unsigned macros from running or evenbeing edited You need to adjust this setting to Medium to begin writing code

lev-1

Figure 1.3

Excel macro security

set-tings are set to High by

default

Very High Security

This is the first option of using Microsoft’s “Sandbox” paradigm for security The paradigmsays that your network administrator can set up a highly protected network directory and

define it as a trusted location This area is called the Sandbox You are allowed to play any

Trang 38

Overview of Recording, Storing, and Running a Macro

macros located in the Sandbox Anything that is installed outside the Sandbox is off limits

The theory is that viruses will not be able to locate themselves into the secured trusted area

High Security

The High security setting allows only trusted macros to run A macro is trusted when it hasbeen digitally signed and you choose to trust the source Because macro signing requiresthat you buy a digital certificate from an agency such as VeriSign, this setting effectively dis-allows all macros that you write yourself If a workbook contains an unsigned macro, theworkbook opens but the macros are automatically disabled—no prompt appears informingyou of this

be in a received workbook is the safest setting

Overview of Recording, Storing, and Running a Macro

Recording a macro is very useful when you do not have enough experience in writing lines

of code in a macro As you gain more knowledge and experience, you will begin to recordlines of code less and less frequently

To begin recording a macro, select Tools, Macro, Record New Macro, or press the RecordMacro button on the VBA toolbar Before recording begins, Excel displays the RecordMacro dialog box, as shown in Figure 1.4

Filling Out the Record Macro Dialog

In the Macro Name field, type a name for the macro Be sure to type continuous characters;for example, type Macro1and not Macro 1(with a space) Assuming you will soon be creatingmany macros, use a meaningful name for the macro A name such as “FormatReport” ismore useful than “Macro1.”

1

Trang 39

The second field in the Record Macro dialog box is a shortcut key If you type j in this field,

then pressing Ctrl+j causes this macro to run

In the Record Macro dialog box, you can choose where you want to save a macro when yourecord it: Personal Macro Workbook, New Workbook, This Workbook I recommend stor-ing macros related to a particular workbook in This Workbook

The Personal Macro Workbook (Personal.xls) is not an open workbook; it is created if youchoose to save the recording in the Personal Macro Workbook This workbook is used tosave a macro in a workbook that will open automatically when you start Excel, therebyenabling you to use the macro After Excel is started, the workbook is hidden If you want todisplay it, select Unhide from the Window menu

It is not recommended you use the personal workbook for every macro you save Save onlythose macros that will assist you in general tasks—not in tasks that are performed in a spe-cific sheet or workbook

After you select the location where you want to store the macro, click OK Record yourmacro When you are finished recording the macro, click the Stop button on the StopRecording dialog box

Running a Macro

If you assigned a shortcut key to your macro, you can play it by pressing the key tion Macros can also be assigned to toolbar buttons, forms controls, or you can run themfrom the Visual Basic toolbar

combina-Creating a Macro Button

If you want to create a macro to assist in your Excel work, store the macro in a personalworkbook and attach it to a toolbar button:

1. Right-click on a toolbar and select Customize

2. Select the Commands tab (see Figure 1.5)

1

Figure 1.4

Use the Record Macro

dialog box to assign a

name and a shortcut key

to the

soon-to-be-recorded macro

Trang 40

Running a Macro

3. From Categories, select Macros

4. Select the Custom button (with the yellow smiley face) and drag it onto a toolbar

5. Right-click on the icon (do not close the Customize dialog box)

6. Select Assign Macro, select the macro, and click OK

7. Close the Customize dialog box

Assigning a Macro to a Form Control

If you want to create a macro specific to a workbook, store the macro to the workbook andattach it to a form control on the sheet, as shown in Figure 1.6

1

Figure 1.5

Use Customize to insert

a Macro button into atoolbar

Figure 1.6

Assigning a macro to aform control is appropri-ate for macros stored inthe same workbook asthe control

Follow these steps to attach a macro to a form control on the sheet:

1. Display the Forms toolbar by selecting View, Toolbars, Forms

2. Click the Button image

Ngày đăng: 05/01/2017, 22:45

TỪ KHÓA LIÊN QUAN

🧩 Sản phẩm bạn có thể quan tâm