Tải bản đầy đủ (.pdf) (260 trang)

Microsoft excel programming pocket primer

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (10.14 MB, 260 trang )


MICROSOFT®

EXCEL® PROGRAMMING
Pocket Primer


LICENSE, DISCLAIMER OF LIABILITY, AND LIMITED WARRANTY
By purchasing or using this book and disc (the “Work”), you agree that this license
grants permission to use the contents contained herein, including the disc, but does
not give you the right of ownership to any of the textual content in the book / disc
or ownership to any of the information or products contained in it. This license does
not permit uploading of the Work onto the Internet or on a network (of any kind)
without the written consent of the Publisher. Duplication or dissemination of any
text, code, simulations, images, etc. contained herein is limited to and subject to
licensing terms for the respective products, and permission must be obtained from
the Publisher or the owner of the content, etc., in order to reproduce or network any
portion of the textual material (in any media) that is contained in the Work.
MERCURY LEARNING AND INFORMATION (“MLI” or “the Publisher”) and anyone
involved in the creation, writing, or production of the companion disc, accompanying
algorithms, code, or computer programs (“the software”), and any accompanying
Web site or software of the Work, cannot and do not warrant the performance
or results that might be obtained by using the contents of the Work. The author,
developers, and the Publisher have used their best efforts to insure the accuracy
and functionality of the textual material and/or programs contained in this package;
we, however, make no warranty of any kind, express or implied, regarding the
performance of these contents or programs. The Work is sold “as is” without
warranty (except for defective materials used in manufacturing the book or due to
faulty workmanship).
The author, developers, and the publisher of any accompanying content, and anyone
involved in the composition, production, and manufacturing of this work will not be


liable for damages of any kind arising out of the use of (or the inability to use) the
algorithms, source code, computer programs, or textual material contained in this
publication. This includes, but is not limited to, loss of revenue or profit, or other
incidental, physical, or consequential damages arising out of the use of this Work.
The sole remedy in the event of a claim of any kind is expressly limited to replacement
of the book and/or disc, and only at the discretion of the Publisher. The use of
“implied warranty” and certain “exclusions” vary from state to state, and might not
apply to the purchaser of this product.


MICROSOFT®

EXCEL® PROGRAMMING
Pocket Primer

Julitta Korol

MERCURY LEARNING AND INFORMATION
Dulles, Virginia
Boston, Massachusetts
New Delhi


Copyright ©2015 by MERCURY LEARNING AND INFORMATION LLC. All rights reserved.
This publication, portions of it, or any accompanying software may not be reproduced in any
way, stored in a retrieval system of any type, or transmitted by any means, media, electronic
display or mechanical display, including, but not limited to, photocopy, recording, Internet
postings, or scanning, without prior permission in writing from the publisher.
Publisher: David Pallai
MERCURY LEARNING AND INFORMATION

22841 Quicksilver Drive
Dulles, VA 20166

www.merclearning.com
800-232-0223
J.Korol. Microsoft Excel Programming Pocket Primer.
ISBN: 978-1-942270-01-0
The publisher recognizes and respects all marks used by companies, manufacturers, and
developers as a means to distinguish their products. All brand names and product names
mentioned in this book are trademarks or service marks of their respective companies. Any
omission or misuse (of any kind) of service marks or trademarks, etc. is not an attempt to
infringe on the property of others.
Library of Congress Control Number: 2015935261
1516321 Printed in the United States of America
This book is printed on acid-free paper.
Our titles are available for adoption, license, or bulk purchase by institutions, corporations, etc.
For additional information, please contact the Customer Service Dept. at 800-232-0223 (toll free).
All of our titles are available in digital format at authorcloudware.com and other digital
vendors. Companion files (figures and code listings) for this title are available by contacting
The sole obligation of MERCURY LEARNING AND INFORMATION to the
purchaser is to replace the disc, based on defective materials or faulty workmanship, but not
based on the operation or functionality of the product.


For Jola
Start at the beginning and see where it
takes you…But make sure you have a plan.




CONTENTS

