Excel 2021 and Office 365
Excel 2021 and Office 365
Bill Jelen
Tracy Syrstad
SPONSORING EDITOR
All rights reserved. This publication is protected by copyright, and permission must be
Charvi Arora
obtained from the publisher prior to any prohibited reproduction, storage in a retrieval
system, or transmission in any form or by any means, electronic, mechanical, photo- DEVELOPMENT EDITOR
copying, recording, or likewise. For information regarding permissions, request forms, Songlin Qiu
and the appropriate contacts within the Pearson Education Global Rights & Permissions
Department, please visit www.pearson.com/permissions. MANAGING EDITOR
No patent liability is assumed with respect to the use of the information contained Sandra Schroeder
herein. Although every precaution has been taken in the preparation of this book, the
publisher and author assume no responsibility for errors or omissions. Nor is any liabil- SENIOR PROJECT EDITOR
ity assumed for damages resulting from the use of the information contained herein. Tracey Croom
COPY EDITOR
ISBN-13: 978-0-13-752152-4
Sarah Kearns
ISBN-10: 0-13-752152-9
INDEXER
ScoutAutomatedPrintCode PROOFREADER
Donna E. Mulder
Trademarks
TECHNICAL EDITOR
Microsoft and the trademarks listed at http://www.microsoft.com on the “Trademarks” Bob Umlas
webpage are trademarks of the Microsoft group of companies. All other marks are
property of their respective owners. Figures 18-1, and 18-2 are © 2022 Spotify AB. COVER DESIGNER
Twist Creative, Seattle
Special Sales
For information about buying this title in bulk quantities, or for special sales
opportunities (which may include electronic versions; custom cover designs; and
content particular to your business, training goals, marketing focus, or branding
interests), please contact our corporate sales department at [email protected]
or (800) 382-3419.
For government sales inquiries, please contact [email protected].
For questions about sales outside the U.S., please contact [email protected].
Education is a powerful force for equity and change in our world. It has the potential to
deliver opportunities that improve lives and enable economic mobility. As we work with
authors to create content for every product and service, we acknowledge our responsibility
to demonstrate inclusivity and incorporate diverse scholarship so that everyone can achieve
their potential through learning. As the world’s leading learning company, we have a duty
to help drive change and live up to our purpose to help more people create a better life for
themselves and to create a better world.
■■ Our educational products and services are inclusive and represent the rich diversity
of learners.
■■ Our educational content accurately reflects the histories and experiences of the
learners we serve.
■■ Our educational content prompts deeper discussions with learners and motivates
them to expand their own learning (and worldview).
While we work hard to present unbiased content, we want to hear from you about any
concerns or needs with this Pearson product so that we can investigate and address them.
iii
To John. Giraffe.
—Tracy Syrstad
Acknowledgments xxv
About the Authors xxvii
Introduction xxix
CHAPTER 1 Unleashing the power of Excel with VBA 1
CHAPTER 2 This sounds like BASIC, so why doesn’t it look familiar? 27
CHAPTER 3 Referring to ranges 53
CHAPTER 4 Looping and flow control 69
CHAPTER 5 R1C1-style formulas 87
CHAPTER 6 Creating and manipulating names in VBA 97
CHAPTER 7 Event programming 111
CHAPTER 8 Arrays 125
CHAPTER 9 Creating classes and collections 133
CHAPTER 10 Userforms: An introduction 153
CHAPTER 11 Data mining with Advanced Filter 175
CHAPTER 12 Using VBA to create pivot tables 211
CHAPTER 13 Excel power 257
CHAPTER 14 Sample user-defined functions 285
CHAPTER 15 Creating charts 313
CHAPTER 16 Data visualizations and conditional formatting 339
CHAPTER 17 Dashboarding with sparklines in Excel 363
CHAPTER 18 Reading from the web using M and VBA 385
CHAPTER 19 Text file processing 413
CHAPTER 20 Automating Word 427
CHAPTER 21
Using Access as a back end to enhance multiuser
access to data 447
CHAPTER 22 Advanced userform techniques 465
CHAPTER 23 The Windows Application Programming Interface (API) 491
CHAPTER 24 Handling errors 501
CHAPTER 25 Customizing the ribbon to run macros 517
CHAPTER 26 Creating Excel add-ins 539
CHAPTER 27 An introduction to creating Office add-ins 549
CHAPTER 28 What’s new in Excel 365 and what’s changed 571
Index 579
vi
vii
viii Contents
Contents ix
x Contents
Contents xi
xii Contents
Contents xiii
xiv Contents
Contents xv
xvi Contents
Contents xvii
xviii Contents
Contents xix
xx Contents
Contents xxi
xxii Contents
Contents xxiii
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
xxiv Contents
Bob Umlas is the smartest Excel guy I know and is an awesome technical editor.
At Pearson, Loretta Yates is an excellent acquisitions editor. Thanks to the Kughens for
guiding this book through production. I updated this edition in residence at the Kola Mi
Writing Camp. My sincere thanks to the staff there for keeping me on track.
Along the way, I’ve learned a lot about VBA programming from the awesome com-
munity at the MrExcel.com message board. VoG, Richard Schollar, and Jon von der
Heyden all stand out as having contributed posts that led to ideas in this book. Thanks
to Pam Gensel for Excel macro lesson #1. Mala Singh taught me about creating charts in
VBA. Suat Özgür keeps me current on new VBA trends and contributed many ideas to
Chapter 18.
My family was incredibly supportive during this time. Thanks to Mary Ellen Jelen.
—Bill
Thank you to all the moderators at the MrExcel forum who keep the board organized,
despite the best efforts of the spammers. Thank you to Joe4, RoryA, and Petersss for
helping process all the forum’s contact emails.
Final Fantasy XIV has become my second home. I’d like to give a special thank you
to my in-game friends who not only make gaming so much fun, but for also helping
me find the confidence to dive head first into the unknown: War, Chraz, and Shabadoo.
Thank you for sharing your love of gaming with me.
And last, but not least, thanks to Bill Jelen. His site, MrExcel.com, is a place where
thousands come for help. It’s also a place where I, and others like me, have an opportu-
nity to learn from and assist others.
—Tracy
xxv
Tracy Syrstad is a Microsoft Excel developer and author of ten Excel books. She has
been helping people with Microsoft Office issues since 1997, when she discovered free
online forums where anyone could ask and answer questions. Tracy found out she
enjoyed teaching others new skills, and when she began working as a developer,
she was able to integrate the fun of teaching with one-on-one online desktop sharing
sessions. Tracy lives on an acreage in eastern South Dakota with her husband, two cats,
two horses, and a variety of wild foxes, squirrels, and rabbits.
xxvii
Your investments in VBA will serve you well until at least 2049.
In the Excel universe today, there are versions of Excel running in Windows, in MacOS,
on mobile phones powered by Android and iOS, and in modern browsers using Excel
Online. In my world, I use Excel 99% of the time on a Windows computer. There is per-
haps 1% of the time where I will open an Excel workbook on an iPad. But, if you are in a
mobile environment where you are using Excel in a browser, then the TypeScript UDFs
might be appropriate for you.
For an introduction to TypeScript UDFs in Excel, read Suat M. Ozgur’s Excel Custom
Functions Straight to the Point (ISBN 978-1-61547-259-8).
xxix
The threat to Excel VBA is the new Excel Power Query tools found in the Get &
Transform tab of the Data tab in Excel for Windows. If you are writing macros to clean
imported data, you should consider cleaning the data once with Power Query and then
refreshing the query each day. I have a lot of Power Query workflows set up that would
have previously required VBA. For a primer on Power Query, check out Master Your Data
with Excel and Power BI: Leveraging Power Query to Get & Transform Your Task Flow by
Ken Puls and Miguel Escobar (ISBN 978-1-61547-058-7).
Chapter 4, “Looping and flow control,” covers the power of looping using VBA. The
case study in this chapter demonstrates creating a program to produce a department
report and then wrapping that report routine in a loop to produce 46 reports.
xxx Introduction
Chapters 15, “Creating charts,” through 20, “Automating Word,” handle charting, data
visualizations, web queries, sparklines, and automating Word.
Chapter 22, “Advanced userform techniques,” shows you how to go further with
userforms. Chapter 23, “The Windows Application Programming Interface (API),” teaches
some tricky ways to achieve tasks using the Windows API. Chapters 24, “Handling errors,”
through 26, “Creating Excel add-ins,” deal with error handling, custom menus, and add-
ins. Chapter 27, “An introduction to creating Office add-ins,” provides a brief introduc-
tion to building your own TypeScript application within Excel. Chapter 28, “What’s new in
Excel 365 and what’s changed,” summarizes the changes in Excel 365.
Bill regularly presents a Power Excel seminar for accountants. These are hard-core
Excelers who use Excel 30 to 40 hours every week. Even so, two things come out in every
seminar. First, half of the audience gasps when they see how quickly you can do tasks
with a particular feature, such as automatic subtotals or pivot tables. Second, someone in
the audience routinely trumps me. For example, someone asks a question, I answer, and
someone in the second row raises a hand to give a better answer.
The point? Both the authors and the audience of this book know a lot about Excel.
However, we assume that in any given chapter, maybe 58% of the people have not used
pivot tables before and maybe even fewer have used the Top 10 Filter feature of pivot
tables. With this in mind, before we show how to automate something in VBA, we briefly
cover how to do the same task in the Excel interface. This book does not teach you how
to make pivot tables, but it does alert you when you might need to explore a topic and
learn more about it elsewhere.
Introduction xxxi
Creating the report was not easy. As in many other companies, there were
exceptions in the data. Valerie knew that certain accounts in one particular
cost center needed to be reclassed as expenses. She knew that other accounts
needed to be excluded 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 worksheet. Then she created a new pivot table report for the
second section of the summary. After about three hours, she had imported the
data, produced five pivot tables, arranged them in a summary, and neatly for-
matted the report in color.
More cheers
The next day, Valerie’s manager attended the monthly department meeting.
When the department managers started complaining that they could not get
the report from the ERP system, this manager pulled out his department’s
report and placed it on the table. The other managers were amazed. How was
he able to produce this report? Everyone was relieved to hear that someone
had cracked the code. The company president asked Valerie’s manager if he
could have the report produced for each department.
xxxii Introduction
Right now, either you or someone in your company is probably stuck doing
manual tasks in Excel that can be automated with VBA. We are confident that
we can walk into any company that has 20 or more Excel users and find a case
just as amazing as Valerie’s.
Versions of Excel
This seventh edition of VBA and Macros is designed to work with Microsoft 365 features
released up through August 2021. The previous editions of this book covered code for
Excel 97 through Excel 2019. In 80% of the chapters, the code today is identical to the
code in previous versions.
Introduction xxxiii
■■ Italic—Indicates new terms when they are defined, special emphasis, non-English
words or phrases, and letters or words used as words.
In addition to the case studies, you will see Notes, Tips, and Cautions.
Note Notes provide additional information outside the main thread of the
chapter discussion that might be useful for you to know.
Tip Tips provide quick workarounds and time-saving techniques to help you
work more efficiently.
Caution Cautions warn about potential pitfalls you might encounter. Pay
attention to the Cautions; they alert you to problems that might otherwise
cause you hours of frustration.
xxxiv Introduction
MicrosoftPressStore.com/ExcelVBAMacros365/errata.
If you find an error that is not already listed, you can report it to us through the same
page.
Please note that product support for Microsoft software and hardware is not offered
through the previous addresses. For help with Microsoft software or hardware, go to
http://support.microsoft.com.
Stay in touch
Let’s keep the conversation going! We’re on Twitter:
http://twitter.com/MicrosoftPress
http://twitter.com/MrExcel
Introduction xxxv
Referring to ranges
■■ Use the Intersect method to create a new range from overlapping ranges
A range can be a cell, a row, a column, or a grouping of any of these. The Range object is probably the
most frequently used object in Excel VBA; after all, you’re manipulating data on a sheet. Although a
range can refer to any grouping of cells on a sheet, it can refer to only one sheet at a time. If you want
to refer to ranges on multiple sheets, you must refer to each sheet separately.
This chapter shows you different ways of referring to ranges, such as specifying a row or column.
You’ll also find out how to manipulate cells based on the active cell and how to create a new range
from overlapping ranges.
53
The Range object is a property of the Worksheet object. This means it requires that a sheet be active
or else it must reference a worksheet. Both of the following lines mean the same thing if Worksheets(1)
is the active sheet:
Range("A1")
Worksheets(1).Range("A1")
There are several ways to refer to a Range object. Range("A1") is the most identifiable because that is
how the macro recorder refers to it. However, all the following are equivalent when referring to cell D5:
Range("D5")
[D5]
Range("B3").Range("C3")
Cells(5,4)
Range("A1").Offset(4,3)
Range("MyRange") 'assuming that D5 has a Name of MyRange
Which format you use depends on your needs. Keep reading. It will all make sense soon!
Range("A1:B5")
In the alternative syntax, specify the upper-left corner and lower-right corner of the desired rectan-
gular range. In this syntax, the equivalent statement might be this:
Range("A1", "B5")
For either corner, you can substitute a named range, the Cells property, or the ActiveCell prop-
erty. The following line of code selects the rectangular range from A1 to the active cell:
Range("A1", ActiveCell).Select
The following statement selects from the active cell to five rows below the active cell and two col-
umns to the right:
Worksheets("Sheet1").Range("MyRange")
Notice the name of the range is in quotes—unlike the use of named ranges in formulas on the sheet
itself. If you forget to put the name in quotes, Excel thinks you are referring to a variable in the pro-
gram. One exception is if you use the shortcut syntax discussed in the next section. In that case, quotes
aren’t used.
Range("D5") [D5]
Range("A1:D5") [A1:D5]
Range("MyRange") [MyRange]
Worksheets("Sheet1").Range("A1")
This line of code references Sheet1 of the active workbook even if Sheet2 is the active sheet.
To reference a range in another workbook, include the Workbook object, the Worksheet object, and
then the Range object:
Workbooks("InvoiceData.xlsx").Worksheets("Sheet1").Range("A1")
To use the Range property as an argument within another Range property, identify the range fully each
time. For example, suppose that Sheet1 is your active sheet and you need to total data from Sheet2:
WorksheetFunction.Sum(Worksheets("Sheet2").Range(Range("A1"), _
Range("A7")))
WorksheetFunction.Sum(Worksheets("Sheet2").Range(Worksheets("Sheet2"). _
Range("A1"), Worksheets("Sheet2").Range("A7")))
However, not only is this a long line of code, but it is also difficult to read! Thankfully, there is a
simpler way, using With...End With:
With Worksheets("Sheet2")
WorksheetFunction.Sum(.Range(.Range("A1"), .Range("A7")))
End With
Notice now there is a .Range in your code but without the preceding object reference. That’s
because With Worksheets("Sheet2") implies that the object of the range is that worksheet. Whenever
Excel sees a period without an object reference directly to the left of it, it looks up the code for the
closest With statement and uses that as the object reference.
Range("B5").Range("C3").Select
This code actually selects cell D7. Think about cell C3, which is located two rows below and two
columns to the right of cell A1. The preceding line of code starts at cell B5. If we assume that B5 is
in the A1 position, VBA finds the cell that would be in the C3 position relative to B5. In other words,
VBA finds the cell that is two rows below and two columns to the right of B5, which is D7.
Again, I consider this coding style to be very unintuitive. This line of code mentions two addresses,
and the actual cell selected is neither of these addresses! It seems misleading when you’re trying to
read this code.
You might consider using this syntax to refer to a cell relative to the active cell. For example, the
following line of code activates the cell three rows down and four columns to the right of the currently
active cell:
Selection.Range("E4").Select
I mention this syntax only because the macro recorder uses it. Recall that when you recorded a
macro in Chapter 1, “Unleashing the power of Excel with VBA,” with relative references on, the following
line was recorded:
ActiveCell.Offset(0, 4).Range("A1").Select
Although a worksheet is usually the object of the Range property, occasionally, such as during
recording, a range may be the property of a range.
Cells.Select
Using the Cells property with the Range object might seem redundant:
Range("A1:D5").Cells
This line refers to the original Range object. However, the Cells property has an Item property that
makes the Cells property very useful. The Item property enables you to refer to a specific cell relative
to the Range object.
The syntax for using the Item property with the Cells property is as follows:
Cells.Item(Row,Column)
You must use a numeric value for Row, but you may use the numeric value or string value for Column.
Both of the following lines refer to cell C5:
Cells.Item(5,"C")
Cells.Item(5,3)
Because the Item property is the default property of the Range object, you can shorten these lines as
follows:
Cells(5,"C")
Cells(5,3)
The ability to use numeric values for parameters is particularly useful if you need to loop through
rows or columns. The macro recorder usually uses something like Range("A1").Select for a single cell
and Range("A1:C5").Select for a range of cells. If you’re learning to code only from the recorder, you
might be tempted to write code like this:
Instead of trying to type the range address, the new code uses the Cells and Resize properties to
find the required cell, based on the active cell. See the “Using the Resize property to change the size of
a range” section later in this chapter for more information on the Resize property.
You can use the Cells properties for parameters in the Range property. The following refers to the
range A1:E5:
Range(Cells(1,1),Cells(5,5))
This is particularly useful when you need to specify variables with a parameter, as in the previous
looping example.
Range.Offset(RowOffset, ColumnOffset)
For example, the following code affects cell F5 from cell A1:
Range("A1").Offset(RowOffset:=4, ColumnOffset:=5)
Range("A1").Offset(4,5)
The count of the rows and columns starts at A1 but does not include A1.
If you need to go over only a row or a column, but not both, you don’t have to enter both the row
and the column parameters. To refer to a cell one column over, use one of these lines:
Range("A1").Offset(ColumnOffset:=1)
Range("A1").Offset(,1)
Range("B2").Offset(RowOffset:=-1)
Range("B2").Offset(-1)
Once again, you can choose which one to use. It’s a matter of the readability of the code.
Suppose you have a list of produce in column A, with totals next to the produce items in column B. If
you want to find any total equal to zero and place LOW in the cell next to it, do this:
When used in a Sub and looping through a data set, it would look like this:
Sub FindLow()
With Range("B1:B16")
Set Rng = .Find(What:="0", LookAt:=xlWhole, LookIn:=xlValues)
If Not Rng Is Nothing Then
firstAddress = Rng.Address
Do
Rng.Offset(, 1).Value = "LOW"
Set Rng = .FindNext(Rng)
Loop While Not Rng Is Nothing And Rng.Address <> firstAddress
End If
End With
End Sub
The LOW totals are noted by the program, as shown in Figure 3-1.
FIGURE 3-1 The code puts “LOW” next to the zeros in the data set.
Note Refer to the section “Object variables” in Chapter 4, “Looping and flow control,” for
more information on the Set statement.
Offsetting isn’t only for single cells; you can use it with ranges. You can shift the focus of a range
over in the same way you can shift the active cell. The following line refers to B2:D4 (see Figure 3-2):
Range("A1:C3").Offset(1,1)
Range.Resize(RowSize, ColumnSize)
Range("B3").Resize(RowSize:=11, ColumnSize:=3)
Range("B3").Resize(11, 3)
But what if you need to resize by only a row or a column—not both? You don’t have to enter both
the row and the column parameters.
Range("B3").Resize(ColumnSize:=2)
or
Range("B3").Resize(,2)
Both lines mean the same thing. The choice is yours. If you use the second line, make sure to include
the comma so Excel knows the 2 refers to the ColumnSize argument. Resizing just the rows is similar.
You can use either of the following:
Range("B3").Resize(RowSize:=2)
or
Range("B3").Resize(2)
Once again, the choice is yours. It is a matter of the readability of the code.
Notice that the Offset property first moves the active cell over to the produce column. When you’re
resizing, the upper-left-corner cell must remain the same.
Resizing isn’t only for single cells; you can use it to resize an existing range. For example, if you have
a named range but need it and the column next to it, use this:
Range("Produce").Resize(,2)
Remember, the number you resize by is the total number of rows/columns you want to include.
This line of code finds the last row in a sheet in which column A has a value and places the row
number of that Range object into the variable called FinalRow. This can be useful when you need to
loop through a sheet row by row; you will know exactly how many rows you need to go through.
Note Some properties of columns and rows require contiguous rows and columns in order
to work properly. For example, if you were to use the following line of code, 9 would be the
answer because only the first range would be evaluated:
Range("A1:B9, C10:D19").Rows.Count
However, if the ranges were grouped separately, the answer would be 19. Excel takes the
top-left cell address, A1, and the bottom-right cell address, D19, and counts the rows in the
range A1:D19:
Range("A1:B9", "C10:D19").Rows.Count
The expression Application is not required. The following code joins two named ranges on the
sheet, inserts the =RAND() formula, and bolds them:
The expression Application is not required. The following code colors the overlapping cells of the
two ranges:
IsEmpty(Cell)
FIGURE 3-4 You can make separations more obvious by using colored rows.
RangeObject.CurrentRegion
The following line selects A1:D3 because this is the contiguous range of cells around cell A1 (see
Figure 3-5):
Range("A1").CurrentRegion.Select
This is useful if you have a data set whose size is in constant flux.
FIGURE 3-5 You can use CurrentRegion to select a range of contiguous data around the active cell.
FIGURE 3-6 Although the Go To dialog box doesn’t seem useful, click the Special button in the lower-left corner to
specify what type of cells to select.
In the Excel interface, the Go To Special dialog box enables you to select only cells with
formulas, only blank cells, or only the visible cells. Selecting only visible cells is excellent for
grabbing the visible results of AutoFiltered data. If you already have a range highlighted, only
cells within this range meeting the criteria will be selected. Make sure only one cell is selected
to search the entire sheet.
To simulate the Go To Special dialog box in VBA, use the SpecialCells method. This enables
you to act on cells that meet certain criteria, like this:
RangeObject.SpecialCells(Type, Value)
FIGURE 3-7 The Go To Special dialog box has many incredibly useful selection tools, such as one for selecting only
the formulas on a sheet.
Set one of the following optional Value constants if you use xlCellTypeConstants or
xlCellTypeFormulas:
xlErrors
xlLogical
xlNumbers
xlTextValues
The following code returns all the ranges that have conditional formatting. It produces an
error if there are no conditional formats and adds a border around each contiguous section it
finds:
Set rngCond = ActiveSheet.Cells.SpecialCells(xlCellTypeAllFormatConditions)
If Not rngCond Is Nothing Then
rngCond.BorderAround xlContinuous
End If
Have you ever had someone send you a worksheet without all the labels filled in? Some
people think that the data shown in Figure 3-8 looks tidy. They enter the Region field only once
for each region. This might look aesthetically pleasing, but it’s impossible to sort.
FIGURE 3-8 The blank cells in the Region column make it difficult to sort data sets such as this.
Using the SpecialCells method to select all the blanks in this range is one way to fill the
blank region cells quickly using the region found above them:
Sub FillIn()
On Error Resume Next 'Need this because if there aren't any blank
'cells, the code will error
Range("A1").CurrentRegion.SpecialCells(xlCellTypeBlanks).FormulaR1C1 _
= "=R[-1]C"
Range("A1").CurrentRegion.Value = Range("A1").CurrentRegion.Value
End Sub
FIGURE 3-9 After the macro runs, the blank cells in the Region column have been filled with data.
You might be tempted to loop through the rows in a sheet and check the properties of a cell in a row,
such as its formatting (for example, font or fill) or whether the cell contains a formula or value. Then you
could copy the row and paste it to another section. However, there is an easier way. In Figure 3-10, the
user enters the values below each fruit and vegetable. The percentages are formulas. The following line
of code selects the cells with numeric constants and copies them to another area:
FIGURE 3-10 The Areas collection makes it easier to manipulate noncontiguous ranges.
Although you can reference a table by using Worksheets(1).Range("Table1"), you have access to
more of the properties and methods that are unique to tables if you use the ListObjects object, like
this:
Worksheets(1).ListObjects("Table1")
This opens the properties and methods of a table, but you can’t use that line to select the table.
To do that, you have to specify the part of the table you want to work with. To select the entire table,
including the header and total rows, specify the Range property:
Worksheets(1).ListObjects("Table1").Range.Select
What I really like about coding with tables is the ease of referencing specific columns of a table.
You don’t have to know how many columns to move in from a starting position or the letter/number
of the column, and you don’t have to use a FIND function. Instead, you can use the header name of
the column. For example, to select the data of the Qty column of the table, but not the header or total
rows, do this:
Worksheets(1).ListObjects("Table1").ListColumns("Qty")_
.DataBodyRange.Select
Note For more details on coding with tables, check out Excel Tables: A Complete Guide
for Creating, Using, and Automating Lists and Tables by Zack Barresse and Kevin Jones
(ISBN: 9781615470280).
579
replacing a list of values with a condition created replacing loops with, 175–178
from a formula, 193–194 selecting a dynamic date range, 180–181
retrieving unique combinations of two or more fields, selecting multiple items, 178–179
190
selecting using the Search box, 179
xlFilterCopy, 202
turning off drop-down menus, 209–210
combining multiple techniques, 205–209
AutoSort method, 226
copying a subset of columns and reordering,
Autosum button, 24–25, 26
203–205
copying all columns, 202–203
alpha characters, sorting, 301–303 B
API (Application Programming Interface), 491. See also
backward compatibility, .AddChart2 method,
Spotify
337–338
declarations, 492
Barresse, Z., 263, 278
32-bit- and 64-bit-compatible, 493–494
Excel Tables: A Complete Guide for Creating, Using,
private, 492 and Automating Lists and Tables, 67
using, 493 barriers to learning VBA, 2. See also learning VBA
functions BASIC, 2, 28
checking whether an Excel file is open on a binding. See early binding; late binding, 499
network, 495–496
blocks, With…End With, 50
creating a running timer, 498–499
bookmarks, 441–442
customizing the About dialog box, 497
BookOpen() function, 288–289
disabling the X for closing a user form, 498
borders, chart, 331
playing sounds, 499
breakpoints, 40, 41
retrieving display-resolution information,
backing up or moving forward, 40
496–497
querying
retrieving the computer name, 495
by hovering, 42
getting credentials for accessing, 386–387
using a Watches window, 42–43
applications, events, 120–124
using the Immediate window, 41–42
setting up a class module, 134
setting with watches, 43
trapping, 134–135
Bricklin, D., 87
Archibald, R., 260
building
Areas collection, 66
advanced filters, 184
arrays, 125, 145
Data Model, 247–249
declaring, 125–126
LAMBDA functions, 307–308
dynamic, 130–131
pivot tables, 245–246, 255–256
filling, 127–128
UDFs (user-defined functions), 286–287
formulas, 573
buttons
JavaScript, 562–563
Autosum, 24–25, 26
multidimensional, declaring, 126–127
command, 160, 161–162
names and, 104
command, running a macro with, 534–535
passing, 131–132
creating, 557–558
retrieving data from, 128–129
Help, 576
speeding up code with, 129–130
option
assigning, macros
adding to a userform, 165–166
to a form control, 12–13
events, 166
to an object, 13
spin, 168–169
AutoFilter
toggle, 471–472
filtering
using images on, 527
by color, 179
by icon, 179–180
580
581
582
583
584
585
586
MSubstitute(), 297–298
NumUniqueValues(), 296
I
icon(s), 340, 575
RetrieveNumbers(), 298–299
filtering by, 179–180
sharing, 288
plus sign, 322–323
SheetExists(), 289–291
Restore Down, 39
SortConcat(), 300–301
sets, adding to a range, 347–348, 351–352
SumColor(), 295
constants, 348–349
WinUserName(), 291–292
specifying an icon set, 348–349
VLOOKUP, 107
specifying ranges for each icon, 350
XLOOKUP, named ranges and, 107–109
Stop Recording, 10
using on the ribbon, 527–529
G If statements, nesting, 84–86
GetAddress() function, 305 If-Else If-End If construct, 82–83
GetObject function, 431–432 If-Then-Else construct, 81
global If-Then-Else-End If construct, 82
names, 97–98 If-Then-End If construct, 82
variables, 402 images, adding to userforms on the fly, 480–481
Go To Special dialog box, 64, 201 Immediate window (VB Editor), 35, 41–42
loops and, 182–183 importing
Visible Cells Only option, 181–182 CSV files, 260
Gonzàlez Ruiz, J. P., 268 text files, 413
gradients, applying to objects, 330 input boxes, 153–154
graphic controls, 167 InsertLines method, 280
grouping, dates, 221–223 installing, add-ins, 543–544
Intersect method, 62
IsEmailValid() function, 293–295
H IsEmpty function, 62–63
Help topics, 32–34
code and, 37
constants, 35
J
optional parameters, 34–35 JavaScript
properties and, 38 adding interactivity to Office add-ins, 559–560
ToolTips and, 42 arrays, 562–563
Hide method, 156–157 comments, 561
hiding custom functions, 549
names, 106 For each...next statement, 565–566
userforms, 156–157 functions, 560–561
HomeKey method, 437 if statements, 564
HTML, 557 for loops, 563
comments, 557 math functions, 567–568
tags, 557 Office add-ins and, 569–570
hyperlinks operators, 566–567
returning the address, 305 Select Case construct, 564–565
running a macro from, 537 strings, 562
userforms and, 476–477 variables, 561
587
K JavaScript, 563
M, 402
Kaji, M., 260
If-then logic, 403–404
Kapor, M., 87
List.Generate, 404–406
keyboard shortcuts. See shortcut(s)
nesting, 74–75
keywords
replacing with AutoFilter, 175–178
New, 430–431
While...Wend, 79
Preserve, 131
Lotus 1–3, 24, 87
Klann, D., 275
M
L M, 385
labels, 159, 161–162
global variables, 402
LAMBDA functions, 307, 573
loops, 402
building, 307–308
If-then logic, 403–404
sharing, 308
List.Generate, 404–406
SLUGIFY.PLUS(), 309–310
searching Spotify for an artist, 388–389
TOC2HTML(), 310–311
macro button, creating
Lanzo, L., 264
on the Quick Access Toolbar, 11–12
late binding, 145, 430
on the ribbon, 10–11
layout
macro recorder
pivot table, 250–251
absolute references, 19–20
report, 251
charts and, 318
learning VBA, 3
relative references, 20–24
barriers
shortcomings of, 15–16
macro recorder, 2
tips for using, 25–26
syntax, 2
macros. See also code
line settings, trendline, 331
assigning
LineFormat object, 331
to a form control, 12–13
list boxes, 162–163
to an object, 13
events, 164–165
attaching
multicolumn, 486–487
to an ActiveX control, 536
MultiSelect property, 163–164
to a shape, 535
Load method, 156
canceling, 408
loading large files to the Data Model, 423–424
copying to new workbooks, 279–280
local names, 97–98, 104
passwords and, 515
logical AND, 193
recording, 8–9
logical OR, 192
running, 10
loops, 69
from a hyperlink, 537
Do, 75–77
using a keyboard shortcut, 533–534
stopping, 77
scheduling, 407, 408–411
While and Until clauses, 77–79
searching Spotify database for an artist, 400
588
589
590
evolution over various Excel versions, 211–212 programming languages. See also M
filtering data sets, 229 BASIC, 2, 28
filters M, 385
conceptual, 230–231 object-oriented, 28
manual, 229–230 procedural, 28
search, 234–236 Programming window, VB Editor, 17–19
ShowDetail property and, 250 progress indicator, cell, 274–275
slicers, 237–241 Project Explorer, 14–15
types, 232–234 properties, 31, 137
formatting the intersection of values in, 243–244 .Calculation, 223
grouping daily dates to months, quarters, or years, Cells, referencing ranges with, 57–58
221–223 ChartColor, 320–321
layout, 250–251 Columns, 61
OLAP, filtering by a list of items, 271–273 CurrentRegion, selecting ranges with, 63
producing a static summary, 218–220 custom, creating, 148–151
reports, 217 Excel8CompatibilityMode, 577–578
layout, 251 Formula, 352–354
multiple value fields, 220–221 Help topics, 38
replicating for every product, 226–229 MultiSelect, 163–164
suppressing subtotals for multiple row fields, 252 NumberFormat, 361–362
TypeScript and, 255–256 ObjectThemeColor, 329
Values area OFFSET, 177
adding numeric fields, 246–247 Offset, referencing ranges with, 58–60
eliminating blank cells, 226 Priority, 341
Power Pivot, 244. See also pivot table(s) Range(), 47
Power Query. See also M Resize, 60–61
Advanced Editor, 387–388 Rows, 61
building a custom function, 390–393 ShowDetail, 250
loading large text files to the Data Model, 423–424 TableRange2, 217–218
M and, 385 Type, 341
queries Version, 577
AlbumTracks, 395, 397 Properties window, VB Editor, 15
ArtistsAlbums, 394–395, 396–397 protected password box, 275–277
duplicating to make a new query, 393–395
error handling, 403
fnGetToken, 392 Q
grouping, 397–398 QueryClose event, 172
placing results on your dashboard, 398–401 querying, in Break mode
SearchArtist, 391, 393, 396 by hovering, 42
refreshing Spotify credentials after they expire, 390 using a Watches window, 42–43
searching Spotify database for an artist, 388–390 using the Immediate window, 41–42
storing global variables in a Settings record, 402–403 Quick Access Toolbar, creating a macro button, 11–12
Preserve keyword, 131 Quick Analysis tool, 24–25, 573
PresetGradient method, 330
PresetTextured method, 329
PrintOut method, 437 R
Priority property, 341 R1C1 addressing, 49, 87, 90, 91
procedural programming, 28 absolute references, 92–93
VBA and, 29 mixed references, 93
591
592
593
594
userforms, 153. See also controls; forms placing a chart in a cell note, 265–267
accelerator keys, 483–484 reading a text file into memory and parsing, 260–261
adding option buttons, 165–166 resetting a table’s format, 278–279
calling, 156 selecting with SpecialCells, 277–278
check boxes, 466–468 separating worksheets into workbooks, 261–262
coloring the active field, 485–486 tracking user changes, 267–268
controls using a protected password box, 275–277
adding at runtime, 477–478 using VBA Extensibility to add code to new work-
adding on the fly, 479 books, 279–280
collections and, 473–475
ProgIds, 480
creating, 155–156
V
validating, email addresses, 293–295
disabling the X for closing, 498
values
events, 157–158
duplicate, minimizing, 340
graphics, 167
unique, counting, 296
hiding, 156–157
variables, 49
hyperlinks, 476–477
declaring, 14
illegal window closing, 172
global, 402
images, adding on the fly, 480–481
JavaScript, 561
input boxes, 153–154
object, 79–81
message boxes, 154–155
For statement, 72
modeless, 475–476
Variant, 128
picture catalog, 481–483
Variant variables, 128
programming, 157
VB Editor, 13–14. See also Object Browser
RefEdit control, 470–471
Break mode, 38–43. See also breakpoints
resizing on the fly, 479
converting a file to an add-in, 542–543
scrollbars, 472–473
Help and, 33–34
setting tab stops, 484–485
Immediate window, 35, 41–42
sizing on the fly, 479
Programming window, 17–19
tab strips, 468–470
Project Explorer, 14–15
tip text, adding, 484
Properties window, 15
transparent, 487–488
settings, 14
verifying field entry, 171
VBA, 31–32
UserPicture method, 329
barriers to learning
utilities
macro recorder, 2
combining workbooks, 262–263
syntax, 2
converting a fixed-width report to a data set,
280–283 charts
copying data to separate worksheets without using applying a color, 320–321
Filter, 263–264 borders, 331
creating a cell progress indicator, 274–275 combo, 331–334
creating a custom sort order, 273–274 filtering, 322
creating an Excel state class module, 268–270 formatting, 327–328
drilling-down a pivot table, 270–271 line settings, 331
exporting data to an XML file, 264–265 map, 335
filtering an OLAP pivot table by a list of items, referring to, 318–319
271–273 SetElement method, 322–327
importing and deleting a CSV file, 260 specifying a title, 319–320
listing files in a directory, 257–260 styles, 315–318
595
596
597