VBA andMacros: Microsoft® Excel® 2010 - GBV · Contents: vii 7 WhatIs Newin Excel...
Transcript of VBA andMacros: Microsoft® Excel® 2010 - GBV · Contents: vii 7 WhatIs Newin Excel...
MrExcel^4JF LIBRARY
VBA and Macros:
Microsoft®
Excel® 2010
Billjekn
Tracy Syrstad
que
800 E. 96th Street
Indianapolis, Indiana 46240
Contents
Introduction 1
Getting Results withVBA 1
What Is in This Book? 1
Reduce the Learning Curve 1
Excel VBA Power 2
Techie StuffNeeded to Produce Applications 2
Does This BookTeach Excel? 2
The Future of VBA and Windows Versions of Excel 4
Versions of Excel 4
Special Elements and Typographical Conventions 5
Code Files 6
Next Steps 6
1 Unleash the Power of Excel with VBA 7
The Power of Excel 7
Barriers to Entry 7
The Macro Recorder Doesn't Work! 7
Visual Basic Is Not Like BASIC 8
Good News: Climbing the Learning Curve Is Easy 8
Great News: Excel with VBA Is Worth the Effort 8
Knowing Your Tools: The Developer Tab 9
Macro Security 10
Adding a Trusted Location 10
Using Macro Settings to Enable Macros in Workbooks Outside of Trusted Locations 11
Using Disable All Macros with Notification 12
Overview of Recording, Storing, and Running a Macro 12
Filling Out the Record Macro Dialog 13
Running a Macro 14
Creating a Macro Button on the Ribbon 14
Creating a Macro Button on the Quick AccessToolbar 15
Assigning a Macro to a Form Control, Text Box, or Shape 16
Using New File Types in Excel 2010 18
Understanding theVB Editor 19
VB Editor Settings 19
The Project Explorer 20
The Properties Window 21
Understanding Shortcomings of the Macro Recorder 21
Examining Code in the Programming Window 23
Running the Macro on Another Day Produces Undesired Results 25
iv VBA and Macros: Microsoft Excel 2010
Possible Solution: Use Relative References When Recording 26
Never Use the AutoSum Button While Recording a Macro 30
Three Tips When Using the Macro Recorder 31
Next Steps 32
2 This Sounds Like BASIC, So Why Doesn't It Look Familiar? 33
I Can't Understand This Code 33
Understanding the Parts ofVBA "Speech" 34
VBA Is Not Really Hard 37
VBA Help Files: Using F1 to Find Anything 37
Using Help Topics 39
Examining Recorded Macro Code: Using the VB Editor and Help 39
Optional Parameters 41
Defined Constants 41
Properties Can Return Objects 46
Using Debugging Tools to Figure Out Recorded Code 46
Stepping Through Code 46
More Debugging Options: Breakpoints 49
Backing Up or Moving Forward in Code 49
Not Stepping Through Each Line of Code 50
Querying Anything While Stepping Through Code 50
Using a Watch to Set a Breakpoint 55
Using a Watch on an Object 55
Object Browser: The Ultimate Reference 56
Seven Tips for Cleaning Up Recorded Code 58
Tip 1: Don't Select Anything 58
Tip 2: Cells(2,5) Is More Convenient Than Range("E2") 59
Tip 3: Ride the Range from the Bottom to Find Last Row 59
Tip 4: Use Variables to Avoid Hard-Coding Rows and Formulas 60
Tip 5: R1C1 Formulas That Make Your Life Easier 61
Tip 6: Learn to Copy and Paste in a Single Statement 61
Tip 7: Use With...End With to Perform Multiple Actions 61
Next Steps 64
3 Referring to Ranges 65
The Range Object 65
Syntax to Specify a Range 66
Named Ranges 66
Shortcut for Referencing Ranges 66
Referencing Ranges in Other Sheets 67
Referencing a Range Relative to Another Range 68
Contents i V
Use the Cells Property to Select a Range 68
Using the Cells Property in the Range Property 69
Use the Off set Property to Refer toa Range 69
Use the Resize Property to Change the Size of a Range 71
Using the Columns and Rows Properties to Specify a Range 72
Use the Union Method to Join Multiple Ranges 72
Use the Intersect Method to Create a New Range from Overlapping Ranges 73
Usethe ISEMPTY Function to Check Whether a Cell Is Empty 73
Usethe CurrentRegion Property to Select a Data Range 74
Usethe Areas Collection to Return a Noncontiguous Range 77
Referencing Tables 77
Next Steps 78
4 User-Defined Functions 79
Creating User-Defined Functions 79
Sharing UDFs 81
Useful Custom Excel Functions 82
Setthe Current Workbook's Name in a Cell 82
Set the Current Workbook's Name and File Path in a Cell 82
Check Whether a Workbook Is Open 83
Check Whether a Sheet in an Open Workbook Exists 83
Count the Number ofWorkbooks in a Directory 84
Retrieve USERID 85
Retrieve Date and Time of Last Save 86
Retrieve Permanent Date and Time 87
Validate an E-mail Address 88
Sum Cells Based on Interior Color 89
Count Unique Values 90
Remove Duplicates from a Range 91
Find the First Nonzero-Length Cell in a Range 93
Substitute Multiple Characters 94
Retrieve Numbers from Mixed Text 95
Convert Week Number into Date 96
Separate Delimited String 96
Sort and Concatenate 97
Sort Numeric and Alpha Characters 99
Search for a String Within Text 100
Reverse the Contents of a Cell 101
Multiple Max 101
Return Hyperlink Address 102
Return the Column Letter of a Cell Address 103
vi VBA and Macros: Microsoft Excel 2010
Static Random 103
Using Select Case on a Worksheet 104
Next Steps 105
5 Looping and Flow Control 107
For...Next Loops 107
Using Variables in the For Statement 110
Variations on the For.. .Next Loop 110
Exiting a Loop Early After a Condition Is Met 111
Nesting One Loop Inside Another Loop 112
Do Loops 113
Using the While or Until Clause in Do Loops 115
While.. .Wend Loops 117
VBA Loop: For Each 117
Object Variables 117
Flow Control: Using If... Then... Else and Select Case 120
Basic Flow Control: If.. .Then.. .Else 121
Conditions 121
If.. .Then.. .End If 121
Either/Or Decisions: If.. .Then.. .Else.. .End If 122
Using If.. .Else If... End If for Multiple Conditions 122
UsingSelect Case...End Select for Multiple Conditions 123
Complex Expressions in Case Statements 124
Nesting If Statements 124
Next Steps 126
6 R1C1-Style Formulas 127
Referring to Cells: A1 Versus R1C1 References 127
Switching Excel to Display R1C1 -Style References 128
The Miracle of Excel Formulas 129
Enter a Formula Once and Copy 1,000 Times 129
The Secret: It's Not That Amazing 130
Explanation of R1C1 Reference Style 132
Using R1C1 with Relative References 132
Using RIG with Absolute References 133
Using R1C1 with Mixed References 133
Referring to Entire Columns or Rows with R1C1 Style 134
Replacing Many A1 Formulas with a Single R1C1 Formula 134
Remembering Column Numbers Associated with Column Letters 136
Array Formulas Require R1C1 Formulas 137
Next Steps 138
Contents : vii
7 What Is New in Excel 2010 and What Has Changed 139
If It Has Changed in the Front End, It Has Changed in VBA 139
The Ribbon 139
Charts 139
Pivot Tables 140
Slicers 140
Conditional Formatting 140
Tables 141
Sorting 141
SmartArt 142
Learning the New Objects and Methods 143
Compatibility Mode 144
Version 144
Excel8CompatibilityMode 145
Next Steps 146
8 Create and Manipulate Names in VBA 147
Excel Names 147
Global Versus Local Names 147
Adding Names 148
Deleting Names 149
Adding Comments 150
Types of Names 150
Formulas 151
Strings 151
Numbers 152
Tables 153
Using Arrays in Names 153
Reserved Names 154
Hiding Names 155
Checking for the Existence of a Name 155
Next Steps 158
9 Event Programming 159
Levels of Events 159
Using Events 160
Event Parameters 160
Enabling Events 161
Workbook Events 161
Workbook_Activate () 161
Workbook_Deactivate () 161
viii VBA and Macros: Microsoft Excel 2010
Workbook_Open() 161
Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) 162
Workbook_BeforePrint(Cancel As Boolean) 163
Workbook_BeforeClose(Cancel As Boolean) 163
Workbook_NewSheet(ByVal Sh As Object) 164
Workbook_WindowResize(ByVal Wn As Window) 164
WorkbookJVindowActivate(ByVal Wn As Window) 165
Workbook_WindowDeactivate(ByVal Wn As Window) 165
Workbook_AddlnInstall() 165
Workbook_AddInUninstall 165
Workbook_Sync(ByVal SyncEventType As Office.MsoSyncEventType) 165
Workbook_PivotTableCloseConnection(ByVal Target As PivotTable) 165
Workbook_PivotTableOpenConnection(ByVal Target As PivotTable) 165
Workbook_RowsetComplete(ByVal Description As String, ByVal Sheet As
String, ByVal Success As Boolean) 165
Workbook_BeforeXmlExport(ByVal Map As XmlMap, ByVal Url As String,
Cancel As Boolean) 166
Workbook_AfterXmlExport(ByVal Map As XmlMap, ByVal Url As String, ByVal
Result As XlXmlExportResult) 166
Workbook_BeforeXmllmport(ByVal Map As XmlMap, ByVal Url As String, ByValIsRefresh As Boolean, Cancel As Boolean) 166
Workbook_AfterXmlImport(ByVal Map As XmlMap, ByVal IsRefresh As Boolean,
ByVal Result As XlXmllmportResult) 166
Workbook Level Sheet and Chart Events 166
Worksheet Events 168
Worksheet_Activate() 168
Worksheet_Deactivate () 168
Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) 168
Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean) 169
Worksheet_Calculate () 169
Worksheet_Change(ByVal Target As Range) 170
Worksheet_SelectionChange(ByVal Target As Range) 170
Worksheet_FollowHyperlink(ByVal Target As Hyperlink) 171
Worksheet_PivotTableUpdate(ByVal Target As PivotTable) 172
Chart Sheet Events 172
Embedded Charts 172
Chart_Activate() 173
Chart_BeforeDoubleClick(ByVal ElementID As Long, ByVal Arg1 As Long,ByVal Arg2 As Long, Cancel As Boolean) 173
Chart_BeforeRightClick(Cancel As Boolean) 173
Chart_Calculate() 173
Chart_Deactivate() 173Chart_MouseDown(ByVal Button As Long, ByVal Shift As Long, ByVal x As
Long, ByVal y As Long) 174
Chart_MouseMove(ByVal Button As Long, ByVal Shift As Long, ByVal x As
Long, ByVal y As Long) 174
Contents I ix
Chart_Mousellp( ByVal Button As Long, ByVal Shift As Long, ByVal x As
Long, ByVal y As Long) 174
Chart_Resize() 174
Chart_Select(ByVal ElementID As Long, ByVal Arg1 As Long, ByVal Arg2 As
Long) 174
Chart_SerlesChange(ByVal Serieslndex As Long, ByVal Pointlndex As Long) 175
Chart_DragOver() 175
Chart_DragPlot() 175
Application-Level Events 176
AppEvent_AfterCalculate () 176
AppEvent_NewWorkbook(ByVal Wb As Workbook) 177
AppEvent_ProtectedViewWindowActivate(ByVal Pvw As ProtectedViewWindow) 177
AppEvent_ProtectedViewWindowBeforeClose(ByVal Pvw As ProtectedViewWindow,
ByVal Reason As XIProtectedViewCloseReason, Cancel As Boolean) 177
AppEvent_ProtectedViewWindowDeactivate(ByVal Pvw As ProtectedViewWindow) 177
AppEvent_ProtectedViewWindowOpen(ByVal Pvw As ProtectedViewWindow) 177
AppEvent_ProtectedViewWindowResize(ByVal Pvw As ProtectedViewWindow) 177
AppEvent_SheetActivate (ByVal Sh As Object) 177
AppEvent_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As
Range, Cancel As Boolean) 178
AppEvent_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As
Range, Cancel As Boolean) 178
AppEvent_SheetCalculate(ByVal Sh As Object) 178
AppEvent_SheetChange(ByVal Sh As Object, ByVal Target As Range) 178
AppEvent_SheetDeactivate(ByVal Sh As Object) 178
AppEvent_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As
Hyperlink) 178
AppEvent_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)....178AppEvent_SheetPivotTableUpdate(ByVal Sh As Object, ByVal Target As
PivotTable) 178
AppEvent_WindowActlvate(ByVal Wb As Workbook, ByVal Wn As Window) 179
AppEvent_WindowDeactivate(ByVal Wb As Workbook, ByVal Wn As Window) 179
AppEvent_WindowResize(ByVal Wb As Workbook, ByVal Wn As Window) 179
AppEvent_WorkbookActivate(ByVal Wb As Workbook) 179
AppEvent_WorkbookAddinInstall(ByVal Wb As Workbook) 179
AppEvent_WorkbookAddinUninstall(ByVal Wb As Workbook) 179
AppEvent_WorkbookBeforeClose(ByVal Wb As Workbook, Cancel As Boolean) 179
AppEvent_WorkbookBeforePrint(ByVal Wb As Workbook, Cancel As Boolean) 180
AppEvent_WorkbookBeforeSave(ByVal Wb As Workbook, ByVal SaveAsUI As
Boolean, Cancel As Boolean) 180
AppEvent_WorkbookNewSheet(ByVal Wb As Workbook, ByVal Sh As Object) 180
AppEvent_WorkbookOpen(ByVal Wb As Workbook) 180
AppEvent_WorkbookPivotTableCloseConnection(ByVal Wb As Workbook, ByVal
Target As PivotTable) 180
AppEvent_WorkbookPivotTableOpenConnection(ByVal Wb As Workbook, ByVal
Target As PivotTable) 180
AppEvent_WorkbookRowsetComplete(ByVal Wb As Workbook, ByVal Description
As String, ByVal Sheet As String, ByVal Success As Boolean) 181
x VBA and Macros: Microsoft Excel 2010
AppEvent_WorkbookSync(ByVal Wb As Workbook, ByVal SyncEventType As
Office.MsoSyncEventType) 181
AppEvent_WorkbookBeforeXmlExport(ByVal Wb As Workbook, ByVal Map As
XmlMap, ByVal Url As String, Cancel As Boolean) 181
AppEvent_WorkbookAfterXmlExport(ByVal Wb As Workbook, ByVal Map As
XmlMap, ByVal Url As String, ByVal Result As XlXmlExportResult) 181
AppEvent_WorkbookBeforeXmlImport(ByVal Wb As Workbook, ByVal Map As
XmlMap, ByVal Url As String, ByVal IsRefresh As Boolean, Cancel As
Boolean) 181
AppEvent_WorkbookAfterXmllmport(ByVal Wb As Workbook, ByVal Map As
XmlMap, ByVal IsRefresh As Boolean, ByVal Result As XlXmllmportResult) 181
Next Steps 182
10 Userforms: An Introduction 183
User Interaction Methods 183
Input Boxes 183
Message Boxes 184
Creating a Userform 184
Calling and Hiding a Userform 186
Programming the Userform 186
Userform Events 186
Programming Controls 188
Using Basic Form Controls 189
Using Labels, Text Boxes, and Command Buttons 189
Deciding Whether to Use List Boxes or Combo Boxes in Forms 191
Adding Option Buttons to a Userform 194
Adding Graphics to a Userform 195
Using a Spin Button on a Userform 196
Using the Mult iPage Control to Combine Forms 198
Verifying Field Entry 200
Illegal Window Closing 200
Getting a Filename 201
Next Steps 202
11 Creating Charts 203
Charting in Excel 2010 203
Referencing Charts and Chart Objects in VBA Code 203
Creating a Chart 204
Specifying the Size and Location of a Chart 204
Later Referring to a Specific Chart 206
Recording Commands from the Layout or Design Tabs 208
Specifying a Built-in Chart Type 208
Specifying a Template Chart Type 210
Changing a Chart's Layout or Style 211
Contents ' xi
Using SetElement to Emulate Changes on the Layout Tab 213
Changing a Chart Title Using VBA 218
Emulating Changes on the Format Tab 218
Using the Format Method to Access Formatting Options 218
Creating Advanced Charts 234
Creating True Open-High-Low-Close Stock Charts 235
Creating Bins for a Frequency Chart 236
Creating a Stacked Area Chart 239
Exporting a Chart as a Graphic 244
Creating a Dynamic Chart in a Userform 244
Creating Pivot Charts 246
Next Steps 248
12 Data Mining with Advanced Filter 249
Replacing a Loop with AutoFilter 249
Using New AutoFilter Techniques 251
Selecting Visible Cells Only 255
Advanced Filter Is Easier in VBA Than in Excel 257
Using the Excel Interface to Build an Advanced Filter 258
Using Advanced Filter to Extract a Unique List of Values 258
Extracting a Unique List of Values with the User Interface 259
Extracting a Unique List of Values with VBA Code 260
Getting Unique Combinations ofTwo or More Fields 263
Using Advanced Filter with Criteria Ranges 265
Joining Multiple Criteria with a Logical OR 267
Joining Two Criteria with a Logical AND 267
Other Slightly Complex Criteria Ranges 267
The Most Complex Criteria: Replacing the List of Values with a Condition Created as the Result of a Formula 268
Using Filter in Place in Advanced Filter 275
Catching No Records When Using Filter in Place 276
Showing All Records After Filter in Place 276
The Real Workhorse: xlFilterCopy with All Records Rather Than Unique Records Only 276
Copying All Columns 277
Copying a Subset ofColumns and Reordering 278
Using Filter in Place with Unique Records Only 283
Excel in Practice: Turning Off a Few Drop-Downs in the AutoFilter 285
Next Steps 285
13 Using VBA to Create Pivot Tables 287
Introducing Pivot Tables 287
Understanding Versions 287
New in Excel 2010 288
New Beginning with Excel 2007 288
xii VBA and Macros: Microsoft Excel 2010
Creating a Vanilla Pivot Table in the Excel Interface 290
Understanding Compact Layout 293
Building a Pivot Table in Excel VBA 294
Defining the Pivot Cache 295
Creating and Configuringthe Pivot Table 295
Adding Fields to the Data Area 296
Learning Why You Cannot Move orChange Part of a Pivot Report 299
Determining Size of a Finished Pivot Table to Convert the Pivot Table to Values 299
Using Advanced Pivot Table Features 302
Using Multiple Value Fields 302
Counting the Number of Records 303
Grouping Daily Dates to Months, Quarters, or Years 303
Changing the Calculation to Show Percentages 305
Eliminating Blank Cells in the Values Area 308
Controlling the Sort Order with AutoSort 308
Replicating the Report for Every Product 309
Filtering a Data Set 312
Manually Filtering Two or More Items in a Pivot Field 312
Using the Conceptual Filters 313
Using the Search Filter 316
Setting Up Slicers to Filter a Pivot Table 319
Filtering an OLAP Pivot Table Using Named Sets 321
Using Other Pivot Table Features 324
Calculated Data Fields 324
Calculated Items 325
Using ShowDetail to Filter a Recordset 325
Changing the Layout from the Design Tab 325
Suppressing Subtotals for Multiple Row Fields 326
Next Steps 327
14 Excel Power 329
File Operations 329
List Files in a Directory 329
Import CSV 331
Read Entire TXT to Memory and Parse 332
Combining and Separating Workbooks 333
Separate Worksheets into Workbooks 333
Combine Workbooks 334
Filter and Copy Data to Separate Worksheets 335
Export Data to Word 336
Working with Cell Comments 337
List Comments 337
Resize Comments 339
Resize Comments with Centering 340
Place a Chart in a Comment 341
Contents xiii
Utilities to Wow Your Clients 342
Using Conditional Formatting to Highlight Selected Cell 342
Highlight Selected Cell Without Using Conditional Formatting 344
Custom Transpose Data 345
Select/Deselect Noncontiguous Cells 347
Techniques for VBA Pros 349
Pivot Table Drill-Down 349
Speedy Page Setup 350
Calculating Time to Execute Code 353
Custom Sort Order 354
Cell Progress Indicator 355
Protected Password Box 356
Change Case 359
Selecting with SpecialCells 360
ActiveX Right-Click Menu 360
Cool Applications 362
Historical Stock/Fund Quotes 362
Using VBA Extensibility to Add Code to New Workbooks 363
Next Steps 365
15 Data Visualizations and Conditional Formatting 367
Introduction to Data Visualizations 367
VBA Methods and Properties for Data Visualizations 368
Adding Data Bars to a Range 369
Adding Color Scales to a Range 374
Adding Icon Sets to a Range 375
Specifying an Icon Set 376
Specifying Ranges for Each Icon 377
Using Visualization Tricks 378
Creating an Icon Set for a Subset of a Range 378
Using Two Colors of Data Bars in a Range 380
Using Other Conditional Formatting Methods 382
Formatting Cells That Are Above or Below Average 383
Formatting Cells in the Top 10 or Bottom 5 383
Formatting Unique or Duplicate Cells 384
Formatting Cells Based on Their Value 385
Formatting Cells That Contain Text 386
Formatting Cells That Contain Dates 386
Formatting Cells That Contain Blanks or Errors 387
Using a Formula to Determine Which Cells to Format 387
Using the New NumberFormat Property 388
Next Steps 389
xiv VBA and Macros: Microsoft Excel 2010
16 Reading from and Writing to the Web 391
Getting Data from the Web 391
Manually Creating a Web Query and Refreshing with VBA 392
Using VBA to Update an Existing Web Query 395
Building Many Web Queries with VBA 396
Using Application .OnTime to Periodically Analyze Data 399
Scheduled Procedures Require Ready Mode 400
Specifying a Window ofTimeforan Update 400
Canceling a Previously Scheduled Macro 400
Closing Excel Cancels All Pending Scheduled Macros 401
Scheduling a Macro to Run x Minutes in the Future 401
Scheduling a Verbal Reminder 402
Scheduling a Macro to Run Every 2 Minutes 403
Publishing Data to a Web Page 404
Using VBA to Create Custom Web Pages 406
Using Excel as a Content Management System 407
Bonus: FTP from Excel 409
Next Steps 410
17 Dashboarding with Sparklines in Excel 2010 411
Creating Sparklines 412
Scaling the Sparklines 414
Formatting Sparklines 418
Using Theme Colors 418
Using RGB Colors 421
Formatting Sparkline Elements 423
Formatting Win/Loss Charts 426
Creating a Dashboard 427
Observations About Sparklines 428
Creating 100's of Individual Sparklines in a Dashboard 428
Next Steps 432
18 Automating Word 433
Early Binding 433
Compile Error: Can't Find Object or Library 435
Late Binding 436
Creating and Referencing Objects 437
The New Keyword 437
CreateObject Function 438
GetObject Function 438
Using Constant Values 439
Using the Watch Window to Retrieve the Real Value of a Constant 440
Using the Object Browser to Retrieve the Real Value of a Constant 440
Contents j xv
Understanding Word's Objects 441
Document Object 442
Selection Object 443
Range Object 444
Bookmarks 448
Controlling Form Fields in Word 450
Next Steps 452
19 Arrays 453
Declare an Array 453
Multidimensional Arrays 454
Fill an Array 455
Empty an Array 456
Arrays Make It Easier to Manipulate Data, but Is That All? 457
Dynamic Arrays 459
Passing an Array 460
Next Steps 461
20 Text File Processing 463
Importing from Text Files 463
Importing Text Files with Fewer Than 1,048,576 Rows 463
Reading Text Files with More Than 1,048,576 Rows 470
Writing Text Files 473
Next Steps 474
21 Using Access as a Back End to Enhance Multiuser Access to Data 475
ADO Versus DAO 476
The Tools of ADO 478
Adding a Record to the Database 480
Retrieving Records from the Database 481
Updating an Existing Record 483
Deleting Records via ADO 485
Summarizing Records via ADO 485
Other Utilities via ADO 487
Checking for the Existence of Tables 487
Checking for the Existence of a Field 488
Adding a Table On the Fly 489
Adding a Field On the Fly 489
SQL Server Examples 490
Next Steps 491
xvi VBA and Macros: Microsoft Excel 2010
22 Creating Classes, Records, and Collections 493
Inserting a Class Module 493
Trapping Application and Embedded Chart Events 494
Application Events 494
Embedded Chart Events 495
Creating a Custom Object 497
Using a Custom Object 498
Using Property Let and Property Get to Control How Users Utilize Custom Objects 499
Collections 501
Creating a Collection in a Standard Module 501
Creating a Collection in a Class Module 502
User-Defined Types 506
Next Steps 509
23 Advanced Userform Techniques 511
Using the UserForm Toolbar in the Design of Controls on Userforms 511
More Userform Controls 511
Check Boxes 512
Tab Strips 513
RefEdit 515
Toggle Buttons 517
Using a Scrollbar As a Slider to Select Values 517
Controls and Collections 519
Modeless Userforms 521
Using Hyperlinks in Userforms 522
Adding Controls at Runtime 523
Resizing the Userform On-the-fly 524
Adding a Control On-the-fly 525
Sizing On-the-fly 525
Adding Other Controls 525
Adding an Image On-the-fly 526
Putting It All Together 527
Adding Help to the Userform 529
Showing Accelerator Keys 529
Adding Control Tip Text 530
Creating the Tab Order 530
Coloring the Active Control 530
Transparent Forms 533
Next Steps 534
Contents ! xvii
24 Windows API 535
What Is the Windows API? 535
Understanding an API Declaration 536
Using an API Declaration 537
API Examples 537
Retrieve the Computer Name 538
Check Whether an Excel File Is Open on a Network 539
Retrieve Display-Resolution Information 540
Custom About Dialog 541
Disable the Xfor Closing a Userform 541
Running Timer 542
Playing Sounds 543
Retrieving a File Path 543
Finding More API Declarations 547
Next Steps 547
25 Handling Errors 549
What Happens When an Error Occurs? 549
Debug Error Inside Userform Code Is Misleading 551
Basic Error Handling with the On Error GoToSyntax 552
Generic Error Handlers 554
Handling Errors by Choosing to Ignore Them 554
Suppressing Excel Warnings 556
Encountering Errors on Purpose 556
Train Your Clients 557
Errors While Developing Versus Errors Months Later 557
Runtime Error 9: Subscript Out of Range 557
RunTime Error 1004: Method Range of Object Global Failed 558
The Ills of Protecting Code 559
More Problems with Passwords 560
Errors Caused by Different Versions 561
Next Steps 562
26 Customizing the Ribbon to Run Macros 563
Out with the Old, In with the New 563
Where to Add Your Code: customui Folder and File 564
Creating the Tab and Group 565
Adding a Control to Your Ribbon 566
Accessing the File Structure 571
Understanding the RELS File 571
Renaming the Excel File and Opening the Workbook 572
Custom Ul Editor Tool 572
xviii VBA and Macros: Microsoft Excel 2010
Using Images on Buttons 572
Microsoft Office Icons 573
Custom Icon Images 574
Troubleshooting Error Messages 577
The Attribute "Attribute Name" on the Element "customui Ribbon" Is Not Defined in the DTD/Schema 577
Illegal Qualified Name Character 578
Element "customui Tag Name" Is Unexpected According to Content Model of Parent Element "customui
Tag Name" 578
Excel Found Unreadable Content 579
Wrong Number ofArguments or Invalid Property Assignment 580
Nothing Happens 580
Other Ways to Run a Macro 580
Keyboard Shortcut 580
Attach a Macro to a Command Button 581
Attach a Macro to a Shape 582
Attach a Macro to an ActiveX Control 583
Running a Macro from a Hyperlink 584
Next Steps 585
27 Creating Add-lns 587
Characteristics of Standard Add-lns 587
Converting an Excel Workbook to an Add-In 588
Using Save As to Convert a File to an Add-In 589
Using the VB Editor to Convert a File to an Add-In 590
Having Your Client Install the Add-In 591
Standard Add-lns Are Not Secure 592
Closing Add-lns 593
Removing Add-lns 593
Using a Hidden Workbook as an Alternative to an Add-In 593
Next Steps 595
Index 597