Dedication .............................................................................................v
Acknowledgments ................................................................................xv
Introduction...................................................................................... xvii
1. Getting Started with Excel VBA ........................................... 1
Introduction........................................................................................................ 1
Macros and VBA ................................................................................................ 2
Excel Macro-Enabled File Formats ......................................................... 2
Macro Security Settings ............................................................................ 3
Enabling the Developer Tab in Excel ............................................................... 5
Hands-On 1.1. Setting Up Excel for Macro Development ...............................................5

Using the Built-In Macro Recorder .................................................................. 7
Planning a Macro ...................................................................................... 7
Hands-On 1.2. Getting Things Ready for Macro Recording .................................8

Recording a Macro .................................................................................... 8
Hands-On 1.3. Recording a Macro that Applies Formatting to a Worksheet .......8

Using Relative or Absolute References in Macros........................ 10
Hands-On 1.4. Recording a Macro that Removes Formatting
from a Worksheet .....................................................................................11

Editing a Macro....................................................................................... 12
Hands-On 1.5. Examining the Macro Code .........................................................12

Macro Comments .......................................................................... 15
Hands-On 1.6. Adding Comments to the Macro Code ..............................16


Cleaning Up the Macro Code ........................................................ 17
Hands-On 1.7. Cleaning Up the Macro Code ............................................17

Running a Macro..................................................................................... 18
Hands-On 1.8. Running a Macro Using the Macro Dialog Box ..........................19

Testing and Debugging a Macro ............................................................ 19


viii • Microsoft Excel Programming Pocket Primer
Hands-On 1.9. Running a Macro from the VBE Screen......................................19

Saving and Renaming a Macro ............................................................... 20
Hands-On 1.10. Saving Macros and Running Macros from Another
Workbook...........................................................................................................20

Printing Macro Code .............................................................................. 21
Hands-On 1.11. Printing Macro Code .................................................................21

Improving Your Recorded Macros .................................................................. 21
Hands-On 1.12. Recording Additional Features for the Existing Macro
in a New Macro ...........................................................................................................22
Hands-On 1.13. Adding Additional Code to the Existing Macro ..................................23
Hands-On 1.14. Adding Visual Basic Statements to the Recorded Macro Code ..........24

Various Methods of Running Macros .............................................................. 24
Running the Macro Using a Keyboard Shortcut ........................... 25
Hands-On 1.15. Assigning a Macro to a Keyboard Shortcut.....................25

Running the Macro from the Quick Access Toolbar .................... 26

Hands-On 1.16. Running a Macro from the Quick Access Toolbar...........26

Running the Macro from a Worksheet Button ............................. 28
Hands-On 1.17. Running a Macro from a Button Placed on a Worksheet ....28

Summary........................................................................................................... 30

2. Getting to Know Visual Basic Editor (VBE) ....................... 31
Understanding the Project Explorer Window ................................................ 31
Understanding the Properties Window........................................................... 33
Understanding the Code Window ................................................................... 33
Setting the VBE Options ................................................................................. 34
Syntax and Programming Assistance ............................................................... 35
List Properties/Methods ......................................................................... 36
List Constants .......................................................................................... 36
Parameter Info ........................................................................................ 37
Quick Info................................................................................................ 38
Complete Word ....................................................................................... 38
Indent/Outdent ....................................................................................... 39
Hands-On 2.1. Indenting/Outdenting Visual Basic Code ...................................39

Comment Block/Uncomment Block ...................................................... 39
Using the Object Browser................................................................................ 40
Hands-On 2.2. Writing a VBA Procedure to Move a Text Box on the Worksheet ........42
Hands-On 2.3. Writing a VBA Procedure to Move a Circle on the Worksheet ............44

Locating Procedures with the Object Browser ...................................... 45
Hands-On 2.4. Using Object Browser to Locate VBA Procedures ......................45

Using the VBA Object Library ........................................................................ 46

Hands-On 2.5. Writing a VBA Procedure to Create a Folder in Windows ..................46

Using the Immediate Window......................................................................... 47
Hands-On 2.6. Entering and Executing VBA Statements in
the Immediate Window ...............................................................................................48

