Excel VBA in Easy Steps
Excel VBA in Easy Steps
1 Getting started 7
Introducing Excel VBA 8
Recording a macro 10
Viewing macro code 12
Testing a macro 14
Editing macro code 15
Referencing relatives 16
Saving macros 18
Trusting macros 20
Summary 22
2 Writing macros 23
Exploring the Editor 24
Creating a macro 26
Adding toolbar buttons 28
Adding Form Controls 30
Recognizing hierarchy 32
Identifying a range 34
Addressing cells 36
Summary 38
3 Storing values 39
Creating variables 40
Defining data types 42
Managing strings 44
Producing arrays 46
Describing dimensions 48
Representing objects 50
Declaring constants 52
Summary 54
4 Performing operations 55
Doing arithmetic 56
Making comparisons 58
Assessing logic 60
Joining strings 62
Understanding precedence 64
Summary 66
5 Making statements 67
Choosing a branch 68
Branching alternatives 70
Selecting branches 72
Performing loops 74
Looping while true 76
Breaking from loops 78
Iterating for each 80
Including with 82
Summary 84
6 Executing procedures 85
Calling subroutines 86
Modifying scope 88
Passing arguments 90
Adding modules 92
Fixing values 94
Debugging code 96
Handling errors 98
Summary 100
7 Employing functions 101
Defining a function 102
Calling a function 104
Scoping a function 106
Passing array arguments 108
Stating options 110
Returning errors 112
Debugging functions 114
Describing functions 116
Summary 118
Index 187
1 Getting started
Enabling VBA
8
Before you can get started using the capabilities of VBA, it must
first be enabled in your Excel installation:
l
com/resource-centre/
downloads 2 When the workbook opens,
choose the File item on the
Excel Ribbon
...cont’d
9
In the Excel Options
dialog you can click
l
contains. If you right-
6 Click the OK button to apply the change and to close click on any group, a
the Excel Options dialog box context menu offers you
options to modify the
Recording a macro
Having enabled VBA, as described on pages 8-9, you can create a
simple app by recording a “macro” to store actions:
l
macro will perform.
5 Now, choose to
store the macro
in This Workbook
A macro is a set
of programming
instructions stored in
VBA code.
...cont’d
11
macro, then click
the Run button
to execute the
macro and see You can also use the
shortcut keys Alt +
the book title
F8 to open the Macro
text appear in dialog box at any time.
the automatically
selected cell A2
Getting started
l
Basic Editor interface.
3 In Project Explorer, click the
+ button beside the Book1
project to expand its contents
...cont’d
Code analysis
• “subroutine” (
Sub BookTitle ( ) – This declares the beginning of a
Sub) with the same name you gave to the macro
(BookTitle) and was written when it began recording.
13
This is a comment, confirming that this
‘ BookTitle Macro
of your chosen name.
• was written
– This denotes the end of this macro subroutine, and
End Sub
when you stopped recording.
The color used in the code is the default syntax highlighting that All lines that begin with
the Visual Basic Editor automatically applies for easier reading. an apostrophe are simply
Blue is applied to “keywords” that have special meaning in Visual ignored when the macro
Basic code, and green is applied to comments describing the code. is executed.
For clarity, the same color syntax highlighting is also used in the
example code listed in the steps provided throughout this book.
Getting started
Testing a macro
Before starting to record the macro, as described on page 10,
shortcut keys were specified in the Record Macro dialog and these
can now be tested to ensure they can run the macro:
15
l 5 Click
the
Save
The eight Visual Basic
color constants are
vbRed, vbGreen, vbBlue,
button vbYellow, vbMagenta,
vbCyan, vbBlack, and
vbWhite – see pages
52-53 for more on
constants.
Referencing relatives
Excel has two macro recording modes that differ in the way they
refer to cells on the worksheet. The default recording mode, used
in the previous examples, refers to cells by their “absolute” position
on the worksheet – cell A1, A2, A3, and so on. The alternative
recording mode refers to cell locations by their position on the
Macros recorded using worksheet “relative” to other cells – offset by a specified number
relative referencing are
of rows and columns from another cell. The difference between
often more flexible, as
they can be applied
the two recording modes is important, as macros that use absolute
anywhere in a workbook. referencing always reference the same cell locations regardless
of the currently selected cell, whereas macros that use relative
referencing reference cells at locations offset from the selected cell:
l 2 Type this
book’s topic,
then select cell
B2 and type
16
this book’s
series name
l 3 Hit Enter,
then click Stop
Recording
l 4 Clear all
worksheet
cells, then
select cell A1
Shortcut keys might also and click the
be specified to run these Use Relative
macros – for example, References
Ctrl + Shift + A button in the
(Absolute) and Code group
Ctrl + Shift + R
l
(Relative).
5 Begin a macro named “RelativeBookTitle”, then repeat
Steps 2 and 3 to complete the macro
...cont’d
17
but relative referencing refers to it as offset by 1 row and 1
column from the initially selected cell. To compare performance:
l 7 Clear all cells, then select cell A2 and run the macro
named “AbsoluteBookTitle”
l
the macro using relative
8 Again, clear all cells, then once more select cell A2 and referencing writes the
book series name in cell
run the macro named “RelativeBookTitle”
B3 – as it is offset by 1
row and 1 column from
the initially selected cell.
Getting started
Saving macros
Since Excel 2007, workbook files have had the standard file
extension of “.xlsx”, but these cannot contain Visual Basic
macros. In order to save an Excel workbook and its macros, it
must instead be saved as an Excel Macro-Enabled Workbook
that is given a file extension of “.xlsm”. If you save a workbook
containing a macro as a standard “.xlsx” file, all macro code will be
lost – but Excel will warn you before this happens:
l
18
19
l 3 A dialog will appear
asking if you wish to
save changes made to
the Personal Macro
Workbook – click the
Save button to retain the macro
Trusting macros
Excel Workbook files (.xlsx) are regarded as safe, as they merely
contain data, whereas Excel Macro-Enabled Workbook files
(.xlsm) may pose a potential threat, as they are executable.
Recognizing this, Excel automatically disables the macros in an
Excel Macro-Enabled Workbook until the user consents to trust
Both .xlsx and .xlsm file their safety. On opening a workbook that contains macros, a
types store workbook
security warning offers the user the option to enable macros. If
data in XML format.
Excel also supports
the user consents to enable macros, the workbook is regarded as
.xlsb files that store trustworthy and the security warning will never appear again.
workbook data in binary
As an alternative to enabling macros in individual workbooks, a
format. This is favored
by some users, but
folder can be nominated as a trusted location. This then allows
workbook content is Excel Macro-Enabled Workbook files to be placed inside that
more accessible to other folder and run without security restrictions:
software when stored as
XML data.
l 1 Navigate to the folder containing an Excel Macro-
Enabled Workbook, and open it in Excel
20
l 6 Browse to
select the
folder you
wish to
nominate
21
as a trusted
location
for Excel
Macro-
Enabled
Workbooks
All workbooks in
Trusted Locations will
run without security
restrictions.
Getting started
Summary
• VBA (Visual Basic for Applications) is the programming
language built into Excel that extends its capabilities beyond
the standard Excel tools.
• Macro
The Code group on the Developer tab contains a Record
button with which to create VBA macros.
• Recorded
22
• enables
The Use Relative References button in the Code group
Excel’s alternative macro recording mode, which
references cells by their relative position.
• AExcel
workbook that contains macro code must be saved as an
Macro-Enabled Workbook and “.xlsm” file extension.
• AMacro-Enabled
folder can be nominated as a trusted location where Excel
Workbooks can be placed and run without
security restrictions.