Obtaining Information in the Immediate Window................................ 50
Hands-On 2.7. Obtaining Information in the Immediate Window.....................50


Contents • ix

Working with Worksheet Cells and Ranges .................................................... 51
Using the Range Property ...................................................................... 52
Hands-On 2.8. Practice Using the Range Property to Select Worksheet Cells ...52

Using the Cells Property ......................................................................... 52
Hands-On 2.9. Practice Using the Cells Property to
Select Worksheet Cells (Part I) .........................................................................52
Hands-On 2.10. Practice Using the Cells Property to Select Worksheet Cells
(Part II)..............................................................................................................53

Using the Offset Property ....................................................................... 53
Hands-On 2.11. Selecting Cells Using the Offset Property .................................54

Using the Resize Property ...................................................................... 54
Hands-On 2.12. Writing a VBA Statement to Resize a Selection of Cells ...........54

Using the End Property .......................................................................... 56
Hands-On 2.13. Selecting Cells Using the End Property ....................................56


Moving, Copying, and Deleting Cells .................................................... 56
Hands-On 2.14. Moving, Copying, and Deleting Cells .......................................56

Working with Rows and Columns ................................................................... 57
Hands-On 2.15. Selecting Entire Rows and Columns ...................................................57

Obtaining Information about the Worksheet......................................... 58
Hands-On 2.16. Counting Rows and Columns ....................................................58

Entering Data and Formatting Cells............................................................... 58
Hands-On 2.17. Using VBA Statements to Enter Data in a Worksheet ........................58

Returning Information Entered in a Worksheet ................................... 58
Finding Out about Cell Formatting ....................................................... 59
Working with Workbooks and Worksheets ..................................................... 60
Hands-On 2.18. Working with Workbooks ....................................................................60
Hands-On 2.19. Working with Worksheets ....................................................................61

Working with Windows .................................................................................... 61
Hands-On 2.20. Working with Windows .......................................................................62

Working with the Excel Application ................................................................ 62
Hands-On 2.21. Working with the Excel Application....................................................63

Summary........................................................................................................... 63

3. Excel VBA Fundamentals .................................................... 65
Excel Objects, Properties, and Methods ......................................................... 65
Microsoft Excel Object Model ........................................................................ 67

Writing Simple and Complex VBA Statements .............................................. 68
Breaking Up Long VBA Statements ...................................................... 71
Saving Results of VBA Statements .................................................................. 72
Introducing Data Types ................................................................................... 72
Using Variables ................................................................................................. 75
How to Create Variables ......................................................................... 76
How to Declare Variables ....................................................................... 76
Specifying the Data Type of a Variable .................................................. 79
Assigning Values to Variables .................................................................. 81
Hands-On 3.1. Writing a VBA Procedure with Variables ...................................81


x • Microsoft Excel Programming Pocket Primer
Forcing Declaration of Variables ............................................................ 85
Hands-On 3.2. Writing a VBA Procedure with Explicitly Declared Variables...85

Understanding the Scope of Variables ................................................... 86
Procedure-Level (Local) Variables ................................................ 87
Module-Level Variables ................................................................. 87
Hands-On 3.3. Writing a VBA Procedure with a
Module-Level Variable ............................................................................87

Project-Level Variables .................................................................. 89
Lifetime of Variables ............................................................................... 89
Finding a Variable Definition ................................................................. 89
Determining a Data Type of a Variable.................................................. 89
Hands-On 3.4. Using the Built-In VarType Function ..........................................90

Using Constants ............................................................................................... 91
Built-In Constants ................................................................................... 91

Hands-On 3.5. Viewing Excel Constants in the Object Browser.........................92

Converting between Data Types ..................................................................... 93
Hands-On 3.6. Using Data Type Conversion Functions in VBA...................................96

Using Static Variables in VBA Procedures ...................................................... 96
Hands-On 3.7. Writing a VBA Procedure with a Static Variable .................................96

Using Object Variables in VBA Procedures ................................................... 97
Hands-On 3.8. Writing a VBA Procedure with Object Variables .................................98

Using Specific Object Variables.............................................................. 99
Summary......................................................................................................... 100

4. Excel VBA Functions .........................................................101
Understanding Function Procedures ............................................................ 101
Creating a Function Procedure ............................................................ 102
Hands-On 4.1. Writing a Simple Function Procedure.......................................102

Various Methods of Running Function Procedures ..................................... 104
Running a Function Procedure from a Worksheet ............................. 104
Hands-On 4.2. Executing a Function Procedure from within an
Excel Worksheet ..............................................................................................104

Running a Function Procedure from Another VBA Procedure ......... 105
Hands-On 4.3. Executing a Function from a VBA Procedure ...........................106

Ensuring Availability of Your Custom Functions.......................................... 106
Passing Arguments to Function Procedures ................................................. 107
Hands-On 4.4. Passing Arguments to Functions (Example 1).....................................107

Hands-On 4.5. Passing Arguments to Functions (Example 2).....................................108

Specifying Argument Types .................................................................. 109
Hands-On 4.6. Passing Arguments to Functions (Example 3) ..........................109

Passing Arguments by Reference and Value ........................................ 110
Hands-On 4.7. Passing Arguments to Functions (Example 4) ..........................110

Using Optional Arguments ................................................................... 112
Hands-On 4.8. Writing Functions with Optional Arguments ...........................112

Testing a Function Procedure ....................................................................... 113


Contents • xi

Locating Built-In Functions .......................................................................... 114
Getting to Know the MsgBox Function ........................................................ 114
Hands-On 4.9. Formatting Text for Display in the MsgBox Function ........................115
Hands-On 4.10. Using the MsgBox Function with Arguments (Example 1) ..............119
Hands-On 4.11. Using the MsgBox Function with Arguments (Example 2) ..............120

Returning Values from the MsgBox Function ..................................... 121
Hands-On 4.12. Using the MsgBox Function with Arguments (Example 3) ....122

Getting to Know the InputBox Function ...................................................... 123
Hands-On 4.13. Using the InputBox Function (Example 1) .......................................123

Determining and Converting Data Types ............................................ 125
Hands-On 4.14. Using the InputBox Function (Example 2) .............................125


Using the InputBox Method .......................................................................... 127
Hands-On 4.15. Using the Excel InputBox Method .....................................................128

Summary......................................................................................................... 131

5. Adding Decisions to Your Excel VBA Programs ...............133
Relational and Logical Operators ..................................................................133
Using If...Then Statement .............................................................................134
Hands-On 5.1. Evaluating Conditions in the Immediate Window ............................ 135
Hands-On 5.2. Writing a VBA Procedure with a Simple If…Then Statement .......... 135

Using If...Then...Else Statement ...................................................................138
Hands-On 5.3. Writing a VBA Procedure with an If…Then…Else Statement ......... 139

Using If...Then...ElseIf Statement ................................................................140
Hands-On 5.4. Writing a VBA Procedure with an If…Then…ElseIf Statement ...... 140

Nested If…Then Statements.........................................................................141
Using the Select Case Statement ..................................................................142
Hands-On 5.5. Writing a VBA Procedure with a Select Case Statement................... 143

Using Is with the Case Clause ..............................................................145
Specifying a Range of Values in a Case Clause ....................................145
Specifying Multiple Expressions in a Case Clause ..............................146
Writing a VBA Procedure with Multiple Conditions....................................146
Hands-On 5.6. Writing a VBA Procedure with Multiple Conditions ........................ 147

Using Conditional Logic in Function Procedures ........................................148
Hands-On 5.7. Writing a Function Procedure with a Select Case Statement............ 149


Summary.........................................................................................................149

6. Adding Repeating Actions to Your VBA Programs...........151
Introducing Looping Statements...................................................................151
Understanding Do...While and Do...Until Loops.........................................151
Hands-On 6.1. Writing a VBA Procedure with a Do…While Statement .................. 152
Hands-On 6.2. Writing a VBA Procedure with a Do…Until Statement .................... 154

Avoiding Infinite Loops .................................................................................155
Executing a Procedure Line by Line ............................................................156
Hands-On 6.3. Executing a Procedure Line by Line .................................................. 156

Understanding While...Wend Loop ..............................................................157


xii • Microsoft Excel Programming Pocket Primer
Hands-On 6.4. Writing a VBA Procedure with a While…Wend Statement .............. 157

Understanding For...Next Loop ....................................................................158
Hands-On 6.5. Writing a VBA Procedure with a For…Next Statement.................... 159

Understanding For...Each...Next Loop .........................................................160
Hands-On 6.6. Writing a VBA Procedure with a For Each… Next Statement ......... 161

Exiting Loops Early........................................................................................ 161
Hands-On 6.7. Writing a VBA Procedure with an Early Exit from a
For Each…Next Statement .........................................................................162

Using a Do…While Statement ......................................................................162

Hands-On 6.8. Writing a VBA Procedure with a Do…While Statement ....162
Using Loops and Conditionals .......................................................................163
Hands-On 6.9. Writing a VBA Procedure with Loops and Conditionals .................. 163

Summary.........................................................................................................164

7. Keeping Track of Multiple Values Using Arrays ..............165
Understanding Arrays ....................................................................................165
Declaring Arrays ...................................................................................167
Array Upper and Lower Bounds ..........................................................169
Initializing and Filling an Array ............................................................169
Filling an Array Using Individual Assignment Statements .........169
Filling an Array Using the Array Function ..................................170
Filling an Array Using For…Next Loop......................................170
Using a One-Dimensional Array ...................................................................171
Hands-On 7.1. Using a One-Dimensional Array ........................................................ 171

Using a Two-Dimensional Array....................................................................172
Hands-On 7.2. Storing Data in a Two-Dimensional Array ........................................ 172

Using a Dynamic Array ..................................................................................173
Hands-On 7.3. Loading Worksheet Data into an Array ............................................. 174

Using Array Functions ...................................................................................175
The Array Function...............................................................................175
Hands-On 7.4. Using the Array Function ......................................................... 175

The IsArray Function............................................................................176
Hands-On 7.5. Using the IsArray Function ...................................................... 176


The Erase Function ..............................................................................176
Hands-On 7.6. Using the Erase Function ......................................................... 177

The LBound and UBound Functions ..................................................177
Hands-On 7.7. Using the LBound and UBound Functions .............................. 177

Troubleshooting Errors in Arrays ..................................................................178
Using the ParamArray Keyword ....................................................................179
Hands-On 7.8. Passing an Array to Procedures Using the
ParamArray Keyword .............................................................................................. 180

Data Entry with an Array ...............................................................................180
Hands-On 7.9. Using the Array Function to Enter Headings in a Worksheet........... 180

Sorting an Array with Excel ...........................................................................181


Contents • xiii
Hands-On 7.10. Using Excel to Sort a VBA Array ..................................................... 181

Summary.........................................................................................................183

8. Keeping Track of Multiple Values Using
Object Collections .............................................................185
Working with Collections of Objects .............................................................186
Declaring and Using a Custom Collection...........................................187
Adding Objects to a Custom Collection ...............................................187
Hands-On 8.1. Using a Custom Collection Object............................................ 188

Removing Objects from a Custom Collection .....................................189

Hands-On 8.2. Removing Items from a Custom Collection ............................. 190

Creating and Using Custom Objects .............................................................192
Lab 8.1a. Creating a Class Module ................................................................... 194

Variable Declarations ............................................................................194
Lab 8.1b. Declaring Members of the CAsset Class ........................................... 194

Defining the Properties for the Class...................................................194
Writing Property Procedures ................................................................195
Lab 8.1c. Writing Property Procedures for the CAsset Class........................... 196

Writing Class Methods..........................................................................197
Lab 8.1d. Writing a Method for the CAsset Class ...............................198
Creating an Instance of a Class ............................................................198
Lab 8.1e. Writing Code .........................................................................199
Summary.........................................................................................................205

9. Getting to Know Built-In Tools for Testing
and Debugging ..................................................................207
Testing VBA Procedures ................................................................................207
Stopping a Procedure.....................................................................................208
Using Breakpoints ..........................................................................................209
Hands-On 9.1. Setting Breakpoints in a VBA Procedure ........................................... 209

When to Use a Breakpoint....................................................................213
Using the Immediate Window in Break Mode .............................................213
Using the Stop and Assert Statements ..........................................................214
Using the Watch Window ..............................................................................216
Hands-On 9.2. Watching the Values of VBA Expressions .......................................... 217


Removing Watch Expressions ..............................................................219
Using Quick Watch ........................................................................................219
Hands-On 9.3. Using the Quick Watch Dialog Box .................................................... 220

Using the Locals Windows and the Call Stack Dialog Box ..........................220
Hands-On 9.4. Using the Locals and Call Stack Windows......................................... 221

Navigating with Bookmarks ...........................................................................222
Trapping Errors ..............................................................................................223
Using the Err Object ............................................................................224
Hands-On 9.5. Writing a VBA Procedure with Error-Handling Code ............ 225

Setting Error Trapping Options in Your VBA Project .........................227


xiv • Microsoft Excel Programming Pocket Primer
Stepping through VBA Procedures ...............................................................228
Hands-On 9.6. Stepping through a VBA Procedure ................................................... 229

Stepping Over a Procedure and Running to Cursor ........................... 229
Hands-On 9.7. Stepping over a Procedure.........................................................230

Setting the Next Statement .................................................................. 231
Showing the Next Statement ................................................................ 231
Stopping and Resetting VBA Procedures ............................................ 231
Summary......................................................................................................... 232

Index ...................................................................................... 233



ACKNOWLEDGMENTS

A

s years pass and we gain more and more knowledge on a particular
subject there is a tendency to publish books for people who want to
know it all. But the truth is that we really don’t have time to read
all the printed pages. I thank my publisher, David Pallai, for suggesting that
I consider creating a smaller book that will serve as a starting point for anyone
attempting to get into VBA programming in Excel. I hope that you as a reader
of this primer book will appreciate this short book and the knowledge gained
from its pages will not only allow you to continue your programming journey
but also take you places you never thought possible.
I’m also thankful to Jennifer Blaney for her expert management of this
book project. I owe a heartfelt thanks to my copyeditor at Educator’s International Press for the thorough review of the manuscript. I am grateful to the
compositor, Tutis Innovative Solutions PTE LTD, for all the typesetting efforts
that gave this book the easy to follow look and feel.
A special thank you goes to the Long Island Railroad for providing me with
a seat on the train so I could use my laptop to write while commuting to my
day job.
Julitta Korol
Brooklyn, New York
April, 2015



INTRODUCTION

B


ack in the ‘90s, I wrote my first book on Excel macro programming. It
was short and sweet. It contained the exact steps you needed to follow
to automate various aspects of your Excel spreadsheets. If you worked
with Excel this book instantly made you an Office hero and gave you skills for
advancement. Over two decades have passed and Excel continues to be the
world’s number 1 spreadsheet. It is my strong belief that if you invest your time
in Excel it will pay over and over again for many more years to come. But, wait,
you’ve got to progress beyond the tools provided by the built-in user interface.
Forget the menus. Do your own thing. Automating Excel is something everyone
can do. With the right training, that is. This book’s purpose is to introduce you
to Excel built-in language, known as Visual Basic for Applications (VBA). With
VBA you can begin delegating repetitive tasks to Excel while freeing your time
for projects that are more fun to do. Besides, knowing how to program these
days is a lucrative skill. It will get you a well-paying and secure job.
This book is short and hopefully sweet as well. It was designed for someone like you who needs to master Excel programming fundamentals without
spending too much time. Most of the time all you need is a short book to
get you started. It’s less overwhelming to deal with a new subject in smaller
chunks. The VBA Programming Pocket Primer series will show you only the
things you need to know to feel at home with VBA. What you learn in this
book on Excel programming will apply to, say, Access programming. Just see
my other book, the Microsoft Access Programming Pocket Primer, to see what
I mean. How’s that for knowledge transfer? Learn in Excel, use it in Access or
another Microsoft Office application. I call this sweet learning.
If you are looking for in-depth knowledge of Excel programming (and have
time to read through a 1,000 page book), then go ahead and try some of my
thicker books. See Chapter 1 for details.


xviii • Microsoft Excel Programming Pocket Primer

Excel is about doing and so is this book. So do not try to read it while not
at the computer. You can sit, stand, or lie down; it does not matter. But you
do need to work with this book. Do the examples, read the comments. Do
this until it becomes easy to do without the step-by-step instructions. Do not
skip anything as the concepts in later chapters build on material introduced
earlier.

CHAPTER OVERVIEW
Before you get started, allow me to give you a short overview of
the things you’ll be learning as you progress through this primer book.
Mi crosoft Excel Programming Pocket Primer is divided into nine chapters
that progressively introduce you to programming Microsoft Excel using
2013/2010 or 365 versions.
Chapter 1 — Getting Started with Excel VBA
In this chapter you learn how you can introduce automation into your
Ex cel worksheets by simply using the built-in macro recorder. You learn
about different phases of macro design and execution. You also learn about
macro security.
Chapter 2 — Getting to Know Visual Basic Editor
In this chapter you learn almost everything you need to know about work ing
with the Visual Basic Editor window, commonly referred to as VBE. Some of
the programming tools that are not covered here are discussed and put to use
in Chapter 9.
Chapter 3 — Excel VBA Fundamentals
In this chapter you are introduced to the basic VBA concepts such as the
Microsoft Excel object model and its objects, properties, and methods. You
also learn concepts that allow you to store various pieces of information for
later use.
Chapter 4 — Excel VBA Functions
In this chapter you learn how to write and execute function procedures.

You also learn how to provide additional information to your procedures
before they are run. You are introduced to working with some useful built-in
functions and methods that allow you to interact with your VBA procedure
users.
Chapter 5 — Adding Decisions to Your Excel VBA Programs
In this chapter you learn how to control your program flow with a number
of different decision-making statements.


Introduction • xix

Chapter 6 — Adding Repeating Actions to Your Excel VBA Programs
In this chapter you learn how you can repeat certain groups of statements
using procedure loops.
Chapter 7 — Keeping Track of Multiple Values Using Arrays
In this chapter you learn the concept of static and dynamic arrays, which you
can use for holding various values. You also learn about built-in array functions.
Chapter 8 — Keeping Track of Multiple Values Using Object Collections
In this chapter you learn how to create and use your own VBA objects and
collections of objects.
Chapter 9 —Getting to Known Built-In Tools for Testing and Debugging
In this chapter you begin using built-in debugging tools to test your
programming code and trap errors.
The above nine chapters will give you the fundamental techniques and
concepts you will need in order to continue your Excel VBA learning path.

THE COMPANION FILES
The example files for all the hands-on activities in this book are available on
the CD-ROM included with this book. Replacement files may be downloaded
by contacting the publisher at Digital versions of this

title are available at authorcloudware.com and other digital vendors.



CHAPTER

1

GETTING STARTED WITH
EXCEL VBA

V

isual Basic for Applications (VBA) is the programming language built
into all Microsoft® Office® applications, including Microsoft Excel®.
By learning some basic VBA commands and constructs, you can start
automating many of the mundane routine tasks that you perform in Excel.
In this chapter, you acquire the fundamentals of VBA by recording macros
and examining and editing the VBA code behind the macro using the Visual
Basic Editor.

INTRODUCTION
This book’s main focus is to introduce you to programming in the 2013 /
2010 and 365 versions of Excel. If you are interested in a complete course of
Excel VBA programming, check out my other programming books available
from Mercury Learning and Information:
 Microsoft Excel 2013 Programming by Example with VBA, XML, and ASP
 Microsoft Excel 2010 Programming by Example with VBA, XML, and ASP
This book assumes that you are ready to build intelligence into your
Microsoft Excel spreadsheets. This first chapter walks you through the process

of speeding up worksheet tasks with macros. You learn what macros are, how
and when to use them, and how to write and modify them. Creating macros
requires nothing more than what you already have—a basic knowledge of
Microsoft Office Excel commands and worksheet concepts. Ready? Let’s get
started.


2 • Microsoft Excel Programming Pocket Primer

MACROS AND VBA
Macros are programs that store a series of commands. When you create a
macro, you simply combine a sequence of keystrokes into a single command
that you can later “play back.” Because macros can reduce the number of
steps required to complete tasks, using macros can significantly decrease
the time you spend creating, formatting, modifying, and printing your
Excel worksheets. You can create macros by using Microsoft Excel’s built-in
recording tool (Macro Recorder), or you can write them from scratch using
Visual Basic Editor, a special development environment built into Excel. You
can combine recorded macros with your own programming code to create
unique VBA applications that meet your everyday needs. Whether you write
or record your programming code in Excel, you’ll be utilizing the powerful
programming language—Visual Basic for Applications—commonly known
as VBA.
Microsoft Excel comes with dozens of built-in, timesaving features that
allow you to work faster and smarter. Before you decide to automate a worksheet task with a recorded macro or programming code written from scratch,
make sure there is not already a built-in feature that you can use to perform
that task. Consider writing your own VBA code or recording a macro when
you find yourself performing the same series of actions over and over again or
when Excel does not provide a built-in tool to do the job.
Just by learning how to handle Excel’s macro recorder and use basic VBA

statements and constructs to enhance your macros, you’ll be able to automate
any part of your worksheet. For example, you can automate data entry by
recording a macro that enters headings in a worksheet or replaces column
titles with new labels. Adding a little bit of conditional logic to your VBA
code will allow you to automatically check for duplicate entries in a specified
range of your worksheet. With a macro, you can quickly apply formatting to
several worksheets, as well as combine different formats, such as fonts, colors,
borders, and shading. Macros will save you keystrokes when it comes to setting
print areas, margins, headers, and footers, and selecting special options for
printouts.

Excel Macro-Enabled File Formats
When a workbook contains programming code, it should be saved in one of
the following macro-enabled file formats:
 Excel Macro-Enabled Workbook (.xlsm)
 Excel Binary Workbook (.xlsb)
 Excel Macro-Enabled Template (.xltm)


Getting Started with Excel VBA • 3

If you attempt to save the workbook in a file format that is incompatible
with the type of content it includes, Excel will warn you with a message as
shown in Figure 1.1.

FIGURE 1.1. When a workbook contains programming code, Microsoft Excel displays this
message if you attempt to save it as a regular .XLSX workbook file.

Macro Security Settings
Because macros can contain malicious code designed to put a virus on a user’s

computer, it is important to understand different security settings that are available in Excel. It is also critical that you run up-to-date antivirus software on your
computer. Antivirus software installed on your computer will scan the workbook
file you are attempting to open if the file contains macros. The default macro
security setting is to disable all macros with notification, as shown in Figure 1.2.

FIGURE 1.2. The Macro Settings options in the Trust Center allow you to control how Excel
should deal with macros whenever they are present in an open workbook. To open Trust
Center’s Macro Settings, choose File | Options | Trust Center | Trust Center Settings and
click the Macro Settings link.


4 • Microsoft Excel Programming Pocket Primer
If macros are present in a workbook you are trying to open, you will receive
a security warning message just under the Ribbon, as shown in Figure 1.3.

FIGURE 1.3. Upon opening a workbook with macros, Excel brings up a security
warning message.

To use the disabled components, you should click the Enable Content button
on the message bar. This will add the workbook to the Trusted Documents list
in your registry. The next time you open this workbook you will not be alerted to
macros. If you need more information before enabling content, you can click the
message text displayed in the security message bar to activate the Backstage View
where you will find an explanation of the active content that has been disabled, as
shown in Figure 1.4. Clicking on the Enable Content button in the Backstage View
will reveal two options:
 Enable All Content
This option provides the same functionality as the Enable Content button
in the security message bar. This will enable all the content and make it a
trusted document.

 Advanced Options
This option brings up the Microsoft Office Security Options dialog shown
in Figure 1.5. This dialog provides options for enabling content for the
current session only.

FIGURE 1.4. The Backstage View in Excel 2013.


×