You are on page 1of 224

EXCEL

POWER PROGRAMMING
WITH
VBA & MACROS

CARTY BINN
Copyright © 2022 CARTY BINN
All Rights Reserved
This book or parts thereof may not be reproduced in any form, stored in any
retrieval system, or transmitted in any form by any means—electronic, mechanical,
photocopy, recording, or otherwise—without prior written permission of the
publisher, except as provided by United States of America copyright law and fair
use.
Disclaimer and Terms of Use
The author and publisher of this book and the accompanying materials have used
their best efforts in preparing this book. The author and publisher make no
representation or warranties with respect to the accuracy, applicability, fitness, or
completeness of the contents of this book. The information contained in this book is
strictly for informational purposes. Therefore, if you wish to apply the ideas
contained in this book, you are taking full responsibility for your actions.
Printed in the United States of America
CONTENTS
CONTENTS
PART ONE
STARTING EXCEL VBA PROGRAMMING
CHAPTER ONE
GETTING TO KNOW VBA
WHAT IS VBA?
KNOWING WHAT VBA CAN DO
Inserting A Bunch of Text
Automating a task, you perform frequently
Automating repetitive operations
Making your own command
Creating a custom button
Developing new worksheet functions
Creating custom add-ins for Excel
Creating complete, macro-driven applications
ADVANTAGES OF VBA
Understanding what VBA excels at
Understanding the disadvantages of using VBA
CHAPTER TWO
BUILDING SIMPLE MACROS
DISPLAYING THE DEVELOPERS TAB
CREATING A MACRO
Preparing the Environment
Recording the Macro
Running the Macro
Viewing a Macro in the Visual Basic Editor
Modifying the Macro
Saving Workbooks that Contain Macros
Understanding Macro Security
Revealing More about the NameAndTime Macro
PART TWO
EMPLOYING VBA WITH EXCEL
CHAPTER THREE
WORKING IN THE VISUAL BASIC EDITOR
Getting to Know the Visual Basic Editor
Activating the VBE
Exploring VBE components
The menu bars
Toolbar
Project window
Code window
Immediate window
IN THE VISUAL BASIC EDITOR, WHAT'S NEW?
Working with the project explorer
Adding a new VBA Module
Removing a VBA module
Exporting and importing objects
Working with a Code Pane
Window minimization and maximization
Looking at the parts of a module
Getting VBA code into a module
Directly entering a code
Using the Macro recorder
Copying VBA Code
Customizing the VBE
Using the Editor tab
Auto Syntax Check option
Require Variable Declaration option
Explicit Option
Auto List Members option
Auto Quick Info option
Auto Data Tips option
Setting the Auto Indent
Text Editing using Drag-and-Drop
Default to Full Module View option
Procedure Separator option
Using the Editor Format tab
Code Colors option
Font option
Size setting
Margin Indicator Bar option
Using the General Tab
Using the Docking tab
CHAPTER FOUR
INTRODUCING THE EXCEL OBJECT MODEL
IS EXCEL AN OBJECT?
Understanding the Hierarchy of Objects
Wrapping Your Mind around Collections
Referring to Objects
Getting around the hierarchy
Setting object references
Diving into Object Properties and Methods
Setting objects properties
Taking action with object methods
Triggering actions with objects events
Getting additional information from VBA resources
Using the Help System in VBA
Using the Object Browser
Automatically listing properties and methods
CHAPTER FIVE
VBA SUB AND FUNCTIONS PROCEDURES
UNDERSTANDING SUBS VERSUS FUNCTIONS
Examining Sub-Procedures
Looking at Function procedures
Naming Subs and Functions
Executing Sub procedures
Directly executing the Sub procedure
Executing the procedure from the Macro dialog box
Executing a macro using a shortcut key
Executing the procedure from a button or shape
Executing the procedure from another procedure
Executing Function procedures
Calling the function from a Sub procedure
Calling a function from a worksheet formula
CHAPTER SIX
USING THE EXCEL MACRO RECORDER
RECORDING BASICS
Getting Ready to Record
Choosing Between Absolute and Relative Modes
Absolute recording mode
Recording in relative mode
What Gets Recorded?
Specifying recording options for your Macro
Macro name
Shortcut key
Store Macro In option
Description
Streamlining Macro Recorder-Generated Code
PART THREE
PROGRAMMING CONCEPT
CHAPTER SEVEN
ESSENTIAL VBA LANGUAGE ELEMENTS
Making Use of Comments in VBA Code
Using Variables, Constants, and Data Types
What are VBA’s data types?
Declaring and scoping variables
Procedure-only variables
Module-only variables
Public variables
Static variables
Life of variables
Working with constants
Using Premade Constants
Working with strings
Working with dates
Using Assignment Statements
Examples of assignment statements
About that equal sign
Smooth operators
WORKING WITH ARRAYS
Array declarations
Multidimensional arrays
Dynamic arrays
Making Use of Labels
CHAPTER EIGHT
WORKING WITH RANGE OBJECTS
REFERRING TO RANGE OBJECTS
Referring to a Range Using Properties
The Cells property
The Offset property
Working with Range Properties
The Value property
The Text property
The Font property
The Interior property
The Formula property
The Number Format property
USING RANGE OBJECT METHODS TO TAKE ACTION
The Select method
The Copy and Paste methods
The Clear method
The Delete method
CHAPTER NINE
USING VBA AND WORKSHEET FUNCTIONS
Understanding Functions
Using VBA's Built-In Functions
Examples of VBA functions
VBA functions that do more than return a value
Using Worksheet Functions in VBA
Worksheet Functions Examples
Determining the highest value in a range
Entering worksheet functions
More about using worksheet functions
Using Custom Functions
CHAPTER TEN
CONTROLLING PROGRAM FLOW AND MAKING DECISIONS
Going with the Flow, Dude
The GoTo Statement
WHAT IS STRUCTURED PROGRAMMING? DOES IT MATTER?
Decisions, Decisions
An If-Then-Else example
Using ElseIf
Another If-Then example
THE SELECT CASE STRUCTURE
An example of a Select Case
A nested Select Case example
Knocking Your Code for a Loop
CHAPTER ELEVEN
AUTOMATIC PROCEDURES AND EVENTS
PREPARING FOR THE BIG EVENT
Are events useful?
Programming event-handler procedures
Where Does the VBA Code Go?
Writing an Event-Handler Procedure
Triggering Workbook Events
The Open event for a workbook
The BeforeClose event for a workbook
The BeforeSave event for a workbook
Using Activation Events
Activate and Deactivate events in a sheet
Activating and deactivating events in a workbook
Workbook activation events
Other Worksheet-Related Events
Why not using data validation?
Preventing data validation from being destroyed
Events Not Associated with Objects
The OnTime event
Keypress events
CHAPTER TWELVE
ERROR HANDLING TECHNIQUES
TYPES OF ERRORS
An Erroneous Macro Example
Not quite perfect macros
Perfecting the Macro
Giving up on perfection
Handling Errors Another Way
Error handling in a nutshell
Knowing when to ignore errors
Identifying specific errors
An Intentional Error
CHAPTER THIRTEEN
BUG EXTERMINATION TECHNIQUES
Species of Bugs
Detecting Bugs
Debugging Techniques
Reviewing your code
Using the MsgBox function.
Using the VBA debugger
Using the debugger’s tools
Setting breakpoints in your code
Stop
Stepping through your code
Using the Watch window
Using the Locals window
Tips for Bug Reduction
CHAPTER FOURTEEN
VBA PROGRAMMING EXAMPLES
Working with Ranges
Copying a range
Copying a variable-size range
Selecting the end of a row or column
Selecting a row or column
Moving a range
Looping through a range efficiently
On Error Resume Next
Looping through a range efficiently (Part II)
Prompting for a cell value
Identifying multiple selections
Changing Excel Preferences
Changing Boolean settings
Changing non-Boolean settings
Working with Charts
AddChart versus AddChart2
Modifying the chart type
Looping through the Chart Objects collection
Modifying chart properties
Applying chart formatting
VBA Quick Tips
Turning off screen updating
Disabling automatic calculation
Eliminating those pesky alert messages
Simplifying object references
Declaring variable types
PART FOUR
COMMUNICATING WITH YOUR USERS
CHAPTER FIFTEEN
SIMPLE DIALOG BOXES
Interacting with User In VBA
The MsgBox Function
Displaying Messages with the MsgBox Function
Customizing message boxes
Getting Data with an Input Box syntax
Using the Input Box function
Constructing a GetOpenFilename Statement
The syntax for the GetOpenFilename method
An example of GetOpenFilename
Displaying Excel’s Built-in Dialog Boxes
CHAPTER SIXTEEN
USERFORM BASICS
Knowing When to Use a UserForm
Working with UserForms
Inserting a new UserForm
Adding controls to a UserForm
Changing properties for a UserForm control
Viewing the UserForm Code window
Displaying a UserForm
Using information from a UserForm
A UserForm Example
Adding the CommandButtons
Adding the Option Buttons
Adding event-handler procedures
Creating a macro to display the dialog box
Making the macro available
Testing the macro
CHAPTER SEVENTEEN
USING USERFORM CONTROLS
GETTING STARTED WITH DIALOG BOX CONTROLS
Adding controls
Introducing control properties
Dialog Box Controls: The Details
CheckBox control
ComboBox control
CommandButton control
Frame control
Image control
ListBox control
MultiPage control
OptionButton control
ScrollBar control
SpinButton control
TabStrip control
TextBox control
ToggleButton control
Working with Dialog Box Controls
Moving and resizing controls
Aligning and spacing controls
Accommodating keyboard users
Changing the tab order
Setting hotkeys
Aesthetics of Dialog Boxes
CHAPTER EIGHTEEN
USERFORM TECHNIQUES AND TRICKS
Using Dialog Boxes
A UserForm Example
Creating the dialog box
Making the macro available
Trying out your dialog box
Adding event-handler procedures
Validating the data
Now the dialog box works
More UserForm Examples
A ListBox example
Filling a ListBox
Determining the selected item
Determining multiple selections
Choosing a range
Using a TextBox and a SpinButton
How this example works
Creating a modeless tabbed dialog box
Displaying a chart in a UserForm
A Dialog Box Checklist
CHAPTER NINETEEN
ACCESSING YOUR MACROS THROUGH THE USER INTERFACE
CUSTOMIZING THE RIBBON
MANUALLY CUSTOMIZING THE RIBBON
Tabs
Groups
Adding a macro to the Ribbon
Using XML to customize the Ribbon
Adding a new item to the Cell shortcut menu
PART FIVE
PUTTING IT ALL TOGETHER
CHAPTER TWENTY
CREATING WORKSHEET FUNCTIONS
Make Custom Functions to Make Your Work Easier
What Custom Worksheet Functions Can't Do?
WORKING WITH FUNCTION EXAMPLES
A function with one argument
A function with two arguments
A function with a range argument
A function with an optional argument
Introducing Wrapper Functions
The ExtractElement function
The SayIt function
The IsLike function
Working with Functions That Return an Array
Returning a sorted list
Using the Insert Function Dialog Box
Displaying the function’s description
Adding argument descriptions
CHAPTER TWENTY-ONE
CREATING EXCEL ADD-INS
Add-Ins Defined
Reasons to Create Add-Ins
Working with Add-Ins
Understanding the Basics of Add-Ins
Looking at an Add-In Example
Setting up the workbook
Testing the workbook
Protecting the VBA code
Creating the add-in
Opening the add-in
Distributing the add-in
Modifying the add-in
PART SIX
OTHER EXCEL PROGRAMMING ETHICS WORTH KNOWING
CHAPTER TWENTY-TWO
TEN HANDY VISUAL BASIC EDITORS TIPS
Applying Block Comments
Copying Multiple Lines of Code at Once
Jumping between Modules and Procedures
Teleporting to Your Functions
Staying in the Right Procedure
Stepping Through Your Code
Stepping to a Specific Line in Your Code
Stopping Your Code at a Predefined Point
Seeing the Beginning and End of Variable Values
Turning Off Auto Syntax Check
CHAPTER TWENTY-THREE
RESOURCES FOR VBA HELP
Allowing Excel to Generate Code for You
Pilfering Code from the Internet
Leveraging User Forums
Visiting Expert Blogs
Mining YouTube for Video Training
Attending Live and Online Training Classes
Learning from the Microsoft Office Dev Center
Dissecting the Other Excel Files in Your Organization
Asking Your Local Excel Guru
CHAPTER TWENTY-FOUR
TEN VBA DO’S AND DON’TS
Declaring All Variables
Don’t Confuse Passwords with Security
Do Clean Up Your Code
Don’t Put Everything in One Procedure
Do Consider Other Software
Don’t Assume That Everyone Enables Macros
Do Get in the Habit of Experimenting
Don’t Assume That Your Code Will Work with Other Excel Versions
Do Keep Your Users in Mind
Don’t Forget About Backups
INDEX

PART ONE
STARTING EXCEL VBA PROGRAMMING
CHAPTER ONE
GETTING TO KNOW VBA
Grasp your horses if you're keen to get into VBA programming. There isn't a single piece of
practical training material in this chapter. It does, nevertheless, offer some important
supplemental materials that will help you learn how to program in Excel. In essence, this chapter
sets the tone for the rest of the book and provides you with a sense of how Excel programming
fits into the bigger picture.
What is VBA?
VBA stands for Visual Basic for Applications. Visual Basic for Applications (VBA) is a
programming language created by Microsoft, the business that attempts to get you to purchase a
new version of Windows every few years. Excel, like the rest of Microsoft Office, comes with
the VBA programming language. In a nutshell, VBA is the tool that individuals like you and me
use to create Excel-controlling applications.
Consider a sophisticated robot who is well-versed in Excel. This robot can understand
instructions and use Excel with great speed and accuracy. In Excel, you create a set of robot
commands using specific codes whenever you want the robot to perform anything. Then you sit
back and have a glass of water as the robot follows your orders. That's essentially what VBA is –
a coding language for robots. Excel, on the other hand, does not include a robot or lemonade.
The vocabulary used in Excel programming may be a little befuddling. VBA, for example, is a
programming language that can also be used to create macros. What do you name something that
was written in VBA and ran in Excel? Is this a program or a macro? VBA processes are often
referred to as macros in Excel's Help system, therefore I use that nomenclature. But I also refer
to this as a program.
All through this book, I use the word automate. This word refers to the automated completion of
a set of steps. You've automated those three stages if you develop a macro that applies color to
certain cells, outputs the worksheet, and then eliminates the color.
Macro doesn't quite stand for Messy and Confusing Repeated Operation, by the way.
Alternatively, it is derived from the Greek makros, which means huge, and which also
characterizes your salary after you have mastered macro programming.
Knowing What VBA Can Do
You're undoubtedly conscious that Excel is used for a wide range of activities.
Here are a few such examples:

Scientific data analysis


Forecasting and budgeting
Receipts and other forms are created.
Creating graphs from data
Making lists of client names, grade point averages, and Christmas present ideas
The list can go on forever, but I'm sure you get the picture. My statement is basically that Excel
is utilized for a broad range of jobs, and everybody viewing this book has distinct Excel
requirements and assumptions. The urge to automate some component of Excel is something that
almost every user has in common. That is what VBA is all about, my reader.
Build a VBA application to input certain statistics, then prepare and publish your month-end
sales report, for instance. After you've finished writing and evaluating the program, you may run
it with a unified program, which will have Excel do several moment tasks for you. Instead of
struggling through a long list of instructions, you can just press a button and then go to Facebook
to pass time while your macro works.
In the subsequent sections, I'll go through some of the most popular applications for VBA
macros. One or two of these may set off your alarm.
Inserting A Bunch of Text
You may develop a macro to type your firm name, address, and phone number into your
spreadsheets if you need to do so often. You may take this idea as far as you want. For example,
you might create a macro that automatically writes a list of all of your company's salesmen.
Automating a task, you perform frequently
Assume you're a sales manager who has to write a month-end sales report in order to please your
employer. If the work is simple, you may write a VBA program to do it for you. Your manager
will be pleased by the continuously high quality of your reports, and you will be promoted to a
new position for which you are grossly underqualified.
Automating repetitive operations
If you need to conduct the same action on 12 distinct Excel workbooks, you may record a macro
while doing the activity on the first workbook and then have the macro repeat the action on the
others. Excel never complains about being bored, which is a wonderful feature. The macro
recorder in Excel works similarly to a video recorder when capturing live activity. It does not,
however, need the use of a camera, and the battery never has to be charged.
Making your own command
Do you have a habit of using the same Excel menu commands again and over? If that's the case,
create a macro that combines these instructions into a single custom command that you can run
with just a single keystroke or button click. You won't save much time, but you'll almost
certainly be more accurate. And the person in the cubicle next to you will be blown away.
Creating a custom button
You may add your own buttons to your Quick Access toolbar that run the macros you create.
Buttons that do magic are often quite impressive to office employees. You may even add
additional buttons to the Ribbon if you truly want to amaze your coworkers.
Developing new worksheet functions
Despite the fact that Excel comes with hundreds of built-in functions (such as SUM and
AVERAGE), you may develop custom worksheet functions to make your formulae easier. I
promise you'll be astonished at how simple it is. (In Chapter 20, I teach you how to achieve this.)
Even better, your own functions are displayed in the Insert Function dialog box, making them
look built-in. It's all quite fancy.
Creating custom add-ins for Excel
Several of the add-ins that come with Excel are presumably recognizable to you. The Analysis
Tool Pak, for example, is a popular add-in. You may create your own special-purpose add-ins
using VBA. People from all around the globe pay me actual money to utilize my Power Utility
Pak add-in, which I created using just VBA.
Creating complete, macro-driven applications
You can utilize VBA to construct large-scale programs with a custom Ribbon tab, dialog boxes,
onscreen assistance, and a variety of other features if you're prepared to put in the effort. This
book doesn't go nearly that far, but I'm just mentioning it to show you how strong VBA can be.
Advantages of VBA
Excel allows you to automate practically any task. You accomplish this by writing instructions
for Excel to follow.
Using VBA to automate a job has numerous advantages:

Excel always completes the assignment in the same manner. (Consistency is often a
desirable trait.)
Excel can do the work considerably quicker than you can (unless you're Clark
Kent, of course).
Excel always accomplishes the operation without mistakes if you're a skilled macro
coder (which definitely can't be stated for you or me).
If you put things up correctly, even someone who isn't familiar with Excel can
execute the macro and do the work.
Excel allows you to perform things that would otherwise be impossible, making
you a popular person at work.
You wouldn't have to sit beside your computer and grow bored with lengthy, time-consuming
chores. While you're at the water cooler, Excel performs the job.
Understanding what VBA excels at
I've produced a quick-and-dirty description of what VBA is all about just to let you know what
you're in for. Of course, I go into semi-excruciating detail about all of this later in the book.
VBA allows you to conduct tasks by writing (or recording) code in a VBA module. The Visual
Basic Editor is used to examine and modify VBA modules (VBE).
Sub procedures make up a VBA module. Sub procedures have nothing to do with submarines or
delectable sandwiches. Rather, it's a piece of computer code that does something with or on
things (discussed in a moment). The AddEmUp Sub method is shown in the following example.
When this fantastic application is run, the result of 1 + 1 is displayed:
A subpar process is one that does not work as expected.
Function procedures may be included in a VBA module. A single value is returned by a Function
procedure. You may use it as a function in a spreadsheet formula or call it from another VBA
operation. The following is an example of a Function procedure (called Add Two). This function
takes two integers as input (arguments) and returns the total of those numbers.

A dysfunctional function process is one that does not operate properly.


VBA is a program that manipulates things. You can alter thousands upon dozens of items in
Excel. A workbook, a worksheet, a cell range, a chart, and a shape are all examples of objects.
You have access to a lot more objects, which you can alter using VBA code.
Objects are organized in a hierarchical order. Things may be used to encapsulate other objects.
Excel is at the top of the object hierarchy. Excel is a kind of object known as an application.
Other items, such as Workbook objects and Add-In objects, are contained inside the Application
object. Other objects, such as Worksheet objects and Chart objects, may be contained inside the
Workbook object. Range and PivotTable objects may be included inside a Worksheet object. The
organization of these things is referred to as an object model. (Object-model aficionados may
learn more in Chapter 4.)
A collection is made up of objects of the same kind. The Worksheets collection, for example,
contains all of the worksheets in a certain workbook. All Chart objects in a workbook are part of
the Charts collection. Collections are things in and of themselves.
A dot (sometimes known as a period) is used as a separator to relate to an item's location in the
object hierarchy. For example, the workbook Book1.xlsx might be referred as
Application. Workbooks("Book1.xlsx")
This pertains to the Workbooks collection's workbook Book1.xlsx. The Application object
contains the Workbooks collection (that is, Excel). To take it a step further, you might refer to
Sheet1 in Book1.xlsx as
Application. Workbooks("Book1.xlsx").
You may go this even farther by referring to a particular cell (in this instance, cell A1), as seen in
the following example:
Application.Workbooks("Book1.xlsx").Worksheets("Sheet1").Range("A1")
Excel utilizes the active objects if you don't provide particular references. If Book1.xlsx is the
active workbook, the above reference may be simplified as follows:
Worksheets("Sheet1"). Range("A1")
You may reduce the reference even further if you know that Sheet1 is the active sheet:
Range("A1")
Objects have attributes. A property may be thought of as an object's setting. Value and Address
are two attributes of a Range object, for example. Has Title and Type are two characteristics of a
Chart object. VBA may be used to determine and update the characteristics of objects.
By combining the object name with the property name, separated by a dot, you may refer to a
property of an object. For example, the Value attribute in cell A1 on Sheet1 may be referred to as
follows:
Worksheets("Sheet1").Range("A1").Value
Variables may have values assigned to them. A variable is a kind of named element that keeps
data. Variables may be used in VBA code to store things like values, text, and property settings.
Use the following VBA statement to allocate the value in cell A1 on Sheet1 to a variable named
Interest:
Worksheets + Interest = ("Sheet1").Range("A1").Value
Methods exist in objects. An action Excel takes with an object is referred to as a method.
ClearContents, for example, is one of the Range object's methods. This technique clears the
contents of the range, as its name suggests.
A method is specified by combining the object with the method and separating them with a dot.
The following sentence, for example, clears the contents of cell A1: Worksheets ("Sheet1").
Range("A1"). ClearContents
VBA has all of the features found in current programming languages, including variables, arrays,
and loops. To put it another way, if you're prepared to put in some effort to understand the ropes,
you can build code that does amazing things.
Understanding the disadvantages of using VBA
You must be familiar with VBA programming (but that's why you purchased this book, right?).
Thankfully, it isn't as complicated as you would think.
Others who will be using your VBA applications will require their own versions of Excel. It
would be wonderful if there was a button that turned your Excel/VBA software into a standalone
program, but this isn't achievable (and probably never will be).
Things go awry from time to time. To put it another way, you can't expect that your VBA
application will always run properly in all situations. Welcome to the world of debugging and
technical assistance, if others are utilizing your macros.
VBA is an ever-changing target. Microsoft, as you may be aware, is constantly updating Excel.
Even while Microsoft makes a concerted effort to ensure that versions are compatible, you may
find that the VBA code you've created is incompatible with previous versions or future versions
of Excel.
CHAPTER TWO
BUILDING SIMPLE MACROS
By the conclusion of this chapter, you'll probably feel a lot better about this Excel programming
thing, and you'll be pleased you took the risk. This chapter walks you through the process of
creating a basic yet useful VBA macro.
Displaying the Developers Tab
You must go through the initiation ceremonies before you can call yourself an Excel coder. That
means you'll need to make a little adjustment to get Excel to show a new Developer tab at the top
of the screen. It's simple to get Excel to show the Developer tab (and you only have to do it one
time).
Simply follow the instructions below:

Customize the Ribbon may be accessed by right-clicking any portion of the Ribbon
and selecting Customize the Ribbon from the shortcut menu.
Locate Developer in the second column of the Customize Ribbon tab of the Excel
Options dialog box.
Next to Developer, put a check mark.
Click the OK button.
You're back in Excel, but this time there's a new tab called Developer.
When you select the Developer tab, the Ribbon shows information that programmers (that's
you!) will find useful. The picture below displays the Ribbon in Excel 2022 when the Developer
tab is chosen.

Creating a Macro
I'll show you how to make your first macro in this part. This is what the macro you're
going to make does:

Fills up a cell with your name.


In the box below, enter the current date and time.
Both cells are formatted to be bold.
The font size in each cell is increased to 16 points.
The Annual VBA Programmer's Competition will not award this macro any awards, but
everyone has to start somewhere. All of these processes are completed by the macro in a single
operation. You begin by documenting your behaviors as you move through these processes, as I
explain in the following sections. The macro is then tested to determine whether it works.
Finally, you add some final touches to the macro. Ready?
Preparing the Environment
The procedures you perform before recording the macro are described in this section.
To put it another way, you'll need to do a few preparations before you can start having fun:

If Excel isn't already open, open it.


Create a new, empty worksheet if required.
Ctrl + N is my preferred method of doing this.
Take a look at the Use Relative References button in the Code group on the
Developer page.
You're in excellent condition if the color of that button differs from the other ones. To activate
this option, click the Use Relative References button if it is the same color as the other buttons.
In Chapter 6, I go through the Use Relative References option in more detail. For the time
being, simply make sure the option is switched on. The Use Relative References button will have
a different color when it is switched on.
Recording the Macro
Carefully follow the following instructions:

Choose a cell.
Any cell will suffice.
Select Developer Code Record Macro from the menu bar, or click the macro
recording button on the status bar.
The dialog window for recording macros appears.
Give your macro a name.
Excel comes with a default name (something like Macro1), but it's best to give it
something more meaningful. This macro's name should be Name and Time
(without spaces).
Enter Shift + N (for an uppercase N) as the shortcut key in the Shortcut Key box.
It is not necessary to provide a shortcut key. You may run the macro by using a key
combination — in this example, Ctrl +Shift + N — if you define one.
Ensure that the Store Macro In option is set to This Workbook.
If you like, you can add some text to the Description box.
This is an optional step. Some individuals like describing the macro's function (or
is supposed to do).
Click the OK button.
Excel's macro recorder is switched on once the Record Macro dialog box closes.
Excel now keeps track of everything you do and transforms it into VBA code:

In the active cell, type your name.


To input this formula, move the cell cursor to the cell below and type:
=NOW()
The current date and time are shown in the formula.
To copy the formula cell to the Clipboard, select it and hit Ctrl + C.
Select Home > Clipboard > Paste Values from the drop-down menu (V).
The formula is converted to its value using this command.
Press the Shift key + up arrow when selecting the date cell to pick it and the one
above it (which contains your name).
Set the font size to 16 points and change the formatting to Bold using the options in
the home Font group.
Stop recording by selecting Developer Code.
The macro recorder has been disabled.

Running the Macro


You may now test this macro to check whether it works correctly. To test your macro, use
Ctrl+Shift+N in an empty cell.
Excel performs the macro in a flash. In huge, strong characters, your name and the current date
and time are shown.
Another approach to running the macro is to open the Macros dialog box by selecting Developer
Code Macros (or using Alt+F8). Click Run after selecting the macro from the list (in this
example, NameAndTime). Before running the macro, make sure the cell that will store your
name is selected.
Viewing a Macro in the Visual Basic Editor
You've created a macro and run it through its paces. If you're the inquisitive sort, you're
undoubtedly puzzled about the appearance of this macro. You could even be curious as to where
it's kept.
Do you recall when you first began recording the macro? You specified that the macro is saved
in This Workbook in Excel. The macro is saved in the worksheet, but you must first open it with
the Visual Basic Editor (VBE).
To view the macro, follow these steps:
Select Developer Code Visual Basic (or press Alt+F11) from the drop-down menu.
The Visual Basic Editor application window displays. Because this window can be customized
so much, your VBE window may appear a little different. The VBE program window is
particularly scary since it includes multiple other windows. Don't worry; you'll get accustomed to
it in no time.
Look for the Project window in the VBE window.
The Project window (also known as the Project Explorer window) displays a list of all currently
active workbooks and add-ins. Each project is organized as a tree that may be enlarged (to
display more information) or contracted (to display less information) (to show less information).
The VBE employs a variety of windows, each of which may be opened or closed. If a window
isn't instantly visible in the VBE, you may show it by selecting an option from the View menu. If
the Project window isn't visible, for example, choose View Project Explorer (or press Ctrl + R) to
bring it up. You may do the same thing with any other VBE window. In Chapter 3, I go through
the components of the VBE in further detail.
Choose the project that corresponds to the workbook where the macro was recorded.
The project is presumably named VBAProject if you haven't saved the workbook (Book1).
Toggle the addition symbol (+) to the left of the Modules folder.
The tree extends to reveal Module1, which is the project's lone module.
Module1 should be double-clicked.
A Code pane displays the VBA code in that module. The picture above is how it appears on my
computer screen. It's possible that your screen may differ somewhat. The code recorded is
determined by the activities you took when recording the macro.

`
You're probably thinking the macro is Greek at this point. Don't be concerned. After a few
chapters, everything will be as obvious as the view from Mount Olympus.
There are multiple statements in the NameAndTime macro. From top to bottom, Excel performs
the statements one by one. A comment is a remark preceded by an apostrophe ('). Comments are
solely offered for your convenience and will be disregarded. In other words, Excel ignores
comments entirely.
The first VBA line (which starts with the term Sub) identifies the macro as a Sub procedure and
gives it a name; you gave it a name before you began recording the macro. You may be able to
decipher parts of the code if you read it carefully. You can see your name, the formula you input,
and a bunch of other code that alters the typeface. The End Sub statement brings the Sub process
to a close.
The macro recorder works similarly to a tape recorder. When you listen to your own voice on a
tape, you always remark, "I don't sound like that." When you look at your recorded macro, you
can see certain activities that you weren't aware of.
Although you just modified the font size when recording the NameAndTime example, the
recorded code contains several font-changing commands (Strikethrough, Superscript, Shadow,
and so on). It occurs all the time, so don't be concerned. Excel often saves a lot of code that
seems to be worthless. You'll learn how to eliminate the extraneous data from a recorded macro
in subsequent chapters.
Modifying the Macro
You may not only see but also update your macro on the VBE, as you would think. Even if you
have no clue what you're doing at this point, I'm certain you can make the following code
changes.

Change the name in the active cell to something else. Use your dog's name if you
have one.
Change the name or size of the typeface.
See if you can find out where this new sentence that makes the cells italic should go.
Selection.Font.Italic = True
Working in a VBA code module is similar to working in a word processing document (with the
exception that there is no word wrap and the text cannot be formatted). On second thinking, it's
probably more akin to using Windows Notepad. You can start a new line by pressing Enter, and
the editing keys operate as intended.
Return to Excel once you've made your modifications and test out the new macro to see how it
works. You can switch back to Excel by pressing Alt+F11 in the VBE, just as you can switch
back to Excel by using Alt+F11 in Excel.
Saving Workbooks that Contain Macros
If you want to save a workbook with one or more macros, you must save it as a macro-enabled
file type. In other words, instead of the standard XLSX extension, the file must be stored with an
XLSM extension.
The file type in the Save As dialog box defaults to XLSX when you save the spreadsheet that
includes your NameAndTime macro, for example (a format that cannot contain macros). Excel
shows the warning seen in the picture until you convert the file format to XLSM. Choose Excel
Macro-Enabled Workbook (*.xlsm) from the Save As Type drop-down box after clicking No.

Understanding Macro Security


Excel's macro security is an important feature. The reason for this is because VBA is a strong
language — so powerful, in fact, that a macro written in it may cause catastrophic computer
harm. A macro may erase files, communicate information to other computers, and even
completely damage Windows, rendering it unusable.
The macro security enhancements in Excel were designed to help avoid issues like these.
The Macro Settings area of the Trust Center dialog box is shown in the picture. Select Developer
Code Macro Security to bring up this dialog box.

Excel utilizes the Disable All Macros with Notification option by default. If you open a
workbook that includes macros with this option enabled (and the file is not digitally "signed" or
saved in a trusted place), Excel will display a warning similar to the one shown in the picture. If
you're certain that the worksheet is legitimate, click Enable Macros, and the macros will be
enabled.

Only if the VBE is open can you see the pop-up box in the picture. Otherwise, as illustrated in
the figure, Excel displays an eye-catching Security Warning above the Formula bar. To activate
the macros, click the Enable Content option if you believe the worksheet is safe. Click the X to
dismiss the warning and use the worksheet without macros.

If you've classified a worksheet as safe, Excel will remember it. So, you won't notice the Security
Warning the next time you open it.
Designating one or more folders as trustworthy places may be the best strategy to address macro
security. Without a macro warning, all workbooks in a trusted place are opened. The Trusted
Locations part of the Trust Center dialog box is where you specify trusted folders.
While the Macro Options part of the Trust Center dialog box is open, click F1 to see what the
other macro security settings mean. A Help screen will appear, describing the security options.
Revealing More about the NameAndTime Macro
By the end of this book, you'll know all there is to know about the NameAndTime macro, and
you'll be able to create more advanced macros. For the time being, I'll sum up the chapter by
mentioning a few more aspects concerning the macro:
The worksheet for this macro must be open in order for it to function. The macro will not run if
you close the spreadsheet (and the Ctrl + Shift + N shortcut will not function).
You may execute the macro when any workbook is open as long as the workbook containing the
macro is open. To put it another way, the macro's own workbook does not need to be open.
The code in the macro isn't "pro-quality." It will replace previous content without notice, and its
consequences are irreversible.
You gave the macro a new shortcut key before you began recording it. This is only one of
several options for running the macro.
Rather than recording this macro, you may construct it manually. To do so, you'll need a solid
grasp of VBA. (Have faith; you'll make it.)
This macro may be saved in your Personal Macro Workbook. If you do this, the macro will be
accessible every time you open Excel. You may also make an add-in file from the worksheet.
PART TWO
EMPLOYING VBA WITH EXCEL
CHAPTER THREE
WORKING IN THE VISUAL BASIC EDITOR
You undoubtedly know a lot about workbooks, formulae, charts, and other Excel delights if
you're a more seasoned Excel user. Now it's time to broaden your horizons and investigate the
Visual Basic Editor, a whole new feature of Excel. You'll learn how to use the Visual Basic
Editor in this chapter, and you'll get down to the nitty-gritty of creating VBA code.
Getting to Know the Visual Basic Editor
I'm going to refer to the Visual Basic Editor as the VBE to spare my fingers some wear and
strain. VBA macros are written and edited in the VBE, which is a distinct program. It works in
tandem with Excel. When I say "seamlessly," I mean that Excel will open the VBE for you when
you need it.
With Excel 2022, each workbook is shown in its own window. There is just one VBE window,
however, and it is compatible with all open Excel windows.
The VBE cannot be operated independently; Excel must be open in order for the VBE to work.
Activating the VBE
When Excel is open, press Alt+F11 to activate the VBE quickly. Return to Excel by pressing
Alt+F11 once again. You may also close the VBE by clicking the Close button on the title bar.
Excel is launched when the VBE window is closed.
You may also use the Developer Code Visual Basic command to start the VBE. If you don't see a
developer tab at the top of your Excel window, see Chapter 2 for instructions on how to get that
useful Developer tab to appear.
Exploring VBE components
The VBE program is shown in the graphic, with some of the most important components
highlighted. Because there is so much going on in the VBE, I want to make the window as big as
possible to view everything.
It's likely that your VBE application window will differ somewhat from the one shown in the
picture. There are multiple windows in the VBE, and it is very customizable. You can hide,
move, and dock windows, among other things.
The VBE really contains more pieces than those seen in the illustration. When these new
elements become significant, I describe them throughout the book.
The menu bars
The VBE menu bar functions similarly to any other menu bar you've seen. It offers commands
that you may use to interact with the VBE's different components. You'll also notice that many of
the menu commands have corresponding shortcut keys.
Shortcut menus are also available in the VBE. You can access a shortcut menu of common
instructions by right-clicking almost anything in the VBE.
Toolbar
The Standard toolbar is one of four VBE toolbars available. It is located just below the menu bar
by default (see picture). You may change the toolbars' appearance, move them around, and show
different toolbars, among other things. Use the View Toolbars command to interact with VBE
toolbars if you're so inclined. The majority of people (including me) just leave them alone.
Project window
The Project window provides a tree diagram of all the workbooks that are presently open in
Excel (including add-ins and hidden workbooks). To expand or contract things inside the outline,
double-click them. In the section "Working with the Project Window," I go over this window in
further depth.
If you don't see the Project window, use Ctrl+R or use the View Project Explorer command.
Click the Close button on the Project window's title bar to close it. Or, from the shortcut menu,
right-click anywhere in the Project window and choose Hide from the drop-down menu.
Code window
Your VBA code is entered into a Code window. A Code window is connected with each item in
a project. Double-click an item in the Project window to open its Code window. Double-click
Sheet1 in the VBAProject for Book1 to see the Code window for the Sheet1 object in Book1.
The Code window will be empty unless you've added some VBA code.
Immediate window
It's possible that the Immediate window isn't displayed. If it isn't visible, use Ctrl+G or the View
Immediate Window command to bring it up. Click the Close button on the Immediate window's
title bar to close it (or right-click anywhere in the Immediate window and choose Hide from the
shortcut menu).
The Immediate window is particularly handy for instantly running VBA instructions and
debugging your code. If you're just getting started with VBA, this window won't be very helpful,
so hide it to make room for other things on your screen.
I go through the Immediate window in great depth in Chapter 13. It could turn out to be a terrific
buddy of yours!
IN THE VISUAL BASIC EDITOR, WHAT'S NEW?
Excel debuted a completely new user interface. A beautiful new Ribbon user interface replaces
menus and toolbars (UI). The VBE, on the other hand, was never given a makeover and
continues to use the old-school menu and toolbar UI.
Nothing else has changed except the VBA programming language has been upgraded to support
the new Excel capabilities. Perhaps Microsoft will update the VBE in the future, but I'm not
holding my breath.
The Help system is one item that has been altered. Previously, help material was saved on your
computer, and you could access Help over the Internet. Starting with Excel 2013, all helping
material is available online and may be accessed using your web browser. To put it another way,
you'll need to be online to use the Help system. You may, however, get a copy of the Help
system directly from Microsoft's website. You may discover it by doing a web search to
"download Excel VBA documentation."
Working with the project explorer
Every Excel worksheet and add-in that you have open in the VBE is a project. A project may be
thought of as a collection of things organized in a pattern. By clicking the plus symbol (+) to the
left of a project's name in the Project window, you may enlarge it. By clicking the negative
symbol (–) to the left of a project's name, you may contract it. You may also extend and shrink
things by double-clicking them.
When you double-click a project name, you'll be requested for the password if it's password-
protected. If you don't know the password, you won't be able to extend the project, which means
you won't be able to access or alter any aspect of it.
An add-in entitled pup7.xlam, an unsaved workbook named Book1, a workbook named
investments.xlsm, and the Personal Macro Workbook are all mentioned in the Project pane
(which is always named PERSONAL.XLSB). Only the investments.xlsm project is enlarged to
display all of its objects out of the four.

At least one node labeled Microsoft Excel Objects appears in every project. This node extends to
reveal one item for each sheet in the workbook (each sheet is an object) as well as a new object
named This Workbook (which represents the Workbook object). A Modules node appears in the
project listing if the project has any VBA modules. A project may additionally have a node
named Forms, which contains User Form objects, as seen in Part IV (which holds custom dialog
boxes).
For you, the notion of things may be a little hazy. However, I can assure you that things will
become a lot clearer in the next chapters. If you don't comprehend what's going on at this point,
don't worry.
Adding a new VBA Module
To add a new VBA module to a project, follow these steps:

Select the project's name in the Project pane in the VBE.


Select Insert Module from the drop-down menu.
Or

Right-click the project's name to open it in a new window.


From the shortcut menu, choose Insert Module.
Excel automatically adds a VBA module to retain the recorded code when you record a macro.
Which workbook contains the module for the recorded macro is determined by where you
decided to save it shortly before you began recording.
Removing a VBA module
You may need to delete a VBA module from a project at times. It might, for example, include
code that you no longer need, or it could be empty because you introduced the module and then
decided against it. To delete a VBA module from a project, do the following:

In the Project window, choose the module's name.


Remove xxx from the File menu, where xxx is the module name.
Or

Right-click the name of the module.


From the shortcut menu, choose Remove xxx.
Excel will ask whether you want to export the code in the module before you remove it since it is
constantly attempting to save you from doing anything you'll regret. Almost all of the time, you
don't. (See the following part if you wish to export the module.)
VBA modules may be removed, but the other code modules — those for the Sheet objects and
This Workbook — cannot.
Exporting and importing objects
In a VBA project, each object may be saved to its own file. Exporting is the process of saving a
single item from a project. It should go without saying that you can import objects into a project.
If you wish to utilize a specific item (such as a VBA module or a User Form) in a separate
project, you may export and import it. Perhaps you wish to transmit a copy of a VBA module to
a coworker, who can then import it into her project.
To export an item, follow these steps:

In the Project window, choose an item.


Choose File > Export File or press Ctrl + E to export a file.
A dialog window appears, asking for a filename. The object is not removed from the project;
only a copy is exported. Excel automatically generates a file extension for you, which is
determined by the kind of item you're exporting. The end output is always a text file. If you're
curious, you can open it in a text editor and examine it.
This is how you add a file to a project:

In the Explorer window, choose the project's name.


Choose File > Import File or press Ctrl+M to import a file.
A dialog window appears, asking for a file.
Click Open when you've found the file.
Only import a file if you previously exported it using the File Export File
command.

Working with a Code Pane


You spend a lot of time working on Code windows as you become better at VBA. You can enter
VBA code directly in a VBA module, and you can record macros in a module.
Window minimization and maximization
The VBE may have a lot of Code windows active at any one moment if you have numerous
projects open. The picture below exemplifies what I'm talking about.
Workbook windows in Excel are similar to code windows. You may minimize, maximize, resize,
conceal, and rearrange them, among other things. Most folks find that maximizing the Code
window that they're working on is significantly simpler. This allows you to view more code
while also preventing you from being distracted.
Click the Maximize button on the title bar of a Code window to maximize it (right next to the X).
To maximize it, just double-click its title bar. Click the Restore button to return a Code window
to its original size. Because the title bar of a maximized window isn't visible, the Restore button
is located underneath the VBE title bar.
You may wish to have two or more Code windows open at the same time. You could wish to
compare two modules' code or copy code from one module to another, for example. You may
manually arrange the windows or use the Window Tile Horizontally or Window Tile Vertically
commands to do it for you.
By hitting Ctrl+F6, you may easily move between Code windows. You can cycle between all of
the open Code windows if you keep pressing that key combination. The combination of
Ctrl+Shift+F6 cycles through the windows backward.
A Code window may be minimized to get it out of the way. You may also dismiss a Code
window by clicking the window's Close button (which shows an X) on the title bar. (Closing a
window just hides it; nothing is lost.) Simply double-click the relevant item in the Project
window to reopen it. Working with these Code windows, by the way, seems to be more complex
than it is.
Looking at the parts of a module
A VBA module may store three sorts of code in general:
Declarations: You give VBA one or more information statements. You may define the data type
for variables you want to use, for example, or set certain module-wide parameters. Declarations
are essentially a list of things that need to be done around the home. They aren't truly carried out.
Sub procedures are a group of computer instructions that, when performed, carry out a specific
task.
A sequence of computer instructions that returns a single result is known as a function
procedure (similar in concept to a worksheet function, such as SUM).
Any number of Sub procedures, Function procedures, and declarations may be stored in a single
VBA module. There is, however, a restriction – around 64,000 characters per module. By way of
comparison, this chapter has almost half as many characters. I haven't even come close to
approaching the 64,000-character limit after more than 20 years of VBA programming. And if I
did, there's an easy solution: Simply add a new module.
It's entirely up to you how you structure a VBA module. Some users like to retain all of their
VBA code for a given application in a single VBA module, while others prefer to break it up into
many modules. It's a matter of personal preference, much like how you arrange your furniture.
Getting VBA code into a module
An empty VBA module is like the bogus food you see in Chinese restaurant windows; it looks
delicious but doesn't do anything for you. You'll need some VBA code in the VBA module
before you can accomplish anything useful.
There are three methods to get VBA code into a VBA module:

Directly enter the code.


To record your activities and convert them to VBA code, use the Excel macro
recorder.
Copy and paste the code from one module into another.
I'd want to take a little detour to explain the terminology. I use the phrases sub procedure,
routine, program, procedure, and macro throughout this book. These words are a little
perplexing. A procedure is a term used by programmers to describe an automated process. A
process may be a Sub procedure, a Function procedure (both of which are commonly referred to
as routines), or even a program in technical terms. All of these phrases are interchangeable in my
mind. However, as will be shown in subsequent chapters, there is a significant distinction
between Sub and Function operations. Don't bother about the terminology for the time being.
Simply attempt to grasp the principles.
Directly entering a code
The most direct method isn't always the best. Directly inputting code entails just that: entering
the code directly. To put it another way, you input the code on your keyboard. In a VBA module,
entering and modifying text works as expected. You may pick, copy, cut, paste, and manipulate
the text in a variety of ways.
To make your code simpler to understand, use the Tab key to indent parts of the lines. Although
indenting isn't required, it is a nice habit to develop. You'll see why indenting code lines is
beneficial as you examine the code I offer in this book.
You can make a single line of VBA code as lengthy as you like. To break up long lines of code,
however, you may wish to utilize the line-continuation characters. End the first line with a space
followed by an underscore (_) to continue a single line of code (also known as a statement) from
one line to the next. Then, on the following line, continue the message. Don't forget about the
empty space. It won't work if the underscore character isn't preceded by a space.
Here's an example of a single sentence that has been broken down into three lines:

If this statement were put in a single line, it would work precisely in the same manner (with no
line-continuation characters). The second and third lines of this sentence are indented. Although
indenting is not required, it does assist to indicate that these lines are not different assertions.
The VBE was created by white-coated engineers who expected that individuals like us would
make blunders. As a result, there are numerous layers of undo and redo in the VBE. If you
accidentally removed a statement, click the Undo button on the toolbar (or press Ctrl+Z) until the
statement reappears. After you've undone your changes, you may click the Redo button to restore
them. I encourage experimenting with this feature until you have a good understanding of how it
works.
Are you prepared to type in some real-world code? Follow these steps to get started:

In Excel, create a new workbook.


To enable the VBE, press Alt+F11.
In the Project window, click the name of the new workbook.
To add a VBA module to the project, select Insert Module.
In the module, type the following code:
Sub GuessName()
Msg = "Is your name " & Application.UserName & "?"
Ans = MsgBox(Msg, vbYesNo)
If Ans = vbNo Then MsgBox "Oh, never mind."
If Ans = vbYes Then MsgBox "I must be psychic!"
End Sub
To run the procedure, place the cursor anywhere in the text you typed and press F5.
The Run Run Sub/UserForm command is accessed by pressing F5. Excel will run the operation
if you typed the code properly, and you will be able to answer the basic dialog box shown in the
picture. The text in the dialog box will differ from the text shown in the figure unless your name
is the same as mine.

It's possible that the GuessName macro will fail. Excel may protest and display the error
message Compile Error: Variable Not Defined when you attempt to execute it. Don't worry;
there's a simple solution.
If that issue occurs, check at the top of your module for the following text: Explicit option.
Simply remove that line, and the macro should function properly. When that line appears at the
beginning of a module, it means you must "declare" all of your variables. This topic is covered in
Chapter 7. If that line was inserted automatically, it suggests your VBE is set up to do so. Don't
be concerned about it for the time being. Simply delete the line and move on from the obnoxious
interruption.
You may notice that the VBE makes some changes to the text you enter when you enter the code
listed in Step 5. The VBE, for example, automatically inserts the End Sub statement after you
type the Sub statement. If you leave a space before or after an equal sign, the VBE will fill it in
for you. The VBE also modifies the color and capitalization of some text. All of this is absolutely
normal. It's just a way for the VBE to keep things tidy and readable.
You've just written a VBA Sub procedure, also known as a macro if you followed the previous
steps. Excel runs the code and follows the instructions when you click F5. To put it another way,
Excel evaluates each statement and executes your instructions. (Don't allow your newfound
power to get the best of you.) You can run this macro as many times as you like, but after a few
hundred times, it starts to lose its attractiveness.
For the record, the following concepts are used in this simple macro, all of which are
covered later in this book:

Defining a Sub procedure


Assigning values to variables (Msg and Ans)
Concatenating (joining) a string (using the & operator)
Using a built-in VBA function (MsgBox)
Using built-in VBA constants (vbYesNo, vbNo, and vbYes)
Using an If-Then construct
Ending a Sub procedure

Using the Macro recorder


Another technique to enter code into a VBA module is to use the Excel macro recorder to record
your activities. You should be familiar with this strategy if you completed the hands-on activity
in Chapter 2.
By the way, there's no method to record the GuessName technique described in the previous
section. Only anything that you can accomplish directly in Excel may be recorded. Excel's
standard toolkit does not include the ability to display a message box. (It's a VBA thing.) The
macro recorder is great, but you'll almost certainly need to input some code manually in many
circumstances.
Here's a step-by-step guide to creating a macro that adds a new worksheet and hides everything
except the first 10 rows and columns. Start with a fresh, blank workbook and follow these
instructions to attempt this example:

In the workbook, activate a worksheet.


Any kind of worksheet will suffice.
Make sure that Use Relative References is not selected in the Developer tab.
Absolute References will be used to record this macro.
Select Developer Code Record Macro from the menu bar, or click the icon next to
the Ready indication on the status bar's left end.
The Record Macro dialog box appears in Excel.
Name the macro TenByTen in the Record Macro dialog box, then use Shift +T as
the shortcut key.
When you hit Ctrl +Shift + T, the macro will run.
To begin recording, click OK.
Excel creates a new VBA module in the project that matches the current workbook
automatically. Excel will transform your actions to VBA code from this point forward. The
symbol in the status bar changes to a little square when you're recording. This message serves as
a reminder that the macro recorder is active.
You may also stop the macro recorder by clicking that symbol:

To the right of the final sheet tab, click the New Sheet button.
Excel creates a new spreadsheet for you.
Ctrl +Shift +right arrow to select all of Column K (the 11th column); then right-
click any chosen column and pick Hide from the shortcut menu.
Excel conceals all of the columns you've chosen.
Press Ctrl +Shift +down arrow to select the full Row 11; then right-click any
chosen row and pick Hide from the shortcut menu.
Excel conceals all of the columns you've chosen.
Cell A1 should be selected.
Select Developer Code Stop Recording from the drop-down menu, or click the
Stop Recording icon on the status bar (the small square).
Excel will no longer record your activities.
To see this freshly recorded macro, enable the VBE by pressing Alt+F11. In the Project box,
look for the name of the workbook. A new module has been added to the project, as you can see.
Whether or not you have any other modules in the workbook when you began recording the
macro determines the name of the module. If you don't, the module's name will be Module1. You
may open the Code window for a module by double-clicking it.

Here's the code that your actions generated:

To test this macro, open any worksheet and hit the Ctrl+Shift+T shortcut key that you specified
in Step 4.
Don't worry if you didn't set a shortcut key to the macro.
Here's how to get a list of all possible macros and then execute the one you want:

Select Developer Code Macros from the drop-down menu.


Fans of the keyboard may use the shortcut Alt+F8. Either of these techniques opens
a dialog box with a list of all the macros that are accessible.
Choose a macro from the drop-down menu (in this case, TenByTen).
To begin, press the Run button.
When Excel runs the macro, it creates a new worksheet with 10 visible rows and columns.
While the macro recorder is running, you may provide any number of instructions and conduct
any number of activities. Excel faithfully converts your mouse and keyboard movements into
VBA code.
You may also alter the macro after it has been recorded. To put your new abilities to the test,
change the macro to insert a worksheet with nine rows and columns displayed, which is ideal for
a Sudoku problem.
Copying VBA Code
Copying code from another module or anywhere else is the last option for putting code into a
VBA module (such as a website). For instance, a Sub or Function process that you develop for
one project may be beneficial in another. You may activate the module and utilize the standard
Clipboard copy-and-paste processes instead of spending time reentering the code. (I like the
keyboard commands Ctrl + C for copying and Ctrl + V for pasting.) Once you've pasted the code
into a VBA module, you may tweak it as needed.
You may discover a lot of VBA code samples on the internet. If you want to test them out, select
the code in your browser and copy it with Ctrl + C. Then choose a module and paste it using Ctrl
+ V.
When you copy code from a website, you may need to make some adjustments. Quotation
characters, for example, may be "smart quotes," which must be translated to plain quote
characters. Long lineups may even stretch around at times. Because erroneous statements display
in red in the VBE, they are easier to notice.
Customizing the VBE
You'll spend a lot of time with VBA modules on your screen if you're serious about becoming an
Excel coder. The VBE offers a variety of modification choices to make things as pleasant as
possible (no, please keep your shoes on).
Select Tools Options from the VBE menu while it is engaged. There will be four tabs in the
dialog box: Editor, Editor Format, General, and Docking. In the sections that follow, I go
through some of the more helpful choices.
Using the Editor tab
The graphic depicts the choices available when you choose the Editor tab in the Options dialog
box. To alter how specific aspects of the VBE operate, use the Editor tab's settings.
Auto Syntax Check option
If the VBE detects a syntax issue while you're typing VBA code, the Auto Syntax Check option
affects whether a dialog box appears. The dialog box describes the issue in general. If you don't
choose this option, VBE indicates syntax problems by highlighting them in a different color than
the rest of the code, and you won't have to deal with any pop-up dialog boxes.
Because I find dialog boxes unpleasant and can generally figure out what's wrong with a
statement, I normally leave this feature turned off. However, in the past (before I was a VBA
aficionado), I found this guidance to be really useful.
Require Variable Declaration option
VBE includes the following sentence at the beginning of each new VBA module you create if
Require Variable Declaration option is set:
Explicit Option
This parameter only impacts new modules; it has no effect on existing modules. You must
explicitly declare each variable you use if this sentence exists in your module. I explain why you
should establish this behavior in Chapter 7.
I usually leave this option unchecked since I prefer to add the Option Explicit statement
manually.
Auto List Members option
If the Auto List Members option is enabled, VBE will assist you in typing the VBA code. It
shows a list of words that would logically finish the sentence you're typing. IntelliSense is a term
used to describe this kind of wizardry.
This is one of the VBE's greatest features, and I usually leave it on. An example may be seen in
the picture (which will make lots more sense when you start writing VBA code).

Auto Quick Info option


VBE provides information about functions and their arguments as you enter if the Auto Quick
Info option is enabled. This can be quite beneficial. Figure 3-7 demonstrates this functionality in
action, informing me of the MsgBox function's parameters.

Auto Data Tips option


When debugging code, VBE shows the value of the variable over which your cursor is
positioned if the Auto Data Tips option is enabled. This option will come in handy when you join
the lovely realm of debugging, which I cover in Chapter 13.
Setting the Auto Indent
VBE's Auto Indent option dictates whether each new line of code is indented the same as the
preceding one. I use indentations a lot in my code, thus I keep this option on.
Instead of using the space bar to indent your code, use the Tab key. You may also "unindent" a
line of code by pressing Shift + Tab. Select all the lines you want to indent if you want to indent
more than one. Then hold down the Tab key.
Indent and Out dent are two essential buttons on the VBE's Edit toolbar (which is hidden by
default). You may rapidly indent or "unindent" a section of code with these buttons. To modify
the block's indenting, select the code and click one of these buttons.
Text Editing using Drag-and-Drop
When you activate Drag-and-Drop Text Editing, you can copy and move the text by dragging
and dropping it with your mouse. This option is always enabled, but I never use it. I like to use
the keyboard to copy and move.
Default to Full Module View option
The Default to Full Module View option determines how new modules are shown by default. If
this option is enabled, procedures in the Code window show as a single scrollable list. (It has no
effect on existing modules.) If this option is disabled, you will only be able to watch one process
at a time. This option is always on for me.
Procedure Separator option
Separator bars appear at the conclusion of each procedure in a Code window when the Procedure
Separator option is enabled. Separator bars appeal to me, therefore I keep this option enabled.
Using the Editor Format tab
The Editor Format tab of the Options dialog box is shown in the picture. This option allows you
to change the appearance of the VBE.
Code Colors option
The Code Colors option allows you to customize the text and background colors for different
VBA code parts. This is mostly a question of personal taste. Personally, I think the default hues
are quite enough. But, for a change of pace, I play around with these settings now and again.
Font option
You may choose the typeface used in your VBA modules using the Font option. Use a fixed-
width typeface like Courier New for the best results. All characters in a fixed-width typeface
have the same width. Because the letters are perfectly aligned vertically and several spaces can
be clearly distinguished, this makes your code more readable (which is sometimes useful).
Size setting
In VBA modules, the Size option determines the font's point size. This is a question of personal
choice, based on the quality of your television display and how many carrots you've consumed.
Margin Indicator Bar option
This setting affects how the vertical margin indication bar appears in your modules. If you don't
have this switched on, you won't be able to view the useful graphical indications when
debugging your code.
Using the General Tab

Error Trapping is the most important option. I highly advise you to enable the Break on
Unhandled Errors option (which is the default). Your error-handling code will not operate if you
choose a different option.
Using the Docking tab
The Docking tab is seen in the picture. The behavior of the VBE's numerous windows is
determined by these parameters. When a window is docked, it is permanently attached to one of
the VBE program window's boundaries. This makes identifying and locating a certain window
much easy. If you disable all docking, you'll be left with a jumble of windows. In general, the
default settings are enough.

When you're attempting to dock a window, you'll notice that the VBE has a life of its own at
times. If docking doesn't appear to be working, give it some time and you'll get the hang of it.

CHAPTER FOUR
INTRODUCING THE EXCEL OBJECT MODEL
An object is a term that everyone is familiar with. Forget the definition you think you know,
folks. The term object has a distinct connotation in the programming world. Object-oriented
programming, or OOP for short, is a term that is often used to describe it. OOP is founded on the
concept that software is made up of separate objects having characteristics (or properties) that
may be changed. These aren't physical items at all. They exist instead in the form of bits and
bytes.
The Excel object model, which is a hierarchy of objects stored in Excel, is introduced in this
chapter. By the end of this chapter, you'll have a solid idea of what OOP is all about — and why
you need to know about it if you want to become a VBA programmer. After all, Excel
programming is essentially the manipulation of Excel's objects. That's all there is to it.
This chapter's content may be a little overwhelming. But, please, follow my advice and go
through it, even if you don't understand everything right away. As you proceed through the book,
the key principles provided here will make a lot more sense.
Is Excel an Object?
You've undoubtedly used Excel for a long time but never considered it an object. The more time
you spend working with VBA, the more you'll think about Excel in those terms. Excel is an
object, and it contains other objects, as you will see. Those items then contain even more objects.
In other words, dealing with an object hierarchy is a part of VBA programming.
The Application object — in this example, Excel — is at the top of the hierarchy (the mother of
all objects).
Understanding the Hierarchy of Objects
Other items are contained inside the Application object.
Some of the most helpful items in the Excel application are as follows:

Addin
Window
Workbook
Worksheet Function
Each item in the Application object has the ability to contain additional objects.
The following are some examples of items that may be contained inside a Workbook object:

Graph (which is a chart sheet)


Name
VBProject
Window
Worksheet
Each of these things, in turn, may contain further objects. Consider a Worksheet object that is
part of a Workbook object that is part of the Application object.
The following are some of the items that may be included inside a Worksheet object:

Comment
Hyperlink
Name
PageSetup
PivotTable
Range
To put it another way, if you wish to accomplish anything with a range on a worksheet, you may
find it useful to visualize that range like follows:
The worksheet has a range, which is contained in a Workbook, which is included in Excel.
Is this starting to make sense to you?
You'll discover that Excel contains more items than you can shake a stick at once you start
digging around. Even seasoned veterans like me might get overwhelmed. The good news is that
you'll never have to deal with most of these items in real life. When you're working on an issue,
you may narrow your attention to a few key elements, which you can usually find by recording a
macro.
Wrapping Your Mind around Collections
Another important idea in VBA programming is collections. A collection is a grouping of similar
things. To add to the complexity, a collection is an object in and of itself.
Here are a few examples of collections that are regularly used:
Workbooks: This is a list of all the Workbook objects that are presently open.
Worksheets: A grouping of all Worksheet objects included in a Workbook object.
Charts: A grouping of all Chart objects (chart sheets) included in a Workbook object.
Sheets: A collection of all sheets (of any kind) present in a certain Workbook object.
It's worth noting that all of the collection names are plural, which makes sense (at least, I think
so).
You may well question, "What are collections for?" For example, they come in handy when you
need to deal with more than one worksheet, such as a few or all of them. As you can see, your
VBA code may loop over a collection's members and perform actions on each one.
Referring to Objects
The preceding parts were written to help you understand the following concept: referencing
objects in VBA code. You may operate with a complete group of items in a single step. More
often than not, though, you'll need to deal with a single item from a collection (such as a
particular worksheet in a workbook). To refer to a single item from a collection, including the
object's name or index number in parentheses after the collection's name, for example:
Worksheets("Sheet1")
The name of the sheet is included in quotation marks. Excel won't be able to recognize the object
if you don't include the quote marks (and will think it's a variable name).
You may also use the following reference if Sheet1 is the first (or only) worksheet in the
collection:
Worksheets(1)
The number is not in quotation marks in this example. What's the bottom line? Use quote marks
when referring to an item by its name. Use a simple number without quotation marks if you're
referring to an item by its index number.
What about graph paper? A single chart is included on a chart sheet. Although there is a sheet
tab, it is not a worksheet. The object model, it turns out, contains a collection named Charts. This
collection holds all of a workbook's chart sheet objects (and does not include charts embedded in
a worksheet). As a result, a single worksheet titled Sheet1 belongs to two different collections:
Worksheets and Sheets. It may be referred to in one of two ways:
Worksheets("Sheet1")
Sheets("Sheet1")
Getting around the hierarchy
All Excel objects are found under the Application object if you wish to deal with them. As a
result, begin by typing Application.
The Application object is the parent of all other objects in Excel's object model. You get to these
things by descending down the hierarchy and using the dot (.) operator to link each object along
the way. Start with the Application object and scroll down to the Workbooks collection object to
find the Book1.xlsx Workbook object:
Application. Workbooks("Book1.xlsx")
Add a dot operator and access the Worksheets collection object to go even farther to a particular
worksheet:
Application.Workbooks("Book1.xlsx").Worksheets(1)
Is it still not far enough? If you truly want to access the value from cell A1 on the first
Worksheet of the Book1.xlsx Workbook, you'll have to go one step up to the Range object:
Application.Workbooks("Book1.xlsx").Worksheets(1).Range("A1").Value
You've informed Excel precisely which range you want, on which worksheet, and in which
workbook, leaving no room for guesswork. People have a lot of imagination, but computer
programs don't.
Workbook names include a dot to distinguish the filename from the extension (for example,
Book1.xlsx). That is just coincidental. A filename's dot has nothing to do with the dot operator I
mentioned a few paragraphs back.
Setting object references
If you had to completely qualify every object reference you made, your code would become
rather extensive and maybe difficult to comprehend. Fortunately, Excel has certain keyboard
shortcuts that might help you increase readability (and save you some typing). To begin, the
Application object is assumed at all times. There are just a few instances when typing it makes
sense. The preceding section's example is shortened by omitting the Application object reference.
Workbooks("Book1.xlsx").Worksheets(1).Range("A1").Value
That's a significant improvement. There's more, however. You may also eliminate the reference
if you're certain that Book1.xlsx is the current workbook. You're down to the wire now.
Worksheets(1).Range("A1").Value
You're making progress now. Have you figured out what the next shortcut is? That's correct.
Excel believes the first worksheet is the currently active worksheet and enables you to input
directly into it.
Range("A1").Value
Excel, contrary to popular belief, does not contain a Cell object. A cell is nothing more than a
single-element Range object.
Although the shortcuts discussed here are beneficial, they may also be hazardous. I describe the
With-End With structure in Chapter 14, which not only helps you completely qualify your
references but also makes the code more understandable and reduces typing. It's like having the
best of both worlds!
Diving into Object Properties and Methods
Although learning how to refer to things is vital, merely referring to an item will not help you (as
in the examples in the preceding sections).
One of two things must be done in order to achieve something worthwhile:

The characteristics of an item may be read or modified.


To use with an object, provide an action method.
It's easy to get overwhelmed with the dozens of attributes and techniques accessible. I've been
dealing with this for years and I'm still feeling overwhelmed. But, as I've already said, you'll
never need to utilize the vast majority of the accessible properties and methods.
Setting objects properties
Everything has its own set of characteristics. Consider properties to be qualities that characterize
an item. The qualities of an item govern how it appears, acts, and even if it is visible.
You can accomplish two things with an object's properties using VBA:

Examine a property's current configuration.


Change the property's configuration.
A single-cell Range object, for example, has a Value attribute. The value in the cell is stored in
the Value property. You may use VBA code to show or hide the Value property, as well as to set
the Value property to a specified value.
MsgBox, is a really handy function. It may be used to show results while Excel runs your VBA
code. The above code shows how to display the current value of a cell's Value attribute.
Worksheets with ChangeValue() ("Sheet1").
Range("A1").
End Sub Value = 994.92
After Excel completes it, the number 994.92 appears in the cell on Sheet 1 of the current
workbook. Executing the macro will result in an error message if the current workbook does not
contain a sheet called Sheet1. VBA just executes commands, and thus cannot operate with a
sheet that is not existing.
Although certain attributes are shared by numerous objects, each object has its unique set of
properties. Many (but not all) objects, for example, have a Visible attribute. A Name attribute
may be found on almost all objects.
Some object properties are read-only, which means your code can access the field but not alter it.
This implies that a collection contains qualities as well. The Count property of the Workbooks
collection, for example, may be used to identify how many workbooks are open. This displays a
message box that displays the number of open workbooks:
Sub CountBooks()
MsgBox Workbooks.Count
End Sub
Taking action with object methods
Objects contain methods in conjunction with the properties. A method is a command you provide
to an object. A method may alter an object's properties or cause it to perform an action.
The ClearContents method on a Range object is used in this basic example to remove the
contents of 12 cells on the current sheet:
Sub ClearRange()
Range("A1:A12").ClearContents
End Sub
One or more arguments are required by certain methods. An argument defines the action to be
performed in more detail. The arguments for a method are separated by a space after the method.
A comma separates several arguments.
The following example launches Sheet1 (in the current workbook) and then uses the Range
object's Copy function to copy the contents of cell A1 to cell B1. The Copy method in this
example has just one parameter, which is the copy operation's target range:
Sub CopyOne()
Worksheets("Sheet1").Activate
Range("A1").Copy Range("B1")
End Sub
When I refer to the Range objects, you'll see that I don't include the worksheet reference. I'm safe
doing this since I activated Sheet1 with a statement. The formal argument name, followed by a
colon, then an equal sign, is another way to declare an argument for a method. Although using
named parameters is not required, it might make your code simpler to comprehend. The
CopyOne procedure's second statement might be worded as follows:
Range("A1").Copy Destination:=Range("B1")
Collections have methods because they are both objects and collections. The Add technique is
used in the following macro for the Workbooks collection:
Sub AddAWorkbook()
Workbooks.Add
End Sub
This sentence, as you would guess, generates a new workbook. To put it another way, it adds a
new workbook to the collection of Workbooks. The active worksheet will be a new workbook
when you run this macro.
Triggering actions with objects events
In this part, I'll go over one more issue that you should be aware of: events. Objects react to a
variety of circumstances. A Workbook Activate event happens, for example, when you're
working in Excel and you activate a separate workbook. For example, you might create a VBA
macro that runs anytime an Activate event happens for a certain Workbook object.
Many events are supported by Excel, but not all objects can react to them. Some things, on the
other hand, do not react to any events. The only events you may utilize are those provided by
Microsoft Excel's programmers. In Chapter 11 and Part IV, the notion of an event is clarified.
Getting additional information from VBA resources
Consider yourself a newcomer to the world of objects, properties, methods, and events. In the
following chapters, you'll learn more about these ideas. If you still haven't had your fill, here are
three more excellent tools to consider:

The Help system in VBA


The Object Browser
Auto List Members

Using the Help System in VBA


Every object, attribute, and function accessible to you are described in the VBA Help system,
which also includes an example code. This is a fantastic resource for learning about VBA, and it
is much more extensive than any book currently available. However, reading it is tedious.
The VBA Help system, on the other hand, may be downloaded from Microsoft's website. You
may discover it by doing a web search to "download excel VBA documentation."
If you're working in a VBA module and want to learn more about a certain object, method, or
property, drag the cursor to the term and click F1. In a matter of seconds, your web browser
displays the proper Help subject, replete with cross-references and possibly even an example or
two.
Part of a screen from the VBA Help system — in this case, for a Worksheet object — is shown
in the image.
Using the Object Browser
The Object Browser is another tool included in the VBE. This tool, as the name implies, allows
you to browse through the objects that are available to you. When the VBE is open, hit F2 (or
select View Object Browser) to open the Object Browser. You come across a window similar to
the one depicted in the image.
A list of all presently accessible object libraries may be found in the drop-down list at the top.
All Libraries are shown in the picture. Select Excel from the drop-down list if you want to look
through the objects in Excel.
You can enter a search string in the second drop-down list. For example, type a comment in the
second field and click the Search button to find all Excel objects that deal with comments. (It's
equipped with a pair of binoculars.) Everything in the object library that includes the text remark
is shown in the Search Results pane. If you find anything that seems interesting, pick it and click
F1 to go to the website for additional information.
Automatically listing properties and methods
I mention a useful tool called Auto List Members in Chapter 3. As you write, this feature
displays a list of properties and methods. The image depicts a Workbooks collection example.
The VBE offered to assist by providing some processes for that collection once I entered the dot
after workbooks. When I entered the letter c, the list was limited down to just those products that
started with that letter. Simply choose the item you need, click Tab, and you're done! You've
saved yourself some typing time while also ensuring that the property or method was
appropriately spelled.

CHAPTER FIVE
VBA SUB AND FUNCTIONS PROCEDURES
I mentioned Sub procedures and alluded to the notion that Function procedures play a part in
VBA many times in previous chapters. The secrets are exposed in this chapter, and any
misunderstandings concerning these notions are clarified.
Understanding Subs versus Functions
A procedure is a name for the VBA code that you create in the Visual Basic Editor. Sub
procedures and Function procedures are the two most prevalent kinds of procedures.
A sub procedure is a collection of VBA lines that performs a specific operation (or set of actions)
in Excel.
A function procedure is a collection of VBA statements that execute a single computation and
return a single result (or, sometimes, an array).
Sub procedures are the most common kind of macro in VBA. A Sub-process may be thought of
as a command: run the Sub procedure, and something occurs. (Of course, what occurs depends
on the VBA code in the Sub method.)
A Function is a procedure, but it's not the same as a Sub. A function is a notion you're already
acquainted with. Many worksheet functions in Excel are used on a daily basis (well, at least
every weekday). SUM, PMT, and VLOOKUP are some examples. These worksheet functions
are used in formulae. Each function accepts one or more arguments (with the exception of a few
functions that don't take any). The function does certain computations behind the scenes with
those parameters before returning a single result. Function procedures are created using the VBA
function in the same manner.
Examining Sub-Procedures
Each Sub procedure begins with the keyword Sub and concludes with the sentence End Sub.
Here's an illustration:
Sub ShowMessage()
MsgBox "That's all folks!"
End Sub
The technique ShowMessage is shown in this example. The procedure's name is followed by a
set of parentheses. Most of the time, these parentheses are left blank. Subprocesses, on the other
hand, may take arguments from other procedures. If your Sub has any arguments, put them in
parenthesis.
When you use the Excel macro recorder to create a macro, the outcome is always a Subprocess
that accepts no parameters.
Excel offers a variety of methods to run a VBA Sub-process, as you'll discover later in this
chapter.
Looking at Function procedures
Each Function procedure begins with the keyword Function and concludes with the phrase End
Function.
Cube Root is a function that accepts one parameter (a numeric variable) that is contained in
parentheses. There may be up to 255 parameters in a function or none at all. When you run the
function, it just returns one value: the cube root of the input you supplied it.
The kind of information (also known as data type) returned by a Function procedure may be
specified in VBA. More information on specifying data types can be found in Chapter 7.
A Function procedure may only be used in one of two ways: from another process (a Sub or
another Function procedure) or from a worksheet formula.
You can't record a Function operation with the Excel macro recorder, no matter how hard you
try. Every Function procedure you design must be manually entered.
Naming Subs and Functions
Every Sub and Function method, like individuals, cats, and storms, needs a name. Although
calling your dog Hairball Harris is absolutely appropriate, it's typically not a good idea to employ
such a loose approach when naming procedures.
When naming processes, there are a few guidelines to follow:

Letters, numerals, and various punctuation characters are all acceptable, but the
initial character must be a letter.
There are no spaces or periods allowed in the name.
Uppercase and lowercase letters are not distinguished in VBA.
Any of the following characters cannot be used in a procedure name: #, $, percent,
&, @, *, or! In other words, your process name must not resemble swear words
from a comic book.
Avoid using a name that appears like a cell address when writing a Function
method for use in a calculation (for example, A1 or AK47). Actually, such function
names are permitted in Excel, but why complicate things further?
Procedure names are limited to 255 characters in length. (Of course, a process
names this lengthy would never be created.)
Some programmers like titles that are similar to sentences and offer a detailed explanation of the
method. Write Report to Text File and Get Print Options and Print Report are two examples.
The adoption of such long names has both advantages and disadvantages. On the one hand, such
names are often descriptive and straightforward. They do, however, take longer to type. If your
macro isn't simply a quick-and-dirty temporary macro, it's a good idea to be descriptive and
avoid meaningless titles like DoIt, Update, Fix, and the ever-popular Macro1.
Executing Sub procedures
I'm going to skip forward a little and talk about how to execute these procedures, even if you
don't know anything about designing Sub procedures at this time. This is critical since a Sub-
process is useless if you don't know how to apply it.
By the way, running or calling a Sub-process is the same thing as executing a Sub procedure.
You are free to use whatever phrase you choose.
I'm not sure how I'm going to run thee. I'll count the ways for you. VBA Sub operations may be
executed in a variety of ways, which is one of the reasons you can accomplish so much with
them. Here's a full list of methods to run a Sub procedure (at least all the ones I could think of):
With the Run Sub/UserForm command, you may create a new user form (in the VBE). The
Subprocess in which the cursor is situated is executed by Excel. The F5 key and the Run
Sub/UserForm button on the Standard toolbar in the VBE are both options for this menu
command. If the process needs one or more parameters, these methods will fail.
From the Macro dialog box in Excel. You may access this box by selecting Developer Code
Macros or View Macros Macros. Alternatively, you may use the Alt+F8 shortcut key to skip the
Ribbon entirely. Select the Subprocess you wish to run from the Macro dialog box and click
Run. Only the procedures that do not need an argument are listed in this dialog box.
Use the shortcut Ctrl+key (or Ctrl+Shift+key) for the Sub-process (assuming you assigned one).
On a worksheet, click a button or a shape. A Sub-process must be given to the button or shape,
which is extremely simple to implement.
You've written another sub-procedure.
From a button on the Quick Access toolbar that you've created. (For further information, see
Chapter 19.)
You've added a custom item to the Ribbon. (For further information, see Chapter 19.)
When a certain occurrence happens. As I describe in Chapter 11, these events include things like
opening the workbook, shutting it, saving it, changing a cell, activating a page, and so on.
From the VBE's Immediate window. Simply input the Sub procedure's name and click Enter.

ShowCubeRoot, by the way, is not an example of a good macro. Because it does not check for
faults, it is prone to failure. Try hitting the Cancel button in the input field or inputting a negative
number to understand what I mean. Either action causes an error notice to appear. How to cope
with these sorts of mistakes is covered in Chapter 12.
Directly executing the Sub procedure
One option to run this procedure is to do so straight from the VBA module where it was created.
Take the following steps:

Activate the VBE and go to the VBA module where the procedure is located.
Place the cursor anywhere in the code of the method.
Press F5 (or choose Run Sub/UserForm from the menu).
Click OK after responding to the entry box.
The cube root of the number you supplied is shown by the process.
Because there is no method to transmit the parameters to the procedure, you can't use the Run
Run Sub/UserForm command to perform a Sub procedure that requires arguments. If a process
has one or more arguments, it can only be called from another procedure, which must give the
argument (s).
Executing the procedure from the Macro dialog box
Subprocesses are often run from Excel rather than the VBE.
The instructions below show how to use the Macro dialog box in Excel to run a macro:

Activate Excel if you're working in the VBE.


The shortcut is to hit Alt+F11.
Developer Code Macros (or Alt+F8) is the option to choose.
The dialog box seen in the picture is shown in Excel.
Choose the macro you want to use.
Double-click the macro's name in the list box to run it.
Sub procedures that utilize parameters are not shown in the Macro dialog box. You can't define
the parameters since there isn't a mechanism to do so.
Executing a macro using a shortcut key
Pressing the shortcut key for a macro is another method to run it. However, before you can use
this strategy, you must give the macro a shortcut key.
When you start recording a macro, you have the option of assigning a shortcut key in the Record
Macro dialog box. If you don't want to use the macro recorder to build the process, you may use
the following procedure to assign a shortcut key (or edit an existing shortcut key):

Select Developer Code Macros from the drop-down menu.


From the list box, choose the name of the sub-process.
ShowCubeRoot is the name of the technique in this example.
Select the Options tab.
The Macro Options dialog box appears in Excel, as seen in the picture.
Select the Shortcut Key option and type a letter in the Ctrl box.
The letter you type should match the key combination you intend to use to run the macro. If you
type the lowercase letter c, for example, you may run the macro by hitting Ctrl + C. You must
add the Shift key to the key combination if you want to type an uppercase letter. If you type C,
for example, you may run the macro by hitting Ctrl +Shift +C.
Close the Macro Options dialog box by clicking OK, and then close the Macro dialog box by
clicking Cancel.
After you've set a shortcut key, you may run the macro by pressing that key combination. If a
shortcut key is set to a macro that uses an argument, it will not operate.
Excel's built-in shortcut keys are overridden by the shortcut keys you set to macros. For example,
the common shortcut key for copying data is Ctrl+C. You can't use Ctrl+C to copy if Ctrl+C is
assigned to a macro. Excel nearly often offers alternate means to perform instructions, thus this
isn't a significant concern.
Executing the procedure from a button or shape
The concept of attaching the macro to a button (or any other form) on a worksheet might be
appealing at times.
Follow these steps to attach the macro to a button:

Make a worksheet active.


From the Form Controls group, add a button.
Select Developer Controls to see the Form Controls group.
Insert
In the Form Controls group, choose the Button tool.
It's the first of the controls in the first row.
To make the button, drag it into the spreadsheet.
Excel reads your thoughts and shows the Assign Macro dialog box seen in the
picture when you add the button to your worksheet.

Choose the macro you'd want to apply to the button.


Click the OK button.
After you've created the assignment, just click the button to start the macro.
When you add a button, you'll see two types of controls in the drop-down box: Form Controls
and ActiveX Controls. Although these two sets of controls seem to be identical, they are fact
rather distinct. In practice, Form Controls are more user-friendly.
A macro may also be assigned to any other form or object. Assume you want to run a macro
every time the user hits a Rectangle object.
Take the following steps:

The Rectangle should be added to the worksheet.


Using the Insert Illustrations Shapes command, create a rectangle.
Select the rectangle using the right-click menu.
From the shortcut menu, choose Assign Macro.
In the Assign Macro dialog box, choose the macro.
Click the OK button.
After you've completed these steps, click the rectangle to start the macro.
Executing the procedure from another procedure
A process may also be called from another procedure. If you want to give it a go, follow
these steps:
Activate the ShowCubeRoot method in the VBA module.
Put this new method (before or below the ShowCubeRoot code - it doesn't matter):
Sub NewSub()
Call ShowCubeRoot
End Sub
Use the NewSub macro to create a new subroutine.
To accomplish this, just drag the mouse anywhere inside the NewSub code and click F5. It's
worth noting that the ShowCubeRoot method is all that this NewSub technique does.
The keyword Call, by the way, is optional. Only the name of the Subprocess may be used in the
statement. Using the Call keyword, on the other hand, makes it quite obvious that a process is
being called.
Executing Function procedures
Give this basic function a go. Put it in a VBA module like this:
Function CubeRoot(number)
CubeRoot = number ^ (1 / 3)
End Function
This function does nothing more than computing the cube root of the integer supplied to it as an
input. It does, however, serve as a starting point for learning how to use functions. It also
demonstrates how to return the value, which is a fundamental notion in functions. (Do you recall
that a function produces a value?)
It's worth noting that the Function procedure's single line of code conducts a computation. The
variable CubeRoot is allocated the outcome of the math (number to the power of). CubeRoot is
also the name of the function, which is no coincidence. You give the value to the name of the
function to tell it what value to return.
Calling the function from a Sub procedure
Sub CallerSub()
Ans = CubeRoot(125)
MsgBox Ans
End Sub
Excel shows a message box with the value of the Ans variable, which is 5 when you run the
CallerSub procedure
Change the parameter given to the CubeRoot function and try calling the CallerSub macro again.
It works as expected, providing you pass a valid parameter to the function (a positive number).
By the way, the CallerSub technique may be made a little more straightforward. Unless your
code will utilize the Ans variable, later on, the Ans variable isn't actually needed. You may get
the same result with only one statement:
MsgBox CubeRoot(125)
Calling a function from a worksheet formula
=CubeRoot(1728)
This function may be used as many times as you like in the worksheet. Your own functions, like
Excel's built-in functions, appear in the Insert Function dialog box. Select the User Defined
category from the Insert Function toolbar button. The Insert Function dialog box, as seen in the
picture, allows you to create your own function.
Follow these steps to have a description of the function shown in the Insert Function dialog
box:

Select Developer Code Macros from the drop-down menu.


The Macro dialog box appears in Excel, but CubeRoot does not show in the list.
(CubeRoot is a Function procedure, and only Sub procedures are shown in this list.)
Don't be concerned.
In the Macro Name box, type the term CubeRoot.
Select the Options tab.
In the Description box, provide a description of the function.
To exit the Macro Options dialog box, click OK.
Click the Cancel button to exit the Macro dialog box.
The Insert Function dialog box now has this informative text.
The CubeRoot function is seen in usage in worksheet formulae in the picture.
Things may be beginning to fall into place for you at this point. (I wish I had known about this
book when I first started out.) Sub and Function procedures have taught you a lot. You begin
constructing macros in Chapter 6, which covers the ins and outs of utilizing the Excel macro
recorder to create macros. Chapter 20 delves much deeper into Function Processes.
CHAPTER SIX
USING THE EXCEL MACRO RECORDER
The ins and outs of utilizing the Excel macro recorder are covered in this chapter. Recording a
macro isn't always the ideal strategy, and certain macros are impossible to capture no matter how
hard you try. However, you'll discover that the Excel macro recorder is really handy. Even if the
macro you captured isn't exactly perfect, the macro recorder can nearly always point you on the
right path.
Recording Basics
When you record a macro, you do the following fundamental steps. Later in this chapter, we will
go through these stages in further depth.

Make a decision on what you want the macro to accomplish.


Make sure everything is in order.
The success of your macro is determined by this phase.
Decide whether you want your macro's cell references to be relative or absolute.
On the left side of the status bar, click the Record Macro button (or choose
Developer Code Record Macro).
The Record Macro dialog box appears in Excel.
Give the macro a name, a shortcut key, and a description.
With the exception of the name, each of these elements is optional.
In the Record Macro dialog box, click OK.
A VBA module is automatically inserted by Excel. Excel turns your actions to
VBA code at this stage. On your status bar, it also shows a square Stop Recording
button.
Using the mouse or the keyboard, do the activities you wish to record.
When you're done, click the Stop Recording button on the status bar (or choose
Developer Code Stop Recording from the menu).
Excel will no longer record your activities.
To ensure that the macro is working properly, test it.
(Optional) Remove any unnecessary statements from your code and add some comments to
clarify what it does.
Simple, basic macros are best recorded using the macro recorder. You could want a macro that
applies formatting to a certain region of cells or creates a row and column headers for a new
worksheet, for example.
Only Sub procedures may use the macro recorder.
It may also be useful for creating more complicated macros. I often record certain activities
before copying the recorded code into a more complicated macro. Most of the time, you'll need
to change the recorded code and add new VBA statements.

Performing any sort of looping that is repetitious


Performing conditional actions of any kind
Values are assigned to variables.
Choosing data types
Messages that appear as pop-ups
Showing custom dialog boxes
The macro recorder's limited capabilities do not negate its significance. Throughout the book, I
make the following point: The best approach to learning VBA is to record your activities. If
you're unsure, try recording. Viewing the recorded code may show certain objects, attributes, and
methods that you weren't aware of and point you on the correct path, even if the outcome isn't
precisely what you want.

Getting Ready to Record


Spend a minute or two thinking about what you're going to do before you take the big step and
switch on the macro recorder. You'll want to record a macro so that Excel can automatically
repeat the activities you record, so be sure they're exact.
The effectiveness of a recorded macro is ultimately determined by five factors:

How to set up the workbook while recording the macro


When you start recording, what options do you have?
Whether you record in absolute or relative mode
The precision with which you documented your activities
The environment in which the recorded macro is played back
When I guide you through an example, the relevance of these elements becomes clearly evident.
Choosing Between Absolute and Relative Modes
Excel generally records absolute references to cells when documenting your operations. (This is
the recording mode by default.) However, this is often the incorrect recording mode. Excel
captures real cell references when you utilize absolute recording mode. Excel records relative
references to cells when you utilize relative recording. Continue reading to learn more about the
differences.
Absolute recording mode
To record a basic macro in absolute mode, follow these instructions. In a spreadsheet, this
macro simply inputs three-month names:

Select Developer Code Record Macro after ensuring that the Developer Code Use
Relative References button is not selected.
As the name for this macro, type Absolute.
To begin recording, click OK.
Cell B1 should be activated, and Jan should be typed in that cell.
In cell C1, type February.
Make your way to cell D1 and type Mar.
To reactivate cell B1, click it.
Stop recording macros.
To enable the VBE, press Alt+F11.
Take a look at the Module1 module.
The following code is generated by Excel:
Sub Absolute()
'
' Absolute Macro
'
Range("B1").Select
ActiveCell.FormulaR1C1 = "Jan"
Range("C1").Select
ActiveCell.FormulaR1C1 = "Feb"
Range("D1").Select
ActiveCell.FormulaR1C1 = "Mar"
Range("B1").Select
End Sub
This macro chooses cell B1 and puts the three-month names into the range B1:D1 when it is run.
Cell B1 is then reactivated by the macro.
These activities take place regardless of which cell is active at the time the macro is run.
Recording in relative mode
By choosing the Use Relative References button in the Developer Tab’s Code group, you may
modify how Excel remembers your activities. This button acts as a toggle switch. The recording
mode is relative when the button is highlighted in a different color. You're recording in absolute
mode when the button shows properly.
You may switch recording methods at any moment, even while recording is in progress.
Remove the contents in range B1:D1 and then execute the following steps to observe how
relative mode recording works:

Cell B1 should be activated.


Select Developer Code Record Macro from the Developer menu.
Relative is the name of the macro.
To begin recording, click OK.
To change the recording mode to a relative, click the Use Relative References
option.
This button becomes a different color from the rest of the ribbon when you click it.
In cell B1, type Jan.
In cell C1, type February.
Move to cell D1, and type Mar.
Cell B1 should be selected.
Stop recording macros.
This approach is somewhat different from the last example. Before you begin recording, you
load the initial cell in the example. This macro will always begin typing in the present cell. Give
it a go. After that, move the cell pointer to any cell and run the Relative macro. Excel creates
code that is substantially different from the code created in absolute mode when the recording
mode is changed to a relative:
Sub Relative()
'
' Relative Macro
'
ActiveCell.FormulaR1C1 = "Jan"
ActiveCell.Offset(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = "Feb"
ActiveCell.Offset(0, 1).Range("A1").Select
ActiveCell.FormulaR1C1 = "Mar"
ActiveCell.Offset(0, -2).Range("A1").Select
End Sub
Activate any cell in exception of cell B1 to try this macro. Beginning with the cell that you
triggered, the month names are typed in three cells.
It's worth noting that the macro recorder's code relates to cell A1. This may appear weird since
cell A1 was never utilized throughout the macro recording.
What Gets Recorded?
Excel translates your mouse and keyboard operations into legitimate VBA code when you enable
the macro recorder. I could probably spend many pages discussing how Excel does this, but
seeing the macro recorder in action is the best way to grasp the process. The picture is how my
screen appears while the macro recorder is on.
Take the following steps:

Begin by creating a blank worksheet.


Know if the Excel window is maximized.
To enable the VBE, press Alt+F11
Resize and reposition the Excel and VBE windows so that they are both visible.
Position the Excel window above the VBE window for optimal results, and close
any other open programs.
Activate Excel and choose Developer Code Record Macro from the Developer
menu.
To start the macro recorder, click OK.
Excel creates a new module called Module1 and begins recording in it.
Activate the VBE program window by clicking on it.
Double-click Module1 in the Project Explorer window
Return to Excel and experiment for a bit. Choose from a number of Excel instructions. Select
cells, add data, format cells, utilize Ribbon commands, make a chart, adjust column widths,
modify graphical elements, e.t.c– let your imagination run wild!
If you have a dual-monitor system, you may find it useful to maintain Excel on one monitor and
the VBE window on the other. That's how I usually operate.
Specifying recording options for your Macro
You have numerous possibilities when recording your activities to produce VBA code.
Remember that before recording starts, the Developer Code Record Macro command shows the
Record Macro dialog box, as seen in the picture.

You may customize a few features of your macro in the Record Macro dialog box. These choices
are described in the following sections.
Macro name
You may give the Subprocess that you're recording a name. Excel assigns the names Macro1,
Macro2, and so on to each macro, you record by default. Normally, I simply go with the default
name. If the macro works well and I want to keep it, I update the recorded code in the VBE to
give it a more descriptive name later. You may, on the other hand, decide to name the macro
right away; the option is yours.
Shortcut key
The Shortcut key option allows you to run the macro by hitting a combination of shortcut keys. If
you type w (lowercase), for example, you may run the macro by hitting Ctrl+W. When you hit
Ctrl + Shift + W, the macro springs to life if you type W (uppercase).
There's no necessity to choose this option while recording a macro since you may add or modify
a shortcut key at any moment. To learn how to assign a shortcut key to an existing macro, go
here.
Store Macro In option
Excel uses the Store Macro In option to inform it where to save the macro it's recording. Excel
saves the recorded macro as a module in the current worksheet by default. You may record it in a
new workbook (Excel creates a blank workbook) or your Personal Macro Workbook if you like.
Your Personal Macro Workbook is a secret workbook that launches Excel automatically.
PERSONAL.XLSB is the name of the Personal Macro Workbook. Until you identify it as the
destination for a recorded macro, this file does not exist. When you depart Excel, if you've made
any modifications to this file, it asks you to save it.

Description
Use the Description box to provide some descriptive notes in your macro. You may write
anything you like in this box or nothing at all. The Description option is a waste of time in my
opinion since adding comments to the recorded macro in the VBE is just as simple.
Streamlining Macro Recorder-Generated Code
You may believe that recording a macro would result in award-winning VBA code that is
superior to anything you could create manually. Reconsider your position. In many
circumstances, the recorder sends out a lot of useless data, and it often creates inefficient code.
Don't get me wrong: I'm a firm believer in a macro recording. It's an excellent tool for learning
VBA. Except for basic macros, I've never utilized a recorded macro without tinkering with it
(usually quite a bit).
Try the following to see how inefficient the macro recorder's coding may be:

Start recording macros using the macro recorder.


Select the Page Layout Page Setup Orientation Landscape command from the Page
Layout Page Setup Orientation Landscape menu.
Disconnect the macro recorder.
Activate the Module1 sheet to examine the macro. The following code is generated by this single
(and extremely easy) command:
Sub Macro1()
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.PrintTitleRows = ""
.PrintTitleColumns = ""
End With
Application.PrintCommunication = True
ActiveSheet.PageSetup.PrintArea = ""
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = ""
.RightHeader = ""
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = ""
.LeftMargin = Application.InchesToPoints(0.7)
.RightMargin = Application.InchesToPoints(0.7)
.TopMargin = Application.InchesToPoints(0.75)
.BottomMargin = Application.InchesToPoints(0.75)
.HeaderMargin = Application.InchesToPoints(0.3)
.FooterMargin = Application.InchesToPoints(0.3)
.PrintHeadings = False
.PrintGridlines = False
.PrintComments = xlPrintNoComments
.PrintQuality = 600
.CenterHorizontally = False
.CenterVertically = False
.Orientation = xlLandscape
.Draft = False
.PaperSize = xlPaperLetter
.FirstPageNumber = xlAutomatic
.Order = xlDownThenOver
.BlackAndWhite = False
.Zoom = 100
.PrintErrors = xlPrintErrorsDisplayed
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
.ScaleWithDocHeaderFooter = True
.AlignMarginsHeaderFooter = True
.EvenPage.LeftHeader.Text = ""
.EvenPage.CenterHeader.Text = ""
.EvenPage.RightHeader.Text = ""
.EvenPage.LeftFooter.Text = ""
.EvenPage.CenterFooter.Text = ""
.EvenPage.RightFooter.Text = ""
.FirstPage.LeftHeader.Text = ""
.FirstPage.CenterHeader.Text = ""
.FirstPage.RightHeader.Text = ""
.FirstPage.LeftFooter.Text = ""
.FirstPage.CenterFooter.Text = ""
.FirstPage.RightFooter.Text = ""
End With
Application.PrintCommunication = True
End Sub
The quantity of code created by this one command may surprise you. (It was the first time I
attempted anything like this.) Excel created code that updated several other print-related
parameters even though you only changed one print option.
This is an excellent example of macro-recording excess. This speeds up the macro and makes it
much simpler to read. After removing the unnecessary lines, this is how the macro looked:
Sub Macro1()
With ActiveSheet.PageSetup
.Orientation = xlLandscape
End With
End Sub
Except for the line that sets the Orientation property, I removed all of the code. Actually, you can
make this macro even simpler by omitting the With-End With construct (which I discuss in more
detail in Chapter 14):
Sub Macro1()
ActiveSheet.PageSetup.Orientation = xlLandscape
End Sub
In this scenario, the macro modifies the PageSetup object's Orientation property. The rest of the
properties remain the same. xlLandscape, by the way, is a built-in constant that makes your code
more readable. Because this constant has a value of 2, the following sentence is equivalent (but
not as simple to read):
ActiveSheet.PageSetup.Orientation = 2
Keep an eye out for updates. In Chapter 7, I go through built-in constants.
Instead of recording this macro, you may just type it into a VBA module. You'll need to know
which objects, attributes, and methods to employ in order to accomplish so. Despite the fact that
the recorded macro isn't perfect, recording it reveals that the PageSetup object is housed inside a
Worksheet object and that the PageSetup object contains an Orientation attribute. You can create
the macro yourself using this information and a short trip to the Help system (and maybe some
experimenting).
When it comes to utilizing the macro recorder, this chapter pretty well wraps it all. Experience is
the only thing that's lacking. After some time, you'll figure out which recorded remarks you may
safely remove. Even better, you'll learn how to tweak a pre-recorded macro to make it more
helpful.

PART THREE
PROGRAMMING CONCEPT
CHAPTER SEVEN

ESSENTIAL VBA LANGUAGE ELEMENTS


VBA utilizes many characteristics that are normal to all programming languages since it is a
genuine, functioning programming language. Several of these pieces are introduced in this
chapter: comments, variables, constants, data types, arrays, and a few more delights. Some of
this content will be recognizable if you've coded in other languages. It's time to roll up your
sleeves and get to work if you're new to programming.
Making Use of Comments in VBA Code
The most basic sort of VBA statement is a comment. Because VBA ignores these statements,
you may put anything you want in them. You may add a note to remind yourself why you did
something or to explain some exceptionally exquisite code you've written
To explain what the code does, it uses comments freely and extensively. Frequently, it makes
perfect sense that today befuddles you the next day. I've been there. That was completed.
An apostrophe (') is utilized to start a remark. Any content after an apostrophe in a line of code is
ignored by VBA. You may either use a whole line for your remark or add it at the end of a line
of code.

A VBA procedure with four comments is shown in the following example:


The "apostrophe denotes a comment" rule has one exception: an apostrophe within a set of
quotation marks is not interpreted as a comment indication by VBA. Even though it contains an
apostrophe, the following sentence does not include a comment:
Msg = "Can't continue"
You may wish to test a process by omitting a certain statement or collection of statements while
developing code. The statements might be deleted and then retyped afterward. That, however, is
a waste of time. A better method is to simply use apostrophes to transform those statements into
comments. When running a routine, VBA rejects statements that start with an apostrophe.
Simply remove the apostrophes to reactivate those "commented" statements.
A fast technique to convert a block of statements to comments is as follows. To see the Edit
toolbar, go to View Toolbars Edit. Select the statements you want to convert to comments and
pick the Comment Block button. Select the statements and pick the Uncomment Block button to
remove the apostrophes.
Everyone develops their own unique commenting style. Comments, on the other hand, should
provide information that isn't immediately apparent from reading the code.
The following suggestions will assist you in making effective use of comments:

Declare yourself to be the author. This will come in handy if you are promoted and
the person who replaces you has some inquiries.
Describe the goal of each Sub or Function operation you write in a few sentences.
To know about the modifications, you make to a process, use comments.
To indicate that you're utilizing a function or construct in an uncommon or
nonstandard way, add a remark.
If you don't use sensible variable names, use comments to explain the variables
you're using.
Make a comment to discuss any solutions you come up with to get around Excel
problems.
Instead of postponing the work for a later phase, write comments as you create the
code.
Consider adding a joke or two as a remark, depending on your workplace. When
you are promoted, the person who takes over your position could appreciate your
wit.

Using Variables, Constants, and Data Types


The primary goal of VBA is to manipulate data. VBA saves the information in your computer's
memory, and it may or may not be saved to disk. Objects hold some data, such as worksheet
ranges. Other information is saved in variables you define.
What are VBA’s data types?
When I say data type, I'm talking about how a program keeps data in memory, such as integers,
real numbers, or strings. Although VBA can handle these details for you automatically, it comes
at a price. (There is no such thing as a free lunch.) Allowing VBA to handle your data entry
causes slower execution and wasteful memory use. In most cases, this isn't a significant issue for
tiny applications. However, you must be knowledgeable about data types if you are developing
big or sophisticated programs that are likely to be sluggish or use every last byte of memory.
VBA takes care of all the data details automatically, making programmers' lives simpler. This is
not a feature available in all programming languages. Some languages, for example, are tightly
typed, requiring the programmer to indicate the data type for each variable.
VBA comes with a number of built-in data type.
Declaring and scoping variables
You should have a basic understanding of variables and data types if you've read the preceding
sections. You'll learn how to define a variable as a specific data type in this section.
If a variable is of the Variant data type and includes a text string that seems to be a number (such
as "143"), you may use it for both string manipulation and numeric computations. VBA does the
conversion for you. Allowing VBA to handle data types may appear to be a quick fix, but keep in
mind that you'll lose speed and use more memory.
It's a good idea to declare your variables — that is, tell VBA what data type each variable is —
before using them in a procedure. Declaring variables allows your macro to execute quicker and
more effectively utilize memory. A variant is the default data type, which leads VBA to run
time-consuming checks and reserve more memory than is required. If VBA knows the data type
of a variable, it won't have to look into it and can just set aside enough memory to store the data.
Include these two words as the first statement in your VBA module to force yourself to declare
all the variables you use:
Option Explicit
You won't be able to execute your code if it has any undeclared variables if this statement is
present.
Option Explicit is only used once: at the start of your module before any procedures are declared.
Remember that the Option Explicit statement only applies to the module in which it is found. If
you have more than one VBA module in a project, you require an Option Explicit statement for
each module.
Assume you're working with an undeclared variable (a Variant) called CurrentRate. At some
point in your procedure, you append the following statement:
CurentRate =.075
The variable name is misspelled (it lacks an r) and might be difficult to recognize. When you
don't detect it, Excel will treat it as a distinct variable, and your routine will most likely provide
inaccurate results. If you start your module with Option Explicit (which forces you to specify the
CurrentRate variable), Excel will raise an error if it sees a misspelled variant of that variable.
Turn on the Require Variable Definition option to guarantee that the Option Explicit statement is
included automatically whenever you introduce a new VBA module. It's on the Editor tab of the
Options dialog box (select Tools Options in the VBE). I strongly advise you to do so.
Declaring your variables also allows you to take advantage of a typing shortcut. Simply input the
variable name's first two or three characters, then hit Ctrl+space. If the option is uncertain, the
VBE either completes the entry for you or displays a selection of matching terms for you to pick
from. This clever method also works with reserved words and functions. An example of how this
works is shown in the image.

You now understand the benefits of defining variables, but how do you go about doing it? The
most typical technique is to utilize a Dim statement.
Here are some instances of defined variables:
Dim YourName As String
Dim January_Inventory As Double
Dim AmountDue As Double
Dim RowNumber As Long
Dim X
The first four variables have a specific data type declared for them. Because the final variable, X,
isn't declared as a data type, it's treated as a Variant (it can be anything).
In addition to Dim, VBA supports three other keywords for declaring variables:

Static
Public
Private
Later, I'll discuss the Dim, Static, Public, and Private keywords, but first, I'll go over two other
subjects that are pertinent here: the scope of a variable and the life of a variable.
A workbook can contain as many VBA modules as it wants, and each VBA module may have as
many Sub and Function operations as it wants. The scope of a variable specifies which modules
and methods may utilize it.

Procedure-only variables
The procedure level is the lowest level of scope for a variable. Variables defined with this scope
may only be utilized in the procedure in which they are declared. (A procedure is either a Sub or
a Function procedure.) When the operation is completed, the variable is removed from the
equation (it is sent to the great huge bucket in the sky), and Excel frees up memory. The variable
comes back to life if you run the procedure again, but its prior value is gone.
A Dim statement is the most popular approach to defining a procedure-only variable. The term
"dim" does not relate to the VBA creators' mental abilities. Rather, it's a programming word that
stands for dimension and simply signifies that you're allocating memory for a certain variable.
Dim statements are usually placed after the Sub or Function statement and before the procedure's
code.
The following example uses Dim statements to define procedure-only variables:
Sub MySub()
Dim x As Integer
Dim First As Long
Dim InterestRate As Single
Dim TodaysDate As Date
Dim UserName As String
Dim MyValue
' … [The procedure’s code goes here] …
End Sub
The final Dim command in the above example does not specify a data type for the MyValue
variable; instead, it just declares the variable. As a result, the variable MyValue is now a Variant.
Other procedures in the same module may use the same variable name if you declare it with
procedure-only scope, but each instance of the variable is unique to its own procedure. Variables
declared at the procedure level are the most efficient in general since VBA frees up the memory
they use after the process is completed.
Module-only variables
You may want a variable to be accessible to all operations in a module at times. If this is the
case, just define the variable. The graphic depicts how to tell whether you're in the Declarations
section. Go straight to the Declarations section using the right-hand drop-down option. Do not
collect $200 and do not pass Go.

Assume you wish to define the CurrentValue variable so that it's accessible to all of your
module's functions. Simply put, under the Declarations section, use the Dim statement:
Dim CurrentValue As Double
The CurrentValue variable may be accessed from any other procedure inside the module with
this declaration in place — and in the right location — and it preserves its value from one
method to the next.
Public variables
If you need to make a variable accessible to all methods in all of your VBA modules in a
workbook, use the public keyword to declare the variable at the module level (in the Declarations
section). Here's an illustration:
Public CurrentRate as Long
The CurrentRate variable is accessible to every operation in the worksheet, even those in other
VBA modules, thanks to the public keyword. You must define a variable as Public and create a
reference to the workbook that includes the variable declaration if you want it to be accessible to
modules in other workbooks.
In VBE, use the Tools References command to create a reference. Sharing a variable between
workbooks is almost never done in reality. In fact, in my whole VBA programming experience,
I've never done it. But it's good to know that it's possible in case it ever comes up on Jeopardy!
question.
Static variables
The Static keyword is used to define static variables, as seen in the following example:
Sub MySub()
Static Counter as Integer
Dim Msg as String
Counter = Counter + 1
Msg = "Number of executions: " & Counter
MsgBox Msg
End Sub
The code maintains track of how many times the process has been run and presents that
information in a message box. The Counter variable's value is not reset after the operation is
completed, but it is reset when the workbook is closed and reopened.
Even if the value of a Static variable is preserved when a variable expires, it is not accessible to
other operations. The Counter variable and its value are only accessible inside the My Sub
method in the previous example. It's a procedure-level variable, in other words.
Life of variables
Variables, like nothing else, do not live indefinitely. The scope of a variable influences not just
where the variable may be used, but also when it is withdrawn from memory.
There are three techniques for removing all variables from memory:
Reset the toolbar by clicking the Reset button (the little blue square button on the Standard
toolbar in the VBE).
When a runtime error message dialog box appears, click End.
Include an End statement in your code at any point. This differs from an End Sub or End
Function statement.
When the macro code has finished executing, only procedure-level variables will be deleted from
memory. Between runs of your code, static variables, module-level variables, and global (public)
variables all keep their values.
If you utilize module- or global-level variables, double-check that they contain the values you
intend. You never know whether one of the scenarios I just described resulted in your variables
losing their information!
Working with constants
During the execution of your procedure, the value of a variable may (and generally does) change.
The Const statement is used to define constants, as seen in the examples below. The constant's
value is also included in the declaration statement:
Const NumQuarters As Integer = 4
Const Rate = .0725, Period = 12
Const ModName As String = "Budget Macros"
Public Const AppName as String = "Budget Application"
It is a good programming practice to use constants instead of hard-coded values or strings. If
your method has to refer to a certain variable (such as an interest rate) numerous times, designate
the value as a constant and refer to the name of the constant rather than the value. Your code will
be more readable and changeable as a result of this. You simply have to modify one statement
rather than numerous if the interest rate changes.
Constants, like variables, have a range of use. Keep the following things in mind:
Declare a constant after the procedure's Sub or Function statement to make it accessible
exclusively inside that procedure.
Declare a constant in the module's Declarations section to make it accessible to all methods in
the module.
Use the Public keyword and declare a constant in the Declarations section of any module to
make it accessible to all modules in the workbook.
The value of a constant, unlike that of a variable, does not change. You'll receive an error if you
try to alter the value of a constant in a VBA procedure. This isn't unexpected since a constant's
value must stay constant. A variable is what you need if you need to modify the value of a
constant while your code is executing.
Using Premade Constants
Many preset constants are available in Excel and VBA, so you don't have to declare them
yourself. To use these constants, it is not mandatory to know their values in general. To modify
the Calculation property of the Application object (in other words, to change the Excel
recalculation mode to manual), use the following simple method, which utilizes a built-in
constant (xlCalculationManual):
Sub CalcManual()
Application.Calculation = xlCalculationManual
End Sub
By recording a macro while changing the calculation mode, I uncovered the
xlCalculationManual constant.
Youmight have also checked in the Help system and discovered the following:

As a result, the xlCalculationManual constant's real value is –4135. It's obviously simpler to
remember the constant's name than to recall such a strange number. Many of the built-in
constants, as you can see, are merely arbitrary integers with a specific significance to VBA.
Ctrl + G will bring up the Immediate window if it isn't visible. The question mark may be used as
a shortcut for the word Print.
Working with strings
Excel can operate with numbers as well as text, so it's no surprise that VBA can do the same. A
string is a term used to describe the text.
In VBA, you may deal with two sorts of strings: Strings having a fixed length are defined by
the number of characters they include. The maximum number of characters is 65,526. That's a lot
of people! As a comparison, this chapter has roughly half the number of characters.
Strings with variable lengths may potentially carry up to two billion characters. If you write at a
rate of 5 characters per second, it will take you 760 days to type 2 billion characters - assuming
you don't stop to eat or sleep.
You may set the maximum length of a string variable with a Dim statement if you know it (it's a
fixed-length string) or let VBA handle it dynamically (it's a variable-length string). The
MyString variable is declared as a string with a maximum length of 50 characters in the
following example. (Up to the 65,526-character maximum, use an asterisk to define the number
of characters.) YourString is likewise declared as a string, but its length is unspecified:
Dim MyString As String * 50
Dim YourString As String
When defining a fixed-length string with a length greater than 999, do not include a comma in
the string size number. In fact, when inputting a numeric number in VBA, never use commas.
That irritates VBA.
Working with dates
The date is another data type that you could find handy. You can keep dates in a string variable,
but you won't be able to conduct date computations. Your routines will be more flexible if you
use the Date data type. You may need to determine the number of days between two dates, for
example. If you utilized strings to keep your dates, this would be impossible (or at least highly
difficult).
Dates spanning from January 1, 0100 to December 31, 9999 may be stored in a variable
designated as a Date. That's approximately 10,000 years, which is more than enough time for
even the most optimistic financial estimate. You may also interact with time data using the Date
data type (VBA lacks a Time data type).
These examples use the Date data type to define variables and constants:
Dim Today As Date
Dim StartTime As Date
Const FirstDay As Date = #1/1/2016#
Const Noon = #12:00:00#
Place dates and times between two hash marks in VBA, as demonstrated in the samples above.
Date variables show dates in your system's short date format, while time variables display times
in your system's time format (either 12- or 24-hour formatting). These settings are stored in the
Windows Registry, and you may change them in the Windows Control Panel's Regional and
Language Settings dialog box. As a result, the date or time format presented by VBA may differ
based on the system settings on which the program is executing.
However, you must use one of the US date formats (such as mm/dd/yyyy) when creating VBA
code. So, even if your system is configured to use dd/mm/yyyyy for dates, the following line
assigns a day in October (not November) to the MyDate variable:
MyDate = #10/11/2016#
When you use the MsgBox function to display the variable, VBA uses your system settings to
display MyDate. MyDate is shown as 11/10/2016 if your system utilizes the dd/mm/yyyyy date
format.
Using Assignment Statements
A VBA statement that assigns the outcome of an expression to a variable or object is known as
an assignment statement. The word expression is defined in Excel's Help system as
... a text, integer, or object created by combining keywords, operators, variables, and constants.
A computation, character manipulation, or data testing may all be done using an expression.
In VBA, you'll spend a lot of time creating (and debugging) expressions. You won't have any
problem constructing expressions if you know how to write formulae in Excel. Excel shows the
outcome of a spreadsheet calculation in a cell. A variable may be assigned to a VBA expression,
on the other hand.
Examples of assignment statements
The expressions to the right of the equal sign are used in the following assignment
statement examples:
x=1
x=x+1
x = (y * 2) / (z * 2)
HouseCost = 375000
FileOpen = True
Range("TheYear").Value = 2016
Expressions may be as complicated as you need them to be; to make long expressions simpler to
understand, use the line continuation character (a space followed by an underscore).
Expressions often make use of functions, such as VBA's built-in functions, Excel's worksheet
functions, or custom VBA functions. In Chapter 9, I go through functions.
About that equal sign
As you can see in the prior example, VBA's assignment operator is the equal sign. An equal sign
is a mathematical symbol denoting equality that you're undoubtedly familiar with.
As a result, an assignment statement like the one below may raise your eyebrows:
z=z+1
In what wacky universe is z equal to 1 plus itself? Answer: There is no such thing as a known
universe. In this scenario, when the assignment instruction is performed, the value of z is
increased by 1. If z is 12, then running the statement will change z to 13. Just keep in mind that
the equal sign is an operator, not a representation of equality, in an assignment.
Smooth operators
Operators are very important in VBA. VBA has a number of operators in addition to the equal-
sign operator (discussed in the previous section). These operators are listed in the illustration.
These are the same operators used in spreadsheet formulae, so you should be acquainted with
them (except for the Mod operator).
Working with Arrays
Array declarations
You must define an array before you can utilize it. There are no exceptions. Unlike normal
variables, VBA adheres to this rule very strictly. Just like a normal variable, you define an array
using a Dim or Public declaration. However, you must additionally define the array's size in
terms of elements. The first index number, the keyword To, and the last index number are all
specified inside parentheses.
The following example demonstrates how to declare a 100-item array:
Dim MyArray(1 To 100) As Integer
You have the option of specifying only the upper index when declaring an array. If you don't
include the lower index, VBA assumes it's zero. As a result, both of the lines below define the
identical 101-element array:
Dim MyArray (0 To 100) As Integer
Dim MyArray (100) As Integer
Include the following sentence in the Declarations section at the start of your module if you want
VBA to presume that 1 (rather than 0) is the lowest index for your arrays:
Option Base 1
For arrays that declare only the upper index, this statement forces VBA to use 1 as the first index
number. The following statements, both defining a 100-element array, are equivalent if this
declaration is present:
Dim MyArray (1 To 100) As Integer
Dim MyArray (100) As Integer
Multidimensional arrays
All of the arrays constructed in the preceding examples are one-dimensional. One-dimensional
arrays may be thought of as a single line of values. Arrays created in VBA may have up to 60
dimensions, however, most arrays only require two or three. The following example defines a
two-dimensional 81-integer array:
Dim MyArray (1 To 9, 1 To 9) As Integer
This array may be thought of as a 9 × 9 matrix, which is ideal for holding all of the numbers in a
Sudoku problem.
MyArray (3, 4)= 125
This statement gives a value to a single array element. If you think of the array as a 9 x 9 matrix,
this gives the element in the third row and fourth column of the matrix the value 125.
Here's how to define a 1,000-element three-dimensional array:
Dim My3DArray (1 To 10, 1 To 10, 1 To 10) As Integer
A three-dimensional array is similar to a cube. It's more difficult to see an array with more than
three dimensions. I'm afraid I haven't yet mastered the fourth and beyond dimensions.
Dynamic arrays
How to modify the number of items in a dynamic array is shown in the following example. It is
assumed that the NumElements variable contains a value that was calculated by your code.
ReDim MyArray (1 To NumElements)
When you use ReDim to redimension an array, you wipe out any values that are currently stored
in the array elements. By using the Preserve keyword, you can avoid destroying the old values.
The following example demonstrates how you can keep an array's values while resizing it:
ReDim Preserve MyArray (1 To NumElements)
If MyArray currently has ten elements and you run the preceding statement with NumElements
equal to 12, the first ten elements will be preserved, and the array will have room for two more
(up to the number contained in the variable NumElements). However, if NumElements = 7, the
first seven items are kept, but the last three elements are eliminated.
When I cover looping in Chapter 10, I bring up the subject of arrays once again.
Making Use of Labels
Every line of code in early versions of BASIC needed a line number. For example, if you had
written a BASIC program in the 1970s (while wearing bell-bottoms, of course) it might have
looked like this:
010: LET X=5
020: LET Y=3
030: LET Z=X*Y
040: PRINT Z
050: END
VBA allows for the usage of such line numbers, as well as text labels. You don't usually need a
label for each line, but you may need one on occasion. If you use a GoTo sentence, for example,
include a label (which I discuss in Chapter 10). A label must start with a nonblank character and
finish with a colon.
As you go through the chapters, the information in this one becomes clearer. I recommend the
VBA Help system if you wish to learn more about VBA language aspects. You can learn as
much as you want or need to know.
CHAPTER EIGHT

WORKING WITH RANGE OBJECTS


Here, I delve a little deeper into Excel's dungeons and examine Range objects in greater detail. It
is a container for cells, and Excel is all about cells. What's the use of knowing so much about
Range objects? Because Range objects are used in so much of your Excel programming.
Referring to Range Objects
A Worksheet object's range is represented by a Range object. A Range object may be as tiny as a
single cell (such as B4) or as big as all 17,179,869,184 cells in a worksheet (A1:XFD1048576).
When the range has a name (which you can create in Excel using the Formulas Defined Names
Define Name command), it is referred by its name (which is also in quotes):
Range("PriceList")
Noncontiguous ranges are selected in Excel by pressing down the Ctrl key while choosing
several ranges with your mouse. The image depicts a range selection that is not contiguous. VBA
also allows you to work with noncontiguous ranges, which should come as no surprise. A two-
area noncontiguous range is denoted by the following phrase.
Range("A1:B8,D9:G16")
Be cautious that noncontiguous ranges might wreak havoc with certain methods and attributes.
You may have to utilize a loop to handle each section independently.
Referring to a Range Using Properties
The more you use VBA, the more you realize it's a well-thought-out language that's usually quite
logical (despite what you may be thinking right now). VBA often presents numerous options for
doing a task. You have the option of selecting the best solution for your problem.
You'll probably need to access additional properties as you work with VBA. The best place to
learn about them is in the Help system, but it's good to keep track of your actions and examine
the code Excel generates. You're probably sick of hearing that advice by now, but it's sound
advice nonetheless.
The Cells property
Instead of using the VBA Range keyword, you can use the Cells property to refer to a range.
It's worth noting that I wrote Cells property rather than Cells object or Cells collection. Cells
may seem to be an object (or a collection), but it is not. Cells, on the other hand, are a property
that VBA evaluates. The object is then returned by VBA (more specifically, a Range object).
Don't be concerned if this appears strange. Even Microsoft appears to be perplexed by the
situation. The Cells property was formerly known as the Cells method in various Excel versions.
Whatever it is, remember that Cells are a convenient way to refer to a range.
The Cells property is used to refer to a multi-cell range. The syntax is demonstrated in the
following example:
Range(Cells(1, 1), Cells(10, 8))
From cell A1 (row 1, column 1) to cell H10, this expression relates to an 80-cell range (row 10,
column 8).
Both of the following phrases yield the same result: a value of 99 is entered into a 10-by-8 range
of cells. These statements, in particular, set the Range object's Value property:
Range("A1:H10").Value = 99
Range(Cells(1, 1), Cells(10, 8)).Value = 99
When you use variables instead of actual numbers as the Cells arguments, the advantage of using
the Cells property to refer to ranges becomes clear. And once you grasp looping, which I explain
in Chapter 10, things start to fall into place.
The Offset property
The Offset property is yet another useful way to refer to ranges. You may refer to a cell that is a
certain number of rows and columns distant from another cell using this property, which acts on
a Range object and returns another Range object.
This property takes two properties:
Range("C2").Offset(-1, -2)
The time of day is inserted into the cell to the right of the present cell with the statement below:
ActiveCell.Offset(0,1) = Time
Excel makes extensive use of the Offset property when recording a macro in relative mode. For
an example, see Chapter 6.
When using variables instead of real values for the parameters, the Offset property comes in
handy. I demonstrate this in Chapter 10 with some examples.
Working with Range Properties
There are hundreds of attributes on a Range object. For the next 12 months, you could build
VBA applications incessantly and never utilize them all. I'll go through some of the most often
utilized Range attributes in this section. Consult the VBE's Help system for further information.
Some Range attributes are read-only, which implies that your code may inspect but not modify
them. You can read but not update this read-only attribute, which makes perfect sense when you
think about it.
By the way, rather than comprehensive methods, the examples that follow are usually assertions.
Furthermore, several of these assertions are only valid if the current page is a worksheet.
The Value property
A cell's value is represented via the Value attribute. The following statement presents the value
in cell A1 on Sheet1 in a message box:
MsgBox Worksheets("Sheet1").Range("A1").Value
The Value attribute can only be read for a single-cell Range object, as one would expect.
A Range object's default attribute is Value. To put it another way, if you don't provide a property
for a Range, Excel defaults to its Value property.
Both of the following statements put a 75 in cell A1 of the current worksheet:
Range("A1").Value = 75
Range("A1") = 75
The Text property
The Text property produces a string that reflects the formatted value of the text as it appears in a
cell. Text is a read-only attribute.
However, the following sentence produces a message box with 12.3:
MsgBox Worksheets("Sheet1").Range("A1").Value
It delivers the formula's result if the cell has one. Because text (unlike numbers) cannot be
formatted to show differently, the Text and Value properties always return the same value when
a cell includes text.
The Font property
A property may return an object, as I mentioned before in this chapter (see "The Cells property").
Another example of this principle in action is the Font attribute of a Range object.
The Font object's Bold attribute is then set to True. This sentence displays the cell in boldface in
plain English:
Range("A1").Font.Bold = True
It will function properly as long as you use the correct syntax. Often, documenting your activities
while writing a macro will reveal everything you need to know about appropriate syntax.
More information about recording macros may be found in Chapter 6.
The Interior property
Another property that returns an object may be found here. The Interior property of a Range
object yields an Interior object (odd name, but that's what it's called). This form of an object
reference is similar to how the Font property works (which I describe in the preceding section).
For instance, the following sentence modifies the Color property of the Range object's
Interior object:
Range("A1").Interior.Color = 8421504
To put it another way, this sentence sets the background of the cell to middle gray. What exactly
is it? 8421504 is intermediate gray, in case you didn't know. See the adjoining sidebar "A quick-
and-dirty color primer" for some insights into Excel's beautiful world of color.
The Formula property
The formula in a cell is represented by the Formula property. It's important to note that the
formula is a text string contained in quotation marks. Also, like with other formulae, the formula
starts with an equal sign.
Things become a little more complicated if the formula incorporates quote marks.
Assume you wish to use VBA to input the following formula:
=SUM(A1:A12)&" Stores"
The word Stores is shown after the value in this formula. Otherwise, VBA becomes perplexed
and reports that a syntax error has occurred (which it does!).
By the way, even if a cell doesn't contain a formula, you may access its Formula property.
Keep in mind that VBA "speaks" American English. This implies that you must use US syntax to
enter a formula into a cell. Read up on the FormulaLocal property if you're using an Excel
version that isn't in English.
The Number Format property
To view a list of different number formats, follow these instructions (better yet, switch on
the macro recorder while you're at it):

Make a worksheet active.


Ctrl+1 will bring up the Format Cells dialog box.
Toggle to the Number tab.
To see and use some other number format strings, go to the Custom category.

Using Range Object Methods to Take Action


The Select method
To choose cell ranges, use the Select technique. The sentence below picks a range in the
current worksheet:
Range("A1:C12").Select
It's a good idea to use one more statement before picking a range to guarantee that the right
worksheet is active. If Sheet1 includes the range you wish to choose, for example, use the
following lines to do so:
Sheets("Sheet1").Activate
Range("A1:C12").Select
The following sentence, contrary to popular belief, throws an error if Sheet1 is not currently the
active sheet. To put it another way, instead of using only one sentence, you'll need two: one to
activate the sheet and another to pick the range.
Sheets("Sheet1").Range("A1:C12").Select
You may forget about picking the proper worksheet first if you use the GoTo method of the
Application object to choose a range. Sheet1 is activated by this statement, which then picks the
range:
Application.Goto Sheets("Sheet1").Range("A1:C12")
The GoTo method in VBA is the equivalent of hitting F5 in Excel to bring up the GoTo dialog
box.
The Copy and Paste methods
The Copy and Paste methods in VBA may be used to conduct copy and paste tasks. It's worth
noting that two separate items are involved. This little macro (thanks to the macro recorder)
duplicates the range A1:A12 and pastes it into the same worksheet, starting at cell C1:
Sub CopyRange()
Range("A1:A12").Select
Selection.Copy
Range("C1").Select
ActiveSheet.Paste
End Sub
The ActiveSheet object is utilized with the Paste method in the prior example. This is a particular
form of the Worksheet object that refers to the worksheet that is presently active. It's also worth
noting that the macro first pick the range to duplicate before copying it. You do not, however,
required to choose a range before working with it. In reality, by utilizing a single statement, the
following approach performs the same objective as the prior example:
Sub CopyRange2()
Range("A1:A12").Copy Range("C1")
End Sub
This function makes use of the Copy method's ability to utilize an argument that corresponds to
the copy operation's target range. You may find out more about this by consulting the Help
system.
The Clear method
The Clear method clears a range's contents as well as any cell formatting. You should be aware
of two approaches that are connected. The ClearContents method removes the range's contents
but keeps the formatting. The Clear Formats function removes the range's formatting but not the
contents of the cells.
The Delete method
Clearing a range is not the same as removing a range. When you eliminate a range, Excel
rearranges the remaining cells to fill in the empty space.
For row 6, check below
Rows("6:6").Delete
Excel needs the knowledge on how to relocate the cells when you delete a region that isn't a
whole row or column. (Experiment with Excel's Home Cells Delete. Then, Delete Cells
command to see how this works.)
The following sentence eliminates a range and then fills in the gap by moving the remaining cells
to the left:
Range("C6:C10").Delete xlToLeft
The Delete function takes an argument that tells Excel how to rearrange the remaining cells.
CHAPTER NINE
USING VBA AND WORKSHEET FUNCTIONS
I mentioned in earlier chapters that you may utilize functions in your VBA expressions. There
are three types of functions: those included with VBA (vanilla), those included with Excel
(strawberry), and additional VBA-written functions (chocolate). In this chapter, I provide a
thorough and delectable explanation. With little or no programming work, functions may help
your VBA code execute some impressive things. This chapter is for you if you enjoy the concept.
Understanding Functions
Except for a few individuals who mistake Excel for a word processor, all Excel formulae use
worksheet functions. The SUM function is the most frequent spreadsheet function, but you have
access to over 500 others.
VBA functions may originate from three different places:

VBA provides built-in functions.


Excel has a lot of worksheet features.
VBA-based custom functions written by you (or someone else).

Using VBA's Built-In Functions


VBA has a lot of built-in features. Some of these routines will accept parameters, while others
will not.
Examples of VBA functions
In this part, I'll show you how to use VBA functions in code.
VBA functions that do more than return a value
A few VBA routines go above and beyond what is required. These functions do more than just
return a result; they also have some beneficial side effects.
The following are the functions:
MsgBox
The method returns a code that indicates which button was clicked by the user. For further
information, see Chapter 15.
InputBox
This shows a basic dialog box that requests input from the user.
Shell
Runs a different software. The method returns the other program's task ID (a unique identifier)
(or an error if the function is unable to start the other application).
Using Worksheet Functions in VBA
Although VBA has a large number of built-in functions, you may not always be able to locate
precisely what you need. Fortunately, most Excel worksheet functions may also be used in VBA
operations. You can't use Excel's RAND function since VBA has a function that does similar
things: Rnd.
Either the Application or WorksheetFunction parts of the phrase might be omitted. VBA will
figure out what you're doing in any situation. To put it another way, these three phrases all do a
similar thing:
Total = Application.WorksheetFunction.SUM(Range("A1:A12"))
Total = WorksheetFunction.SUM(Range("A1:A12"))
Total = Application.SUM(Range("A1:A12"))
To make it quite apparent that the code is utilizing an Excel function, I like to utilize the
WorksheetFunction parameter.
Worksheet Functions Examples
I'll show you how to utilize worksheet functions in VBA expressions in this part.
Determining the highest value in a range
An example of how to utilize Excel's MAX worksheet function in a VBA method can be found
here.

The MIN function may be used to find the smallest number in a range. You may also utilize
additional functions in a similar way, as you would assume.
SecondHighest = WorksheetFunction.LARGE(Range("A:A"),2)
It's worth noting that the LARGE function has two parameters.
Entering worksheet functions
You can't paste a worksheet function into a VBA module using the Excel Paste Function dialog
box. Instead, use the old-fashioned method of entering such functions by hand.
You may also use the Auto List Members option in the VBE, which shows a drop-down list of
all worksheet functions. Simply write Application.WorksheetFunction into the search box.
Then, as indicated in the picture, you'll see a list of the functions you may utilize. If this function
isn't working, go to Tools Options in the VBE, pick the Editor tab, and check the box next to
Auto List Members.

More about using worksheet functions


VBA's built-in functions are often confused with Excel's workbook functions by newcomers to
the language. Most worksheet functions that aren't provided as WorksheetFunction object
methods may be replaced with a VBA built-in operator or function. The MOD worksheet
function, for example, is not accessible in the WorksheetFunction object since VBA has a built-
in equivalent: the Mod operator.
Using Custom Functions
Custom functions are the third kind of function you may utilize in your VBA processes. It is one
that you create yourself using Visual Basic for Applications (VBA). To utilize a custom function,
you are to declare it in the worksheet where it will be utilized, or define it in an add-in (see
Chapter 21).
MultiplyTwo is a custom function that consists of two parameters. Its procedure is used by the
ShowResult Sub procedure, which passes two parameters to it (in parentheses). The
MultiplyTwo method returns a value, which the ShowResult operation displays in a message
window.
The multiplication may be done in the ShowResult Sub method, which is significantly more
efficient. It's just included to show you how a Subprocess may make use of a custom function.
Custom functions may also be used in spreadsheet formulae. If MultiplyTwo is specified in your
workbook, for example, you may construct a formula like this:
=MultiplyTwo(A1,A2)
The product of the values in cells A1 and A2 is returned by this formula.
The issue of creating custom worksheet functions is significant (and really handy). I dedicate a
full chapter to it since it is so essential (and beneficial).
CHAPTER TEN
CONTROLLING PROGRAM FLOW AND MAKING
DECISIONS
Some VBA processes begin from the beginning of the code and advance line by line to the
finish, never breaking from the program's top-to-bottom flow. This is how all macros you record
function. However, in many circumstances, managing the flow of your code is important and you
can do so by skipping certain lines, running some statements several times, and checking
conditions to figure out what the method should do next. Keep your hat on and enjoy the
journey, because you're going to learn the fundamentals of programming.
Going with the Flow, Dude
Some newcomers to programming are baffled as to how a stupid machine can make clever
judgments. The key lies in a number of programming constructs that are supported by almost all
computer languages. The picture shows a sneak peek at these structures.

The GoTo Statement


In general, you should only utilize GoTo when you don't have any other options. The only time
you'll need to use a GoTo statement in real life is to catch mistakes.
By the way, I'm demonstrating the GoTo statement using the CheckUser method. It's not
supposed to be a demonstration of a good security approach!
Many hard-core programmers despise GoTo statements because they produce difficult-to-read
(and difficult-to-maintain) "spaghetti code." When speaking with other programmers, you should
never confess to using GoTo statements.
WHAT IS STRUCTURED PROGRAMMING? DOES IT MATTER?
If you hang around with programmers long enough, you'll hear the phrase structured
programming at some point. This concept has been around for a long time, and most
programmers think that structured programs are preferable to unstructured ones. So, what exactly
does structure programming entail? Is it possible to achieve this using VBA?
A procedure or code section should only have one entry point and one exit point, according to
the fundamental assumption of structured programming. To put it another way, a code block
should be self-contained. A program cannot enter this unit in the middle, nor can it depart at any
point other than the single exit point. When you create structured code, your program advances
in a logical and easy-to-follow way, as opposed to a program that leaps about haphazardly. This
effectively eliminates the need for the GoTo statement.
An organized program is often simpler to read and comprehend. What's more, it's a lot simpler to
change when the need comes.
VBA is a structured programming language. If-Then-Else, For-Next loops, Do-Until loops, Do-
While loops, and Select Case structures are among the commonly structured constructions
available. Furthermore, modular code constructs are completely supported. If you're new to
programming, aim to establish strong structure-programming practices as soon as possible. The
lecture has come to an end.
Decisions, Decisions
Effective decision-making is the key to success in designing Excel macros, as it is in many other
facets of life. If this book has the desired impact, you'll quickly understand why I believe that a
great Excel application comes down to making choices and acting on them.
In this part, I'll go over two programming structures that may provide your VBA functions a lot
of decision-making power: If-Then and Select Case are two types of conditional logic.
An If-Then-Else example
The Else clause may be used to solve the previous issue in a different way.
The identical method has been rewritten to utilize the If-Then-Else structure:
In the above example, you'll see that I used the line continuation character (underscore). In
reality, the If-Then-Else sentence is a single statement. If-Then-Else structures that employ an
End If statement is coded in a slightly different manner in VBA. As a result, the GreetMe
method might be renamed
In fact, you may put as many statements in the If portion as you want, and as many assertions in
the Else part as you like. This style is my preferred method since it is simpler to understand and
makes the sentences shorter.
What if you require the GreetMe routine to cover three different scenarios: morning, afternoon,
and evening? You may choose between two options: Use a nested If-Then-Else structure or three
If-Then statements. The first method, which employs three If-Then statements, is the simplest:
Depending on the time of day, the Msg variable receives a varied text value. The greeting is
shown using the MsgBox statement: Good Morning, Good Afternoon, or Good Evening.
The following method, which employs an If-Then-End If structure, does the same task:
Using ElseIf
Every line in the routine is performed in the preceding instances, even in the morning. If
confirmed that a condition is true, a little more efficient structure would leave the procedure.
The process should, for example, show the Good Morning message in the morning and then quit
— without considering the other needless requirements.
You don't have to worry about execution speed with a little routine like this. However, you
should be aware of alternative syntax for the If-Then structure if you're working on bigger
projects where performance is crucial.
Here's how you use this syntax to work on the GreetMe routine:
VBA performs the conditional statements when a condition is confirmed to be true, and the If
structure is terminated. In other words, VBA doesn't spend time examining the non-essential
conditions, making this operation a little faster than the previous ones. The trade-off is that the
code is harder to comprehend (there are always trade-offs). (Of course, you were aware of this.)
Another If-Then example
This procedure executes each If-Then statement, and the value for Discount might vary as the
statements are performed. However, since I ordered the If-Then lines in increasing Discount
values, the program eventually shows the right amount for Discount.
Using the alternative ElseIf syntax, the following technique accomplishes the same things. I find
these many If-Then constructs to be pretty inconvenient. Only for basic binary judgments do I
utilize the If-Then structure.
The Select Case structure
An example of a Select Case
This demonstrates a different approach to coding the examples from the previous section:
The Quantity variable is being evaluated in this case. The routine looks for four distinct scenarios
(0–24, 25–49, 50–74, and 75 and above).
Each Case statement may have any number of statements after it, and all of them will be
performed if the case is true. If you just have one statement, like in this example, you may place
it on the same line as the Case keyword, separated by a colon, which is the VBA statement
separator character. This, in my perspective, makes the code a little more concise and
understandable.
In this format, the procedure looks like this:
When VBA runs a Select Case structure, it exits as soon as the structure discovers a true case and
executes the statements for that case.
A nested Select Case example
This method looks at the active cell and displays a message that describes the contents of the
cell.
There are three Select Case structures in the process, each with its own End Select
statement:
You may layer Select Case structures as deep as you like, but each Select Case statement must be
followed by an End Select statement.
If you're still not persuaded that indenting code is worthwhile, the preceding example is an
excellent place to start. The indentations are there to let you see where you're nesting (at least I
think so). If you don't trust me, consider the following process without the indentation.
Knocking Your Code for a Loop
The phrase looping refers to repeatedly running a set of VBA commands. Why are loops used?
There are a few explanations that come to mind.
HOW FAST ARE LOOPS?
You may be interested in how quickly VBA can execute If-Then loops. Is it true that certain
systems execute code quicker than others? I put the following VBA technique on my website a
few years ago and invited others to share their results:
Sub TimeTest()
'100 million random numbers, tests, and math operations
Dim x As Long
Dim StartTime As Single
Dim i As Long
x=0
StartTime = Timer
For i = 1 To 100000000
If Rnd <= 0.5 Then x = x + 1 Else x = x - 1
Next i
MsgBox Timer - StartTime & " seconds"
End Sub
Inside the loop, the code loops 100 million times and performs the following operations: It
creates an arbitrary number, then does an If-Then comparison and a mathematical calculation.
The elapsed time is shown in the box after the loop is completed. This loop took my system 8.03
seconds to complete. Around 150 additional people shared their findings, with timings ranging
from 2 to 30 seconds. To put it another way, some computers are 15 times as quick as others.
That's helpful to know.
By the way, on my newer machine, I reran the code. The time has now been reduced to 3.49
seconds.
But the actual question is how long it would take me to do this activity by hand. I flipped a coin
and scribbled 0 on a piece of paper. I added one to my total if the coin came out heads. I
deducted 1 if it came up tails. It took me 42 seconds to do this 10 times. As indicated in the
graphic, one pass through my "loop" took 4.2 seconds. Using this data, I determined that doing
this activity 100 million times would take me 13.3 years — but only if I worked continuously.
The end result is that my computer is 120 million times quicker than I am.
CHAPTER ELEVEN
AUTOMATIC PROCEDURES AND EVENTS
A VBA Sub operation may be run in a variety of methods. One option is to schedule the Sub to
run automatically. In this chapter, I walk you through the ins and outs of this potentially valuable
feature, showing you how to set things up such that a macro runs automatically when a certain
event happens. (No, this chapter isn't about the death penalty.)
Preparing for the Big Event
What kinds of occurrences am I referring to? That is an excellent question. In Excel, an event is
essentially anything that occurs.
The following are some instances of events that Excel may recognize:

It is possible to open or close a workbook.


It is possible to activate or deactivate a window.
It is possible to activate or deactivate a worksheet.
A cell is either filled with data or altered.
It is possible to save a workbook.
A click is made on an item.
A certain key or combination of keys is pushed.
A certain time of day.
An error has occurred.
The most often utilized events are discussed in this chapter. To keep things simple, I divide
occurrences into two categories: workbook events and worksheet events.
Are events useful?
You may be asking how these events might be beneficial at this stage. Here's a simple
illustration.
Assume there is a worksheet in which column A contains values. Your employer, who is a bit of
a control freak, insists on knowing precisely when each number was input. A
WorksheetChange event occurs when data is entered. You may reply to this event using a
macro. When the worksheet is modified, the macro is activated. If you make a modification in
column A, the macro adds the date and time to column B, next to the data point you supplied.
If you're wondering, here's what a macro like this might look like. Isn't it probably a lot easier
than you imagined?
Macros that react to events, by the way, are quite particular about where they are stored. This
Worksheet Change macro, for example, must be in the Code module for that worksheet. It won't
function if you put it anywhere else. I'll go into more detail about this later.
The presence of processes that react to events in your workbook does not ensure that they will be
carried out. As you may be aware, you may open a worksheet without macros enabled. All
macros (including procedures that react to events) are disabled in this situation. When creating
workbooks that depend on event-handler routines, keep this in mind.
Programming event-handler procedures
This is a VBA procedure that runs in response to an event. Subprocesses are always present (as
opposed to Function procedures). After you understand how the process works, writing these
event handlers is pretty simple.
There are just a few stages to creating event-handler procedures:

Determine the event that will start the operation.


To open the Visual Basic Editor, press Alt+F11.
Double-click the relevant item listed under Microsoft Excel Objects
This procedure will be given a unique name to distinguish it from other event-handler
procedures.
As you move through the text, these stages become obvious. Have faith in me.
Where Does the VBA Code Go?
It's critical to know where your event-handler routines are located. They must be located in an
Object module's Code window. They don't belong in a typical VBA module. It won't function if
you placed your event-handler method in the incorrect location.
The VBE window is shown, with one project open. (For further information on the VBE, see
Chapter 3.) It's worth noting that the VBA project for Book 1 has been completely enlarged and
now includes the following objects:

Each worksheet in the workbook has its own object (in this case, three Sheet
objects)
a labeled item This Workbook is for you.
A VBA module that I manually added using the Insert Module command.

Writing an Event-Handler Procedure


VBE automatically creates an event-handler method for you when you choose an event from the
list. This is a really handy feature since it informs you of the correct parameters.
Here's a peculiarity. VBE automatically assumes that you want to build an event-handler method
for the Open event when you first choose Workbook from the Object list and generate one for
you. That's OK if you're truly writing a Workbook Open process
However, VBE's assistance is limited. The Sub statement and the End Sub statement are written.
You don't have to utilize those two drop-down lists, but doing so makes your work simpler since
the event-handler procedure's name is vital. The method will fail if you don't spell the name
correctly. In addition, several event-handler routines employ the Sub statement with one or more
parameters. You're not going to be able to recall those arguments. If you choose SheetActivate
from a Workbook object's event list, VBE generates the following Sub statement:
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Triggering Workbook Events
In this part, I'll give you a few examples so you can get a feel for how this event-planning
company works.
The Open event for a workbook
When a workbook is opened, Workbook Open is called automatically. You could have a hard
time trying this technique if today isn't Friday. Simply alter the 6 to match the current day's
number.
Of course, you are free to alter this technique in any manner you see fit. The following version,
for example, shows a notification each time the worksheet is opened. This becomes grating after
a time, believe me.

A Workbook Open method may be used to do nearly any task. The following are common
uses for these event-handlers:

Putting up welcome messages (as in Frank's amazing workbook)


Changing to another workbook
Activating a specific worksheet inside a workbook
Creating your own shortcut menus
The GetSetting and SaveSetting methods are used in this last example of a Workbook Open
procedure to keep track of how many times the workbook has been accessed. The GetSetting
method retrieves a value written to the Windows registry by the SaveSetting function (see the
Help system for details).
The example below obtains the count from the registry, increases it, and then stores it. It also
informs the user of the Cnt value
The BeforeClose event for a workbook
The Workbook BeforeClose event-handler method, which is performed automatically just before
the workbook is closed, is shown below.

To clean up after themselves, Excel programmers often employ the Workbook BeforeClose
method. For example, if you use the Workbook Open process to modify certain settings when
you start a workbook (for example, concealing the status bar), it's only natural to restore those
settings after you shut the workbook. A Workbook BeforeClose method may be used to execute
this electronic housekeeping.
The BeforeSave event for a workbook
The BeforeSave event is triggered before a workbook is saved, as its name indicates. When you
use the File Save or File Save As commands, this event happens.
There are two parameters to the Workbook BeforeSave procedure: SaveAsUI and Cancel.
Examine the following macro, which is run before the worksheet is saved, to see how these
parameters function. This method tries to prevent the user from saving the workbook under a
different name. The SaveAsUI parameter is True if the user selects the File Save As command.
The SaveAsUI value is checked when the code runs.

It's worth noting that this approach won't stop someone from storing a duplicate under a different
name. If someone truly wants to do it, they may just open the worksheet without the macros
turned off. Event-handler procedures are disabled when macros are deactivated, which makes
sense since they are, after all, macros.
Using Activation Events
Activating and deactivating items like sheets and workbooks is another kind of occurrence.

Activate and Deactivate events in a sheet


Activate and deactivate events in a sheet Excel can detect when a certain sheet is active or
deactivated and run a macro when this happens. These event-handler routines are located in the
Sheet Object’s Code window.
By right-clicking the sheet's tab and choosing View Code, you may easily view the sheet's code
window.
When a certain sheet is active, the following example displays a basic operation that is run.
This code just shows the current sheet’s name in an obnoxious message box:

Another example is when the sheet is active, cell A1 is activated:


Private Sub Worksheet_Activate()
Range("A1").Activate
End Sub
Although the code in these two procedures is as basic as it gets, event-handler procedures may be
as complicated as you want them to be.
The Deactivate event is used in the code below to prohibit a user from activating any other sheet.
The user receives a notice and Sheet1 is enabled if Sheet1 is deactivated (that is, another sheet is
active).
Private Sub Worksheet_Deactivate()
MsgBox "You must stay on Sheet1"
Sheets("Sheet1").Activate
End Sub
By the way, I don't advocate employing methods that seek to take control of Excel, such as this
one. For the user, these so-called "dictator" programs may be very annoying and perplexing.
And, of course, deactivating macros is a simple way to thwart them. Rather, I urge that you teach
the user how to properly utilize your program.
Activating and deactivating events in a workbook
The above examples make use of events that are linked to a certain worksheet. Sheet activation
and deactivation events are similarly handled by the ThisWorkbook object. When any sheet is
active, the following method, which is contained in the Code window for the ThisWorkbook
object, is called. The code generates a message that includes the name of the active sheet.
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
MsgBox Sh.Name
End Sub
The Sh parameter is used in the Workbook SheetActivate method. The current Sheet object is
represented by the variable Sh. The Name attribute of the Sheet object is shown in the message
box.
Workbook activation events

This is the Workbook Deactivate code. When a worksheet is deactivated, this method is run.
When the worksheet is disabled, this method duplicates the chosen range. It might come in
handy if you're copying data from many places and putting it into a new worksheet. You may
pick the range to be copied, activate the other workbook, select the destination, and paste the
copied data by pressing Ctrl + V (or Enter) after the event procedure is in place.
This sentence didn't turn out the way I had hoped. The range from the second worksheet was
copied (the one I activated after deactivating the first workbook). This is because, following the
deactivation event, the second workbook became the active worksheet.
This statement was also ineffective. In reality, it returned a runtime error to me.
ThisWorkbook.ActiveSheet.Selection.Copy
The RangeSelection attribute of a Window object finally came to mind, and that did the job. This
is what I refer to as the trial-and-error method of programming.
Other Worksheet-Related Events
I gave examples of worksheet activation and deactivation events in the prior section. In this part,
I'll go through three more things that happen in worksheets: Changing a cell, right-clicking a cell,
and double-clicking a cell.
Why not using data validation?
The Data Data Tools Data Validation command may be familiar to you. This useful feature
makes it simple to guarantee that only the correct kind of data is placed into a cell or range.
Although the Data Data Tools Data Validation command is helpful, it is not without flaws.
Add data validation to a cell and see what happens. You can, for example, set it up so that the
cell only accepts numerical values. It's good until you copy and paste another cell into the data
validation cell. The data validation is removed when you paste. It's as though it never existed.
The severity of this problem is determined by the program you're using. In the next part, I'll show
you how to leverage the Change event to improve your validation.
Because Excel considers validation to be a cell format, pasting removes data validation. As a
result, it belongs in the same category as font size, color, and other comparable characteristics.
When you paste a cell, the formats in the target cell are replaced with those in the source cell.
Regrettably, your validation criteria are also included in those forms.
Preventing data validation from being destroyed
This procedure demonstrates how to prevent users from copying data and overriding data
validation rules. This example assumes that the worksheet contains a range named InputArea that
contains data validation rules (created using the Data Data Tools Data Validation command).
Any validation rules you want can be applied to the range.
When a cell is altered, the process is called. It examines the validation type of the range (called
InputRange) that should include the data validation rules. If the VT variable contains an error,
data validation is disabled for one or more cells in the InputRange. (It's likely that the user copied
some data across it.) If this is the case, the code calls the Application object's Undo function to
undo the user's action. Then, as indicated in the figure below, it shows a message box.

Events Not Associated with Objects


The events I mentioned earlier in this chapter are either related to a workbook object or a
worksheet object. I'll talk about two forms of events that aren't related to objects in this section:
time and keypresses.
Because time and keypresses aren't tied to a specific object like a workbook or a worksheet, you
may program them in a regular VBA module (unlike the other events discussed in this chapter).
The OnTime event
Most people, including this author, struggle to conceive of time in terms of the Excel numeral
system. As a result, you might want to represent the time with the VBA TimeValue function.
TimeValue transforms a string that looks like a time into an Excel-compatible value. The
following statement demonstrates an easier way to program a 3 p.m. event:
Application.OnTime TimeValue("3:00:00 pm"), "DisplayAlarm"
You may use a statement like this to plan an event relative to the current time (for example,
20 minutes from now):
Application.OnTime Now + TimeValue("00:20:00"), "DisplayAlarm"
The OnTime method can also be used to run a VBA procedure on a specific day. You must
ensure that your computer remains turned on and that the procedure's workbook remains open.
At 5 p.m. on December 31, 2016, this statement executes the DisplayAlarm procedure.
Application.OnTime DateValue("12/31/2016 5:00 pm"), "DisplayAlarm"
Another example of the OnTime event is shown below. When the UpdateClock procedures are
run, the time is written to cell A1 and a new event is programmed five seconds later. This event
causes the UpdateClock method to be restarted. As a result, cell A1 is updated every five seconds
with the current time. Execute the StopClock operation to halt the sequence of events (which
cancels the event). NextTick is a module-level variable that keeps track of the time until the next
event.

Even when the workbook is closed, the OnTime event continues. To put it another way, if you
shut the workbook without performing the StopClock operation, it will reopen in five seconds
(assuming that Excel is still running). Use a Workbook BeforeClose event procedure with the
following statement to prevent this: Call StopClock.
There are two more parameters to the OnTime function. If you plan to use this method, consult
the Help system for more information.
Keypress events
Excel keeps track of everything you enter while you're working. As a result, you may program an
operation to be executed by a single keystroke or a key combination.
The following is an example of reassigning the PgDn and PgUp keys:
Pressing PgDn takes you down one row after setting up the OnKey events using the Setup
OnKey method. You may advance one row by pressing PgUp.
The key codes are contained in braces rather than parentheses. Consult the Help system for a
comprehensive list of keyboard codes. Look for OnKey.
I utilize On Error Resume Next in this example to disregard any errors that are produced. If the
active cell is in the first row, moving up one row will result in an error that may be safely
ignored. There is no active cell if a chart sheet is active.
The OnKey events are canceled by running the following routine:
Sub Cancel_OnKey()
Application.OnKey "{PgDn}"
Application.OnKey "{PgUp}"
End Sub
The OnKey event is not canceled by passing an empty string as the second parameter to the
OnKey method. Excel, on the other hand, just ignores the keystroke. The following phrase, for
example, causes Excel to disregard Alt+F4. The Alt key is represented by the % sign:
Application.OnKey "%{F4}", ""
The OnKey function will not be reset if you close the workbook containing the code and keep
Excel open. As a result, tapping the shortcut key will allow Excel to launch the macro-enabled
file automatically. To avoid this, you should add code to reset the OnKey event in your
Workbook BeforeClose event code (explained previously in this chapter).

CHAPTER TWELVE
ERROR HANDLING TECHNIQUES
Error is a natural part of life. It's heavenly to be able to predict mistakes. When dealing with
VBA, there are two types of faults to be mindful of: code errors and runtime problems. The focus
of this chapter is on runtime errors.
A well-written software handles mistakes with the elegance with which Fred Astaire danced.
Fortunately, VBA contains various tools to assist you in detecting problems and gently handling
them.
Types of Errors
You've undoubtedly experienced one or more error messages if you've attempted any of the
examples in this book. Some of these issues are caused by faulty VBA codes. You could, for
example, misspell a term or enter a phrase with improper syntax. If you make a mistake like this,
you won't be able to run the operation until you fix it.
These sorts of mistakes are not addressed in this chapter. Instead, I'll talk about runtime errors,
which are mistakes that occur when Excel runs your VBA code.
This chapter, in particular, delves into the following intriguing topics:

Detecting mistakes
Taking action in response to faults that occur
Recognizing and correcting faults
Intentionally making mistakes (Yes, a mistake may be beneficial at times.)
The ultimate purpose of error handling is to develop code that minimizes the appearance of
Excel's error warnings. To put it another way, you want to be aware of possible mistakes and
address them before Excel raises its ugly head with a (typically) uninformative error message.
An Erroneous Macro Example
To get things started, I've created a quick and easy VBA macro. Isn't it true that a macro this
basic couldn't possibly create any errors?
This process the user for a value.
By hitting F5, you may run this process straight from the VBE. You could also add a button to a
worksheet (Select Developer Controls Insert and choose the button from the Form Controls
group to do so) and then assign the macro to the button. (Excel will ask you to assign a macro.)
The operation may then be started by simply pressing the button.
Not quite perfect macros
To test the code, run it a couple of times. Doesn't it seem to function very well? Oops. On this
planet, attempting to compute the square root of a negative integer is forbidden.
Excel displays the runtime error notice displayed below. For the time being, just click the End
button. Excel suspends the macro if you click the Debug button, allowing you to utilize the
debugging tools to assist you to trace out the mistake.

The majority of people don't find Excel error notifications (such as Invalid procedure calls or
arguments) to be very useful. You must anticipate this issue and manage it more graciously in
order to enhance the operation. To put it another way, you'll need to include some error-handling
code.
Perfecting the Macro
Isn't the updated EnterSquareRoot technique flawless? Not at all. Instead of inputting a value,
try typing text. Alternatively, use the Cancel button in the input box. Both of these acts result in a
mistake (Type mismatch). More error-handling code is required for this basic process.
The process shows a notice and then quits if the user does not provide a number. It's also worth
noting that the Num variable has been renamed to Variant. If the variable was defined as a
Double, the code would throw an unhandled exception if the user submitted a non-numeric
value.
Is the macro finished yet?
Isn't this code now totally flawless? That's not the case. If the active sheet is a chart sheet, try
executing the process. Another runtime fault has occurred, this time the dreaded Number 91.
When a chart sheet is active or anything other than a range is chosen, this error occurs because
there is no active cell.
Giving up on perfection
This method ought to be flawless by now. Please reconsider, friend.
Then execute the code after protecting the worksheet (using the Review Changes Protect Sheet
command). Trying to write to protected worksheet results in yet another error. And I'm sure I
haven't considered all of the other possibilities. Continue reading to learn another strategy for
dealing with mistakes, even ones you can't predict.
Handling Errors Another Way
How can you see and correct every conceivable mistake? Quite often, you won't be able to.
Fortunately, VBA gives you another option for dealing with mistakes.
Error handling in a nutshell
I've put up a quick-and-dirty summary to assist you to keep track of all this error-handling
activity. The following are the properties of an error-handling code block:
Knowing when to ignore errors
In certain instances, it's absolutely acceptable to overlook mistakes. When this happens, the On
Error Resume Next sentence kicks in.
In this scenario, you may just skip any cell that includes a number that you can't square root. If-
Then structures may be used to provide a variety of error-checking capabilities, but you can
come up with a better (and simpler) solution by just disregarding the mistakes that occur.
In general, if you deem the mistakes to be innocuous or insignificant to your work, you may
utilize an On Error Resume Next statement.
Identifying specific errors
Not all mistakes are made equal. Some are serious, while others aren't. You may disregard little
faults, but you must deal with more major ones. In certain circumstances, you'll need to figure
out which fault is causing the problem.
Every sort of mistake has a unique number assigned to it. The error number is stored in this
object's Number field, and the error description is stored in its Description property.
The error number, a colon, and an explanation of the error are shown in the following
statement:
MsgBox Err.Number & ": " & Err.Description
The steps below will show you how to figure out which mistake happened. You may safely
disregard errors generated by attempting to square the root of a non-positive integer or errors
caused by attempting to square the root of a non-numeric value in this situation (error 13). You
must notify the user if there is security in the worksheet and the selection has more than one
locked cell. (Otherwise, the user could believe the macro worked when it didn't.) Trying to write
to a locked cell in protected worksheet results in error 1004.
Sub SelectionSqrt()
Next cell
Exit Sub
ErrorHandler:
Select Case Err.Number
Case 5 'Negative number
Resume Next
Case 13 'Type mismatch
Resume Next
Case 1004 'Locked cell, protected sheet
MsgBox "Cell is locked. Try again.", vbCritical, cell.Address
Exit Sub
Case Else
ErrMsg = Error(Err.Number)
MsgBox "ERROR: " & ErrMsg, vbCritical, cell.Address
Exit Sub
End Select
End Sub
When a runtime error occurs, the code starting at the ErrorHandler label is executed. (In other
words, the error is ignored.) If the error code is 1004, however, the function informs the user and
then exits. The last instance, which acts as a catch-all for unexpected problems, captures all
others and shows the real error message.
An Intentional Error
You may sometimes take advantage of a mistake. Assume you have a macro that only functions
if a certain worksheet is open. How do you tell whether a worksheet is open or not? Here's a
simpler solution: use a general-purpose function that takes one parameter and returns True if the
workbook is open or False if it isn't.
Here’s the function:
Function WorkbookIsOpen(book As String) As Boolean
Dim WBName As String
On Error GoTo NotOpen
WBName = Workbooks(book).Name
WorkbookIsOpen = True
Exit Function
NotOpen:
WorkbookIsOpen = False
End Function
This function takes use of the fact that referring to a worksheet that isn't open in Excel causes an
error. If a workbook called MyBook.xlsx is not open, for example, the following sentence will
result in an error:
WBName = Workbooks("MyBook.xlsx").Name
Another implementation of the WorkbookIsOpen function. However, the code examines Err's
Number attribute. There was no problem, and the worksheet is open if Err.Number is 0. If
Err.Number is something other than zero, it signifies there was an error (and the workbook is
not open).
Function WorkbookIsOpen(book) As Boolean
Dim WBName As String
On Error Resume Next
WBName = Workbooks(book).Name
If Err.Number = 0 Then WorkbookIsOpen = True _
Else WorkbookIsOpen = False

End Function
The WorkbookIsOpen function is called by the UpdatePrices method and the workbook name
(Prices.xlsx) is sent as an argument. The WorkbookIsOpen method returns True or False
depending on whether the workbook is open. As a result, if the workbook is not open, the
method notifies the user. The macro continues if the worksheet is open.
Error management may be a difficult task. After all, numerous mistakes might happen, and you
can't predict them all. If at all feasible, you should catch problems and remedy the issue before
Excel intervenes. Writing efficient error-trapping code requires a solid grasp of Excel and how
VBA error handling works.
CHAPTER THIRTEEN
BUG EXTERMINATION TECHNIQUES
Here, I'll go through how to spot programming errors and how to get rid of them off your
module's face.
Species of Bugs
This is Entomology 101. As you surely know, a software bug is referred to as a program bug. To
put it another way, if the software doesn't work as it should, it has a defect. All significant
software products, in fact, contain defects - a lot of flaws. Excel is riddled with hundreds, if not
thousands, of flaws. Fortunately, the great majority of these vulnerabilities are cryptic and only
emerge in extremely particular situations.
Your code will almost certainly have flaws if you build nontrivial VBA apps. This is a reality of
life, and it has nothing to do with your programming abilities. The bugs might be classified as
one of the following:
Logic errors in your code: You may frequently prevent these issues by carefully considering
the problem that your software is trying to solve.
Bugs that occur when you try to perform something at the wrong moment are known as
incorrect context bugs. If your code tries to write data to cells on the active sheet while the
active sheet is really a chart sheet, for example (which has no cells).
Extreme-case bugs: These issues occur when you meet data that you didn't expect, such as very
big or tiny numbers.
Wrong data-type issues arise when you want to process data of the incorrect type.
Bugs involving incompatibilities between Excel versions: This sort of problem concerns
mismatches between various Excel versions. For example, you may create a workbook in Excel
2016 only to discover that it doesn't operate with Excel 2003. By avoiding employing version-
specific functionality, you can typically prevent such issues. The simplest method is to design
your application using the least recent Excel that your consumers may have. In any case, you
should test your work on all of the versions you anticipate seeing it in.
Bugs that are beyond your control are the most aggravating. When Microsoft updates Excel, it
may introduce a tiny, undocumented change that causes your macro to fail. Security upgrades
have been known to create issues in the past.
Debugging is the process of locating and fixing flaws in software. Debugging skills take time to
develop, so don't be discouraged if it's tough at first.
Detecting Bugs
You will have to identify whether a problem exists before you can begin debugging. When the
macro doesn't operate as it should, you've got a bug on your hands. (Wow, this book is jam-
packed with wisdom, isn't it?) Usually, but not always, you'll be able to tell.
When Excel shows a runtime error message, it usually (but not always) indicates that there is a
problem. An example may be seen in the picture. It's worth noting that this error message
contains a Debug button.
Bugs often arise when you least expect them, as many programmers are aware. For instance, just
because your macro works well with one data set does not indicate it will perform as well with
other data sets.
The ideal way to debug is to start with rigorous testing in a range of real-world scenarios. I
normally put some files into a temporary folder and test with those files.
Debugging Techniques
The four most frequent ways for debugging Excel VBA code are discussed in this section:

Investigating the code


MsgBox methods may be used in a variety of places in your code.
Debug.Print statements are inserted.
Using the built-in debugging tools in Excel

Reviewing your code


Taking a thorough look at your code to see if you can locate the issue is maybe the easiest
debugging strategy. Of course, this strategy requires prior knowledge and expertise. To put it
another way, you need to know what you're doing. If you're fortunate, the mistake will leap out
at you, and you'll smack your forehead and exclaim, "D'oh!" Once the agony in your forehead
subsides, you can remedy the issue.
Because you commonly uncover problems after working on your software for eight hours
straight, it's 2 a.m., and you're operating on coffee and willpower, I stated "if you're fortunate."
You're fortunate if you can even view your code at that point, much alone locate the errors. As a
result, don't be shocked if merely looking at your code isn't enough to detect and fix all of the
flaws it includes.
Using the MsgBox function.
Inserting temporary MsgBox functions into your code is one method to do this.
Displaying the values of two or more variables in the message box is often useful. The following
sentence shows the current values of two variables separated by a space: LoopIndex (1) and
CellCount (72).
MsgBox LoopIndex & vbNewLine & CellCount & vbNewLine & MyVal
This method isn't only for tracking variables. While your code is running, you may utilize a
message box to show a variety of valuable information.
If your code cycles over a sequence of sheets, the statement shows the current sheet's name
and type:
MsgBox ActiveSheet.Name & " " & TypeName(ActiveSheet)
If your message box puts out an unexpected message, hit Ctrl + Break, and you'll receive a
dialog box that says Code execution has been paused; you have four options, as seen in the
image below.

Continue by pressing the Enter key. The program continues to run.


To finish, click the Finish button. The execution has come to an end.
Select Debug from the drop-down menu. The VBE enters Debug mode.
To get help, use the Help button. You hit Ctrl + Break, according to a help screen. To put it
another way, it's not really useful
If you don't have a Break key on your keyboard, try hitting Ctrl + ScrollLock.
When debugging your code, feel free to utilize MsgBox functions regularly. Just be sure to get
rid of them when you've identified and fixed the issue.
Using the VBA debugger
Excel programmers are well-versed in the idea of bugs. As a result, Excel contains a set of
debugging tools that may assist you in resolving issues with your VBA code.
The following part is about the VBA debugger.
Using the debugger’s tools
In this part, I go through the ins and outs of utilizing Excel's debugging features. These
approaches are much more powerful than the ones I discussed in the last section. However, with
great power comes great responsibility. It takes some time to get the debugging tools set up.
Setting breakpoints in your code
The display of a message box effectively stops your code in the middle of its execution, and
pressing the OK button continues it.
Wouldn't it be great if you could pause the execution of a routine, check the value of any of your
variables, and then resume it? Setting a breakpoint allows you to accomplish just that.
There are numerous methods to establish a breakpoint in VBA code:

Place the cursor over the statement you wish to halt execution on, then press F9.
To halt the execution of a statement, click the gray margin to the left of the
statement.
Select the insertion point in the statement where you wish the execution to end.
Then choose Debug Toggle Breakpoint from the menu.
From the shortcut menu, right-click a statement and choose Toggle Breakpoint.
The graphic below shows the consequences of establishing a breakpoint. Excel highlights the
line and places a huge dot in the margin to remind you that you placed a breakpoint there.
Excel enters Break mode before the line with the breakpoint is executed when you run the
method. The term [break] appears in the VBE title bar while in Break mode. Press F5 or click the
Run Sub/UserForm button on the VBE toolbar to exit Break mode and resume execution.
Click the big dot in the gray margin or move the mouse to the highlighted line and press F9 to
swiftly remove a breakpoint. Ctrl+Shift+F9 will delete all breakpoints in the module.
VBA also provides a term that triggers Break mode, which you can use as a statement:
Stop
VBA enters Break mode when your code hits the Stop keyword.
Stepping through your code
You may also go through your code line by line while in Break mode. Each time you hit F8, a
single statement is performed. You may verify the state of your variables in the Immediate
window at any moment throughout the line-by-line execution of your code.
You may choose which statement VBA executes next by using your mouse. Your mouse pointer
transforms to a right-pointing arrow if you place it in the margin to the left of the currently
highlighted sentence (which is normally yellow). Simply move your cursor to the next sentence
you'd want to run and see it become yellow.
Using the Watch window
You may wish to know whether a variable or expression takes on a certain value in some
instances. Consider a method that loops across 1,000 cells. During the 900th iteration of the loop,
you discover that there is an issue. You could add a breakpoint to the loop, but it would need you
to answer 899 prompts before the code reaches the iteration you want to view (and that gets
boring real fast). Setting a watch expression is a more efficient option.
You may, for example, define a watch expression that sends the method into Break mode once a
certain variable reaches a specific value, such as Counter=900. Choose Debug Add Watch to
bring up the Add Watch dialog box, where you may define a watch expression.

The Add Watch dialog box is divided into three sections:


Expression: Enter a valid VBA expression or a variable in this box, such as Counter=900 or
simply Counter.
Context: Select the method and module you wish to observe in the context. It's worth noting that
you have the option of selecting All Procedures and All Modules.
Watch Type: By choosing an option button, you may choose the kind of watch you want. Your
option here is determined by the phrase you use. The first option, Watch Expression, does not
trigger a break; instead, it just shows the value of the expression when one happens.
After you've set up your watch expression, carry out your operation (s). Everything continues as
usual till your watch expression is pleased (based on the Watch Type you specified). Excel enters
Break mode when this occurs (you did set the Watch Type to Break When Value Is True, didn't
you?). You may then debug your code by stepping through it or using the Immediate window.
VBE shows the Watches window when you create a watch, as seen in the picture. This window
shows the total value of all the watches you've created. The value of the Counter variable in this
diagram reached 900, causing Excel to enter Break mode.
Right-click a watch in the Watches window and choose Delete Watch from the shortcut menu.
The easiest approach to learning how this Watch company operates is to utilize it and experiment
with different alternatives. Soon enough, you'll be wondering how you ever managed without it.
Using the Locals window
The Local’s window is another valuable debugging tool. This window may be accessed by
selecting View Locals Window in the VB. This pane displays a list of all variables that are local
to the current process while you are in Break mode. The wonderful thing about this window is
that if you want to look at the content of a lot of variables, you don't have to manually add a
bunch of watches. All of the hard work has been done for you by the VBE.
Tips for Bug Reduction
I'm afraid I won't be able to advise you on how to entirely remove flaws from your VBA scripts.
Finding problems in software may be a full-time job in and of itself, but here are some pointers
to help you limit the issues to a minimum.
Every variable you use must have a data type defined in this sentence. You'll have to do a little
more effort, but you'll avoid making the usual mistake of misspelling a variable name. It also has
a wonderful side effect: it makes your routines run a little quicker.
When using the On Error Resume Next statement, be cautious. This sentence permits Excel
to disregard any mistakes and continue performing the procedure, as I describe in Chapter 12.
Using this statement might lead Excel to disregard mistakes that it shouldn't be ignored in certain
instances.
Learn how to utilize Excel's debugger. The Excel debugger is a helpful tool, even though it
might be intimidating at first. Spend some time getting to know it.
Debugging code isn't one of my favorite things to do (it's right up there with being audited by the
IRS), but it's an unavoidable part of the job. You spend less time debugging as you get more
expertise with VBA, and you are more efficient when you do have to debug.
CHAPTER FOURTEEN
VBA PROGRAMMING EXAMPLES
When it comes to learning how to build Excel macros, I focus a strong emphasis on examples.
An excellent example, rather than a long discussion of the underlying theory, frequently conveys
a notion far better. You presumably agree with me since you're reading this book. Several
examples of typical VBA procedures are shown in this chapter.
These examples are divided into the following categories:

Working with different ranges


Changing Excel's preferences
Making use of graphs
Increasing the speed of your VBA code
Although you may be able to utilize some of the examples as is, you will most likely need to
modify them to fit your requirements.
Working with Ranges
Worksheet ranges are generally used in the majority of your VBA programming. (See Chapter 8
for more information on Range objects.)
Keep the following factors in mind while working with Range objects:

To deal with it, your VBA doesn't need to pick a range.


If your code selects a range, the worksheet it belongs to must be active.
The macro recorder isn't always the most efficient code generator. Frequently, you
can use the recorder to construct your macro and then tweak the code to make it
more efficient.
When writing VBA code, it's a good idea to utilize named ranges. Range("Total"),
for example, is preferable than Range("D45"). If you add a row above row 45 in the
latter scenario, you'll need to change the macro so that it uses the right range
address (D46). It's worth noting that you may name a group of cells by going to
Formulas Defined Names Define Name.
Excel enables you to make several choices. For example, you may choose a range,
hold down Ctrl, and then use your mouse to select another range. Your code may
check for numerous selections and respond appropriately.
These ideas are shown in the examples in this section.
Copying a range
One of my all-time favorite Excel pastimes is copying a range. This VBA macro appears when
you switch on the macro recorder and copy a range from A1:A5 to B1:B5.
Take note of the final sentence. This statement was created by hitting Esc, which removes the
dotted-line outline that appears when you copy a range from the spreadsheet.
This macro works OK, however, you can duplicate value ranges more quickly. You may achieve
the same effect using the following one-line macro, which does not involve setting
CutCopyMode to False and does not select any cells:

This function takes use of the Copy method's ability to accept a destination parameter as an
argument. I discovered this by using the VBA Help system. This example also shows how the
macro recorder does not always provide the most efficient code.
Copying a variable-size range
You may need to replicate a range of cells but don't know the precise row and column
dimensions in many circumstances.
The graphic depicts a worksheet range. There are multiple rows in this range, and it varies from
day to day. You need a technique to build code that doesn't utilize a range address since you
don't know the precise range address at any given moment.
The macro below shows you how to replicate this range from Sheet 1 to Sheet 2. (beginning at
cell A1). It makes use of the Current Region property, which returns a Range object that
represents a block of cells around a certain cell. That cell is A1 in this situation.

Using the Current Region property is the same as going to Home Editing Find & Select Go To
Special and selecting the Current Region option from the Go To Special dialog box. Record your
activities when sending the command to observe how it works. The Current Region is often
made out of a rectangular block of cells surrounded by one or more blank rows or columns.
By omitting the destination, you may make this macro even more efficient. The following macro
takes use of the Copy method's ability to utilize a destination range argument:
Sub CopyCurrentRegion2()
Range("A1").CurrentRegion.Copy Sheets("Sheet2").Range("A1")

End Sub
If the data is in the form of a table (made in Excel using Insert Tables Table), it's much simpler.
The table is given a name (for example, Table1) and extends when new data is entered.
Sub CopyTable()
Range("Table1").Copy Sheets("Sheet2").Range("A1")
End Sub
If you do this, you'll see that the table's header row isn't replicated since Table1 doesn't have that
row. Change the table reference if you need to include the header row.
Range("Table1[#All]")
Selecting the end of a row or column
You're undoubtedly used to selecting a range that includes everything from the current cell to the
end of a row or column using key combinations like Ctrl +Shift + right arrow and Ctrl +Shift +
down arrow. You can construct macros to do these sorts of selects, which is unsurprising.
The Current Region property may be used to pick an entire block of cells. Fortunately, VBA is
capable of handling this scenario. After you've chosen a range, you may copy, move, format, and
so on with it.

The End functions accept just one parameter, which may be one of the following constants:

xlUp
xlDown
xlToLeft
xlToRight
It's important to remember that selecting a range before doing anything with it isn't required.
Without specifying the range, the following macro adds bold formatting to a variable-size
(single-column) range:
Sub MakeBold()
Range(ActiveCell, ActiveCell.End(xlDown)).Font.Bold = True
End Sub
Selecting a row or column
It makes use of the EntireColumn property, which returns a Range object with the whole column:

VBA also has an EntireRow property that returns a Range object that contains a complete row,
as you would imagine.
Moving a range
Cutting a range to the Clipboard and copying it to another location is how you relocate it. The
macro recorder outputs code like this when you record your activities while conducting a move
operation:

In reality, you can change a range with just one VBA line, as seen below:
Sub MoveRange2()
Range("A1:C6").Cut Range("A10")
End Sub
This macro takes use of the fact that the Cut method accepts a destination parameter as an
argument. It's also worth noting that the range hasn't been chosen. The cell pointer stays in the
same location as before.
Looping through a range efficiently
Many macros execute an operation on each cell in a range or conduct certain actions depending
on the contents of each cell. A For-Next loop is commonly included in these macros, which
processes each cell in the range.
Using the Special Cells technique, the following procedure does this. (For further information on
the parameters, see the VBA Help system.) The Set keyword is used in this method to construct
two new Range objects: a subset of the selection that contains cells with constants and a subset
of the selection that contains cells with formulas. Each of these groups is processed separately,
with the result that all blank cells are skipped. Isn't it slick?
Regardless of what you choose, the Skip Blanks technique works quickly. You may choose the
range, all columns in the range, all rows in the range, or the full worksheet, for example. It's a
huge step forward from the Process Cells process described previously in this chapter.
In this code, you'll see that I utilize the following statement:
On Error Resume Next
This line instructs Excel to disregard any mistakes and proceed to the following statement. (A
description of error handling may be found in Chapter 12.) Because the SpecialCells function
throws an error if no cells meet the criteria, this line is required.
Selecting the Constants option or the Formulas option from the Home Editing Find & Select
GoTo Special command is identical to using the SpecialCells approach. Record your activities
when issuing that command and select different parameters to get a sense of how this works.
Looping through a range efficiently (Part II)
Then there's the follow-up. This section shows how to process cells in a more efficient manner.
This function makes use of the UsedRange attribute, which returns a Range object that only
contains the worksheet's utilized area. It also employs the Intersect method, which produces a
Range object containing cells shared by two ranges.
The WorkRange object variable contains cells that are shared by the user's selection and the
worksheet's active range. When an entire column is chosen, WorkRange displays just the cells in
that column that are also inside the worksheet's utilized area. It's quick and easy to use, with no
time lost processing cells beyond the worksheet's active area.
Prompting for a cell value
You may utilize VBA's InputBox method to receive a value from the user, as seen in the figure
below. The value may then be entered into a cell. Using just one sentence, the following
technique explains how to ask the user for a value and insert it in cell A1 of the current
worksheet:
Sub GetValue()
Range("A1").Value = InputBox( _
"Enter the value for cell A1")
End Sub
Identifying multiple selections
Excel enables you to make numerous selections by holding down the Ctrl key when selecting
objects or ranges. Some macros may be affected as a result of this. You can't replicate multiple
selections that contains nonadjacent cells, for example. If you try to do so, Excel will chastise
you with the notice displayed below.

The following macro shows how to evaluate whether the user made several selections so
that your macro can respond appropriately:
The Areas method is used in this example, and it returns a collection of all ranges in the
selection. The Count property returns the collection's item count.
Changing Excel Preferences
Simple operations that alter one or more of Excel's settings are some of the most helpful macros.
This section includes two examples that demonstrate how to adjust Excel settings. These
examples explain broad ideas that may be applied to different procedures that update settings.
Changing Boolean settings
A Boolean setting is either on or off, like a light switch. You could wish to develop a macro that
toggles the worksheet page break display on and off, for example. Excel shows dashed lines to
signify page breaks when you print or preview a worksheet. These dashed lines irritate some
people, including the author. Unfortunately, the only method to disable the page break display is
to enter the Excel Options dialog box, choose the Advanced tab, and scroll down until the Show
Page Breaks check box is shown. When you choose that option and enable the macro recorder,
Excel creates the following code:
ActiveSheet.DisplayPageBreaks = False
If, on the other hand, you don't see any page breaks when you record the macro, Excel creates
the following code:
ActiveSheet.DisplayPageBreaks = True
This may lead you to believe that you need two macros: one to enable the page break display and
the other to disable it. This is not the case. The Not operator is used in the following process to
convert True to False and False to True. Toggling the page break display from True to False and
from False to True is as easy as using the TogglePageBreaks procedure:
Sub TogglePageBreaks()
On Error Resume Next
ActiveSheet.DisplayPageBreaks = Not _
ActiveSheet.DisplayPageBreaks
End Sub
Excel is told to disregard any mistakes in the first statement. Because a chart sheet does not show
page breaks, you will not get an error notice if you run the macro while it is running.
Changing non-Boolean settings
For non-Boolean settings, a Select Case structure may be used. This example switches between
manual and automated computation modes and shows a message identifying the current
mode:
Sub ToggleCalcMode()
Select Case Application.Calculation
Case xlManual
Application.Calculation = xlCalculationAutomatic
MsgBox "Automatic Calculation Mode"
Case xlAutomatic
Application.Calculation = xlCalculationManual
MsgBox "Manual Calculation Mode"
End Select
End Sub
You may use this method to change non-Boolean parameters as well.
Working with Charts
Because charts include so many distinct items, controlling them using VBA may be difficult.
I picked the range A1:A3 by entering certain integers in A1:A3. Then I activated the macro
recorder and constructed a simple three-data-point column chart. The chart's gridlines were
removed, and the title was modified.
The macro that I recorded is as follows:
Sub Macro1()
' Recorded by Excel 2016
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$A$3")
ActiveChart.SetElement (msoElementPrimaryValueGridLinesNone)
ActiveChart.ChartTitle.Select
ActiveChart.ChartTitle.Text = "This is my chart"
End Sub
In Excel 2013, the AddChart2 was introduced. This is the code you'll receive if you record
the same macro in Excel 2010:
Sub Macro1()
Recorded by Excel 2010
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlColumnClustered
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$A$3")
ActiveChart.Axes(xlValue).MajorGridlines.Select
Selection.Delete
ActiveChart.SetElement (msoElementChartTitleAboveChart)
ActiveChart.ChartTitle.Text = "This is my chart"
End Sub
This implies that macros created in Excel 2013 or 2016 will not operate with Excel 2010. The
macro created in Excel 2010 will, however, operate in Excel 2013 and subsequent versions. To
put it another way, the Excel 2010 macro is backward compatible. Backward compatibility is not
available for the Excel 2013 (and later) macro.
A typical Excel user is unlikely to be aware of macro compatibility when it comes to chart
development. However, if you share your macro with someone who uses an older version, you'll
immediately learn about it. What's the bottom line?
AddChart versus AddChart2
The AddChart method's official syntax is as follows:
. AddChart(Type, Left, Top, Width, Height)
The AddChart2 method has the following syntax
.AddChart2 (Style, XlChartType, Left, Top, Width, Height, NewLayout)
As you can see, the AddChart2 method accepts a number of extra inputs, including style, chart
type, and layout. The AddChart function merely produces an empty chart. Additional comments
are required to give the chart's details.
Examining it reveals a few points that may be useful when building your own chart macros.
Here's a homemade version of the macro that makes a chart from the given range if you're
interested:
Sub CreateAChart()
Dim ChartData As Range
Dim ChartShape As Shape
Dim NewChart As Chart
' Create object variables
Set ChartData = ActiveWindow.RangeSelection
Set ChartShape = ActiveSheet.Shapes.AddChart
Set NewChart = ChartShape.Chart
With NewChart
.ChartType = xlColumnClustered
.SetSourceData Source:=Range(ChartData.Address)
.SetElement (msoElementLegendRight)
.SetElement (msoElementChartTitleAboveChart)
.ChartTitle.Text = "This is my chart"
End With
End Sub
A clustered column chart with a legend and a title has been constructed. This simple chart-
making macro may be readily tweaked. One method is to record your activities while modifying
the chart, then utilize the recorded code as a guide.
By the way, later in this chapter, I go through the With End-With construct. It's a convenient
technique to save time typing and make your code more readable.
If you want to build VBA macros that alter charts, you'll need to know a few terms. A
ChartObject object is an embedded chart on a spreadsheet. A ChartObject may be activated in
the same way as a sheet can. The ChartObject called Chart 1 is activated by the statement below:
ActiveSheet.ChartObjects("Chart 1").Activate
After you've activated the chart, you may refer to it as the ActiveChart in your VBA code. If the
chart is on a different chart sheet, it becomes the active chart once that chart sheet is activated.
It's a little perplexing since a ChartObject is also a Shape. In reality, creating a new Shape is the
first step in your VBA code's creation of a chart.
A chart may also be activated by choosing the Shape object that contains it:
ActiveSheet.Shapes("Chart 1").Select
To make it quite apparent that I'm dealing with a chart, I like to utilize the ChartObject object in
my code.
Excel picks an item inside the ChartObject object when you click an embedded chart. By holding
down Ctrl while selecting the embedded chart, you may pick the ChartObject itself.
Modifying the chart type
A ChartObject object works as a container for a Chart object, which may be perplexing. If you
read it a few times, it may make sense.
You don't have to activate a chart to change it using VBA. The Chart method may return the
chart that is included in the ChartObject. Are you completely perplexed yet? The two techniques
that follow are of the same effect: they convert Chart 1 into an area chart. The first method starts
by activating the chart and then works with it. The chart is not activated by the second process.
Rather, it returns the Chart object contained in the ChartObject object using the Chart property.
Looping through the Chart Objects collection
The chart type of every embedded chart on the active sheet is changed in this example. The code
cycles over each item in the ChartObjects collection, accessing the Chart object in each and
changing its Type attribute using a For Each-Next loop.
Sub ChartType()
Dim cht As ChartObject
For Each cht In ActiveSheet.ChartObjects
cht.Chart.Type = xlArea
Next cht
End Sub

The following macro does the same task; however, it applies to all chart sheets in the
current workbook:
Modifying chart properties
The legend font for all charts on the active sheet is changed in the following example:

Applying chart formatting


The active chart is formatted in different ways in this sample. This macro was made by recording
my activities when formatting a chart.
Sub ChartMods()
ActiveChart.Type = xlArea
ActiveChart.ChartArea.Font.Name = "Calibri"
ActiveChart.ChartArea.Font.FontStyle = "Regular"
ActiveChart.ChartArea.Font.Size = 9
ActiveChart.PlotArea.Interior.ColorIndex = xlNone
ActiveChart.Axes(xlValue).TickLabels.Font.Bold = True
ActiveChart.Axes(xlCategory).TickLabels.Font.Bold = True
ActiveChart.Legend.Position = xlBottom
End Sub
Before running the ChartMods macro, you must first activate a chart. By clicking on an
embedded chart, you may make it active. Activate the chart sheet to activate a chart inside it.
You may add a statement to detect whether a chart is active to guarantee that it is picked. The
changed macro is as follows: If a chart is not enabled, it shows a notice (and then exits):
Sub ChartMods2()
If ActiveChart Is Nothing Then
MsgBox "Activate a chart."
Exit Sub
End If
ActiveChart.Type = xlArea
ActiveChart.ChartArea.Font.Name = "Calibri"
ActiveChart.ChartArea.Font.FontStyle = "Regular"
ActiveChart.ChartArea.Font.Size = 9
ActiveChart.PlotArea.Interior.ColorIndex = xlNone
ActiveChart.Axes(xlValue).TickLabels.Font.Bold = True
ActiveChart.Axes(xlCategory).TickLabels.Font.Bold = True
ActiveChart.Legend.Position = xlBottom
End Sub
Another version that makes use of the With-End With construct is to save time and make the
code more readable. I'm getting ahead of myself again. To learn more about the With End-With
structure, go a few pages ahead.
Sub ChartMods3()
If ActiveChart Is Nothing Then
MsgBox "Activate a chart."
Exit Sub
End If
With ActiveChart
.Type = xlArea
.ChartArea.Font.Name = "Calibri"
.ChartArea.Font.FontStyle = "Regular"
.ChartArea.Font.Size = 9
.PlotArea.Interior.ColorIndex = xlNone
.Axes(xlValue).TickLabels.Font.Bold = True
.Axes(xlCategory).TickLabels.Font.Bold = True
.Legend.Position = xlBottom
End With
End Sub
This brief overview of how to use VBA to deal with charts hardly scrapes the surface. Of course,
there's a lot more to it, but at the very least, this fundamental overview will get you started.
VBA Quick Tips
VBA is quick, but it isn't always enough. (Computer programs are never fast enough.) In this
part, you'll find several programming examples for speeding up your macros.
Turning off screen updating
When you're running a macro, you can sit back and watch everything that happens onscreen.
Although this may be enlightening, it's frequently inconvenient once you've gotten your macro to
operate correctly, and it can significantly slow down your macro's performance.
Execute this simple macro, which fills a range with numbers, to show the difference in
speed:
Sub FillRange()
Dim r as Long, c As Long
Dim Number as Long
Number = 0
For r = 1 To 50
For c = 1 To 50
Number = Number + 1
Cells(r, c).Select
Cells(r, c).Value = Number
Next c
Next r
End Sub
The range gets filled significantly quicker, and the output isn't visible until the macro is done and
screen updating is set to True (automatically).
When you're debugging code, program execution might often stop in the midst without you
realizing it since you haven't switched on Screen updating (and yes, this happens to me, too).
Excel's application window might become completely unresponsive as a result of this.
Application.ScreenUpdating = True
Disabling automatic calculation
When utilizing a worksheet with a lot of complex formulas, you might find that switching to
manual calculation mode while your macro is running speeds things up a lot. Set the computation
mode back to automatic after the macro is finished.
Excel's calculation mode is set to manual using the following statement:
Application.Calculation = xlCalculationManual
To change the computation mode to automated, use the following command:
Application.Calculation = xlCalculationAutomatic
Turning off calculation implies that if your code utilizes cells containing formula results, the
cells will not be recalculated until you expressly instruct Excel to do so!
Eliminating those pesky alert messages
A macro, as you may know, can perform a series of actions automatically. You can usually start
a macro and then go hang out in the break room while Excel does its magic. However, certain
Excel functions show notifications that demand a human reaction. Because of these notifications,
you can't leave Excel alone while it runs your macro unless you know the hidden technique.

Inserting the following VBA statement into your macro is the secret to avoiding these alert
messages:
Application.DisplayAlerts = False
When deleting a sheet, the default action is to delete it (which is just what you want to happen).
Perform a test to see what happens if you're not sure what the default operation is.
Excel automatically sets the DisplayAlerts property to True when the procedure is completed (its
normal state).

Simplifying object references


As you undoubtedly already know, object references may become rather long.
Workbooks("MyBook.xlsx").Worksheets("Sheet1") _
.Range("InterestRate")
The following statement, for example, assigns this Range object to the Rate object variable:
Set Rate = Workbooks("MyBook.xlsx") _
.Worksheets("Sheet1").Range("InterestRate")
You may use the variable Rate instead of the long reference once you've defined this object
variable. You may, for example, modify the value of the cell InterestRate:
Rate.Value = .085
This sentence is considerably simpler to write (and comprehend) than the following:
Workbooks("MyBook.xlsx").Worksheets("Sheet1"). _
Range("InterestRate") = .085
Using object variables speeds up your macros significantly, in addition to simplifying your code.
I've observed certain macros run twice as quickly as before after using object variables.
Declaring variable types
Tell Excel what kind of data will be given to each of your variables if you want your processes to
run as quickly as possible (and prevent some potentially unpleasant consequences).
In general, you should pick the data type that takes the fewest bytes while still being able to
handle all of the data that has been given to it. When working with data, VBA's execution speed
is determined by the number of bytes available to it. To put it another way, the fewer bytes used
by data, the faster VBA can access and manipulate it. The Integer data type is an exception to
this rule. Use the Long data type instead if speed is critical.
PART FOUR
COMMUNICATING WITH YOUR USERS
CHAPTER FIFTEEN
SIMPLE DIALOG BOXES
You won't be able to use Excel for very long without seeing dialog windows. They seem to
appear on a regular basis. To acquire information, explain instructions, and show messages,
Excel, like other Windows applications, employs dialog boxes. You can design your own dialog
boxes that operate exactly like the ones included in Excel if you write VBA macros. In VBA, the
bespoke dialog windows are known as UserForms.
This chapter contains no information on how to create UserForms. Rather, it explains several
highly helpful strategies that may be used instead of UserForms. Chapters sixteen through
eighteen will provide you with a thorough explanation.
Interacting with User In VBA
This macro generates the same output every time and does not need any extra user input.
Other macros might be created that respond differently in certain situations or provide the user
with alternatives. In such circumstances, a custom dialog box may be beneficial to the macro. A
custom dialog box, is an easy way to gather information from the user. The information is then
utilized by your macro to decide what it should perform.
UserForms are really helpful, but they take time to create. Before I go into the issue of generating
UserForms in the following chapter, you should be aware of a few time-saving options.
VBA allows you to show a variety of dialog boxes that you may use in lieu of a custom
UserForm. These built-in dialog boxes can be customized in certain ways, but they don't have
nearly as many choices as a UserForm. However, in certain circumstances, they're just what the
doctor prescribed.
I also showed you how to use VBA to display some of Excel's built-in dialog boxes, which are
the ones that Excel uses to collect data from you.
The MsgBox Function
The VBA MsgBox function is certainly known to you; I use it often in the examples throughout
this book. The MsgBox method, which takes the parameters in the picture, is useful for
displaying data and receiving basic user input.
Displaying Messages with the MsgBox Function
To elicit a response from the user: In this scenario, the result produced by the function is
important. The outcome is determined by the user's selection of a button.
If you're only using the MsgBox function, don't put parentheses around the parameters.
The graphic depicts the appearance of this message box. When the user hits OK in this situation,
printing begins. Isn't it true that there's no way to stop the printing? The next section explains
how to correct this.
Customizing message boxes
The buttons argument's versatility allows you to easily alter your message boxes. You may pick
which buttons to show, whether an icon displays and which button is the default (if the user
pushes Enter, the default button is "clicked").
Simply link them using a + operator to utilize more than one of these constants as an argument.
The constant vbDefaultButton2 makes the second button (No) the default button, which means
it's the one that gets pressed when the user clicks Enter. I put these constants in the Config
variable for ease of usage, and then use Config as the second parameter in the MsgBox function:
Sub GetAnswer3()
Dim Config As Long
Dim Ans As Integer
Config = vbYesNo + vbQuestion + vbDefaultButton2
Ans = MsgBox("Process the monthly report?", Config)
If Ans = vbYes Then RunReport
End Sub
The picture depicts the dialog box that appears when you run the GetAnswer3 operation in
Excel. If the user selects Yes, the RunReport method is invoked by the routine (which is not
shown). The program stops with no effect if the user hits the No button (or presses Enter). Excel
uses the default title, Microsoft Excel since I ignored the title parameter in the MsgBox method.

Getting Data with an Input Box syntax


Here's a simplified version of the InputBox function's syntax:
InputBox(prompt[, title][, default])
The InputBox function accepts the arguments listed below:

Using the Input Box function


The information in this section is for the InputBox function in VBA. You also have access to the
InputBox method, which is a method of the Application object, since Microsoft seems to like
causing confusion.
The ability to ask for a range selection is one of the major benefits of utilizing the Application
InputBox technique. The user may then highlight the cells in the worksheet to pick the range.
Here's an example of a prompt that asks the user to choose a range:
Sub GetRange()
Dim Rng As Range
On Error Resume Next
Set Rng = Application.InputBox _
(prompt:="Specify a range:", Type:=8)
If Rng Is Nothing Then Exit Sub
MsgBox "You selected range " & Rng.Address
End Sub
In this basic example, the code displays the address of the specified range to the user. Your code
would really perform something helpful with the given range in real life. Excel handles the error
management in this case, which is a pleasant touch. If you type anything that isn't a range, Excel
warns you and gives you the option to try again.
The Application.InputBox method is similar to the InputBox function in VBA, although it differs
in a few ways. For further information, use the Help system.
Constructing a GetOpenFilename Statement
Most users find it difficult to remember paths, backslashes, filenames, and file extensions, so an
input box isn't the best tool for the job. To put it another way, it's simply too simple to make a
mistake while inputting a filename.
Use the GetOpenFilename function of the Application object to obtain a better solution to this
issue, which guarantees that your code receives a proper filename with the whole path. The
familiar Open dialog box (a perfect ringer for the dialog box Excel shows when you pick File
Open Browse) is shown by the GetOpenFilename method.
The GetOpenFilename function does not really open the file that has been supplied. This
function just returns a string with the user-selected filename. Then you may create code to
manipulate the filename in any way you want.
The syntax for the GetOpenFilename method
The GetOpenFilename method's official syntax is as follows:
object.GetOpenFilename ([fileFilter], [filterIndex],
[title],[buttonText], [multiSelect])
The GetOpenFilename function accepts the following optional parameters.

An example of GetOpenFilename
The following code displays a dialog box that asks the user for a filename. Five file filters are
defined by the method. Notice how I set up the Filter variable using the VBA line-continuation
sequence; this helps to simplify this somewhat extensive argument.
The figure depicts the dialog window that appears when you run this method in Excel.
Depending on the version of Windows you're running and the display choices you've chosen, the
look may differ.
You'd perform something more significant with the filename in a real application. For instance,
you could wish to start it with a sentence like this:
Workbooks.Open FileName
Displaying Excel’s Built-in Dialog Boxes
VBA may be thought of as a tool that allows you to replicate Excel commands.
Consider the following VBA statement:
Range("A1:A12").Name = "MonthNames"
Choosing Formulas Defined Names Define Name to open the New Name dialog box, entering
MonthNames in the Name box and A1:A12 in the Refers To box, then clicking OK has the same
effect as putting MonthNames in the Name box and clicking OK.
The New Name dialog box does not display when you run the VBA line. You don't want dialog
boxes flashing across the screen while your macro runs, so this is almost always what you want
to happen.
However, in some cases, you may want your code to display one of Excel's many built-in dialog
boxes and allow the user to make the dialog box's choices. This can be accomplished by using
VBA to run a Ribbon command. Here's an example of the New Name dialog box in action. The
range selected when the command is executed is represented by the address in the Refers To box.

The dialog box does not provide any information about your VBA code.
The CommandBars object's ExecuteMso function takes one argument: an idMso parameter that
specifies a Ribbon control. Unfortunately, the Help system does not provide these parameters.
Because the Ribbon hasn't always been present, code that utilizes the ExecuteMso function isn't
compatible with Excel versions before 2007.
Another use of the ExecuteMso method is seen below. Application.CommandBars.ExecuteMso
"FormatCellsFontDialog"
There are hundreds of commands in Excel. Right-click any Ribbon control and choose to
Customize the Ribbon from the shortcut menu to get there quickly. On the left side, you'll find a
list of almost every command possible in Excel. When you hover your cursor over command, the
tooltip will reveal its hidden command name (it's the section in parenthesis).

CHAPTER SIXTEEN
USERFORM BASICS
If your VBA macro has to stop and collect data from a user, a UserForm comes in handy. Your
macro, for example, might have some options that can be set in a UserForm. If only a few pieces
of data are needed. Here, I'll show you how to use User Forms. It will be a pleasure for you to
meet them.
Knowing When to Use a UserForm
You can improve the utility of this macro. One option is to make two more macros, one for
lowercase and the other for the proper case. Another alternative is to change the macro to
accommodate the additional parameters.
The solution is to show a dialog box similar to the one shown below. In the next section, I'll
show you how to make this dialog box.

Working with UserForms


Each dialog box you construct is saved in its own UserForm object — one UserForm per dialog
box. The Visual Basic Editor is where you create and access these UserForms.
Inserting a new UserForm
Insert a UserForm object by following
Follow these steps to create a UserForm object:
By hitting Alt+F11, you may start the VBE.
In the Project box, choose the workbook that will house the UserForm.
Select UserForm from the drop-down menu.
A new UserForm object is created by the VBE, which has an empty dialog box.
The graphic depicts a UserForm – an empty dialog box. If you accept the task, you
will be responsible for adding certain controls to this UserForm.
Adding controls to a UserForm
The VBE displays the Toolbox in a floating window when you activate a UserForm (refer to
Figure 16-2). To add controls to your UserForm, you utilize the tools in the Toolbox. If the
Toolbox does not display when you activate your UserForm for any reason, choose View
Toolbox.
Simply, select the desired control from the Toolbox and drag it into the dialog box. After you've
added control, you may use normal approaches to move and resize it.
Changing properties for a UserForm control
The characteristics of each control you add to a UserForm affect how the control appears and
acts. The Properties window, as its name suggests, allows you to change these settings. When a
CommandButton control is selected, the Properties window appears.
When you press F4, the Properties window appears, and the properties displayed in this window
are dependent on what is selected. If you pick a different control, the attributes change to those
suited for that control. To hide the Properties window and get it out of the way, click the Close
button in its title bar. When you need it, pressing F4 always brings it back.
Name Control properties include the following:

Width
Height
Value
Caption
Each control has its unique set of characteristics (although many controls have some shared
features) (although many controls have some common properties).
To update a property using the Properties window, follow these steps:

In the UserForm, double-check that the relevant control is chosen.


Check that the Properties window is visible (if it isn't, hit F4).
Click the property you wish to edit in the Properties window.
Make the modification in the Properties window's right-hand section.
Some UserForm parameters are used as defaults for new controls that you drag onto the
UserForm. If you modify the Font attribute of the UserForm, for example, the controls you add
will utilize the same font. Controls that are already on the UserForm are not affected.
Viewing the UserForm Code window
To display the Code module, click F7. Until you add some procedures, the Code window is
blank. Press Shift+F7 to return to the dialog box.
Use the View Code and View Object buttons in the Project window's title bar to switch between
the Code window and the UserForm display. Alternatively, right-click the UserForm and select
View Code from the context menu. Return to the UserForm by double-clicking the UserForm
name in the Project window if you're viewing code.
Displaying a UserForm
In a VBA procedure, you use the UserForm's Show method to display a UserForm.
The UserForm1 dialog box is displayed using the following procedure:
Sub ShowDialogBox()
UserForm1.Show
' Other statements can go here
End Sub
When Excel shows the dialog box, the ShowDialogBox macro stops working until the user
dismisses it. The procedure's remaining statements are then executed by VBA.
Using information from a UserForm
UserForm1.CheckBox1.Value = True
The code for a UserForm is usually written in the UserForm's code module. If that's the case,
remove the UserForm object qualifier and write the sentence as follows:
CheckBox1.Value = True
Your VBA code may also inspect different characteristics of the controls and take necessary
actions. If the check box (named CheckBox1) is checked, the following statement runs a macro
called PrintReport:
If CheckBox1.Value = True Then Call PrintReport
In Chapter 17, I go into this issue in depth.
It's usually a good idea to change the default name the VBE has given to your controls to
something more meaningful. cbxPrintReport is a possible name for the check box I just defined.
It's worth noting that I prefix the name with a three-letter prefix (for check box) to indicate the
control type. It is a question of personal preference as to whether or not you believe this is a good
practice.
A UserForm Example
The UserForm example in this part is a more advanced version of the ChangeCase macro from
earlier in the chapter. This macro's original version converts the text in the chosen cells to
uppercase. It is used in this updated version to question the user about the sort of modification
they are to make: uppercase, lowercase, or appropriate case.
The user must provide just one item of information to this dialog box: the kind of modification to
be made to the text. Because the user has three options, a dialog box with three OptionButton
controls is the best option. Two extra buttons are required in the dialog box: an OK button and a
Cancel button. The code that accomplishes the job is performed when you click the OK button.
The macro will terminate without doing anything if you click the Cancel button.
Adding the CommandButtons
Check that the Toolbox is visible; if it isn't, choose View Toolbox.
Press F4 to show the Properties window if it isn't displayed.
To create a button, drag a CommandButton from the Toolbox into the dialog box.
The button has a default name and description, as seen in the Properties box: CommandButton1.
Make sure the CommandButton is chosen, then open the Properties window and adjust the
following settings.

Change the following attributes on a second Command Button object in the UserForm:

Change the size and placement of the controls.


Adding the Option Buttons
Click the Frame tool in the Toolbox and drag it into the dialog box.
This stage produces a frame for the choices buttons to be placed in.
Change the caption of the frame to Options in the Properties box.
Click the Option Button tool in the Toolbox and drag it into the dialog box (within the Frame).
This results in the creation of an Option Button control.
Change the following properties by selecting the Option Button and using the Properties
window:

When the Value attribute is set to True, this Option Button becomes the default.
Add another Option Button and alter the following settings in the Properties window:
Add a third Option Button and alter the following settings in the Properties window:
The option Buttons, Frame, and dialog box may all be resized and positioned.
Press F5 to receive a sneak peek at what the UserForm will look like when it's displayed.
Because none of the controls are operational at this time, you must exit the dialog box by
clicking the red X.
The Accelerator property controls which letter in the caption is highlighted, as well as which
Alt+key combination is used to choose that control. Because the L is highlighted, you may pick
the Lower-Case option by pressing Alt+L...
Because the control's Default attribute is True, pressing Enter is identical to clicking OK.
Because the control's Cancel attribute is True, pressing Esc is equal to clicking Cancel.
Adding event-handler procedures
The code that follows is an improved version of the ChangeCase macro that I presented at the
start of the chapter. The macro comprises three different code pieces. Only one block is run,
which is chosen by the user's selection of OptionButton.
Here's something strange. Although VBA provides UCase and LCase functions, it lacks a way to
transform the text into a suitable case. To achieve the appropriate case conversion, I utilize
Excel's PROPER worksheet function (preceded by Application.WorksheetFunction).
Another solution is to utilize the VBA StrConv function with the vbProperCase second
parameter. (For further information, see the Help system.) Because the StrConv function isn't
accessible in every version of Excel, I utilize the PROPER worksheet function instead. It's worth
noticing that the StrConv function converts to proper case faster than the PROPER function. The
PROPER function in Excel always capitalizes the letter after an apostrophe. As a result, the term
can't is shortened to Can'T. StrConv isn't able to perform this.
Creating a macro to display the dialog box
You're almost done with this task. The only thing that's lacking is a procedure for displaying the
dialog box.
End Sub
Its straightforward technique. It double-checks that a range has been chosen. The user gets a
MsgBox with the text Select a range if no range is chosen.
Making the macro available
Everything should be operating fine at this time. However, you'll still need a simple method to
run the macro. Follow these steps to create a shortcut key (Ctrl+Shift+C) that runs the
ChangeCase macro:
By hitting Alt+F11, you open the Excel window.
Select Developer Code Macros or press Alt+F8 to access the Developer Code Macros menu.
Select the ChangeCase macro in the Macros dialog box.
Select the Options tab.
The Macro Options dialog box appears in Excel.
For the Shortcut key, type an uppercase C.
In the Description area, provide a description for the macro.
Click the OK button.
When you return to the Macro dialog box, click Cancel.
Pressing Ctrl +Shift + C after this action runs the ChangeCase macro, which shows the
UserForm if a range is specified.
This macro may also be accessed from the Quick Access toolbar. Customize the Quick Access
Toolbar by right-clicking it and selecting Customize Quick Access Toolbar. The Excel Options
dialog box opens, and the ChangeCase macro appears under Macros.
Testing the macro
Finally, test the macro and dialog box to ensure that they function correctly, as follows:
Make a worksheet active (any worksheet in any workbook).
Choose a few text-filled cells.
You may even choose whole rows or columns to pick.
Ctrl +Shift + C is the shortcut.
The UserForm is shown.
Make your decision and then click OK.
If you followed the steps properly, the macro will update the text in the chosen cells as you
indicated.
When you try this technique with only one cell selected, you'll see that it processes all of the
worksheet's cells. Using the Special Cells technique results in this behavior. Change the first
piece of code to something like this if you just want to handle one cell:

The worksheet after the text has been converted to uppercase is shown in the picture. The
formula in cell B15 and the date in cell B16 have not been altered. The macro only works with
text-filled cells.
You may run the macro from any other worksheet as long as the workbook is open. Ctrl +Shift
+C has no effect once you shut the worksheet that includes your macro.
If the macro doesn't function, double-check the previous steps to find and fix the problem. Don't
be afraid; debugging is a necessary element of the macro development process.
CHAPTER SEVENTEEN
USING USERFORM CONTROLS
A user interacts with a custom dialog box (also known as a UserForm) by utilizing the dialog
box's different controls (buttons, edit boxes, option buttons, and so on). You should be familiar
with UserForm controls if you went through the hands-on example in Chapter 16. Some of the
gaps are filled in this chapter.
Getting Started with Dialog Box Controls
I'll show you how to add controls to a UserForm, give them appropriate names, and change some
of their attributes in this part.
Before you can accomplish any of these things, you'll need a UserForm, which you can acquire
by going to the VBE and selecting Insert UserForm.
Adding controls
To add a control to the UserForm, follow these steps:

Select the Toolbox tool for the control you wish to add from the drop-down menu.
To resize and place the control, click and drag in the UserForm.
You may also construct a control with the default dimensions by dragging a control
from the Toolbox to the UserForm.
Vertical and horizontal grid lines may appear on a UserForm to assist align the
controls you add. A control snaps to the grid when you add or move it.
To disable it, follow the steps below:

Navigate to the Tools Options.


Select the General tab in the Options box.
In the Form Grid Settings section, choose your preferred choices.

Introducing control properties


The characteristics of each control you add to a UserForm affect how the control appears and
acts. You have two options for changing a control's properties.
When you're creating the UserForm, during design time. Using the Properties window, you may
do so manually.
While your macro is executing, during runtime. You do this by creating VBA code. Changes
performed at runtime are always transitory; they affect the copy of the dialog box you're
displaying, not the UserForm object you created.
When you add a control to a UserForm, you nearly always need to alter its attributes at design
time. These adjustments are made in the Properties panel. (Press F4 to bring up the Properties
window.)
However, all controls share certain characteristics, such as Name, Width, and Height. Some of
the common characteristics accessible for various controls are shown in the photographs.
The properties of a control display in the Properties box when you select it. Simply choose a
property in the Properties box and make the necessary changes. Some properties will assist you.
Dialog Box Controls: The Details
In the sections that follow, I'll go through each of the several types of controls you may use in
custom dialog boxes, as well as some of their most valuable attributes. I don't go through every
property for each control since it would take a book four times as long to do so. The control and
property help system are extensive. Select a property in the Properties pane and press F1 to get
all of the information for that property.
CheckBox control
A CheckBox control may be used to receive a binary decision, such as yes or no, true or false, on
or off, and so on.
The following are the most important characteristics of a CheckBox control:
Accelerator: A keyboard character that lets you change the value of a control. If the accelerator
is set to A, for example, hitting Alt+A will modify the value of the CheckBox control (from
checked to unchecked, or from unchecked to checked).
ControlSource: The address of a connected CheckBox cell in a worksheet. If the control is
checked, the cell shows TRUE; otherwise, it displays FALSE. This is an optional step. A
CheckBox is usually not associated with a cell.
If True, the CheckBox will have a checkmark. The CheckBox does not have a checkmark if
False.
CheckBox controls are not to be confused with OptionButton controls. They have a similar
appearance, yet they serve distinct functions.
ComboBox control
A ComboBox control is comparable to a ListBox control. A drop-down control is a ComboBox.
Another distinction is that you may be permitted to input a value that is not included in the list of
options.
The attributes of the ComboBox control are as follows:
ControlSource: A cell that keeps track of the ComboBox value.
ListRows: The number of items to show when the drop-down menu appears.
The look of the list items is controlled by the list-style property.
The control's style determines whether it behaves like a drop-down list or a ComboBox.
Value: The user-selected item's text, which is shown in the ComboBox.
CommandButton control
A CommandButton is nothing more than a standard clickable button. If you don't give an event-
handler method to run when the button is pressed, it'll be useless. A dialog box with nine
CommandButtons is shown in Figures 17-6. Clip-art pictures may be added to two of these
buttons by copying the clip art and pasting it into the Picture box in the Properties window.

When a CommandButton is clicked, an event-handler procedure with the name of the


CommandButton, an underscore, and the word Click is executed. If a CommandButton is called
MyButton, for example, clicking it performs the macro MyButton Click. This macro is saved in
the UserForm's code pane.
Some useful CommandButton control properties are as follows:
If True, pressing Esc will run the macro associated with the button. This option should only be
set to True for one of the form's buttons.
If True, hitting Enter will run the macro associated with the button. This option should only be
set to True on one button.
Frame control
Other controls are encased by a Frame control. You may use it to arrange a collection of controls
logically or for aesthetic reasons. When the dialog box has many sets of OptionButton controls
(see "OptionButton control," later in this chapter), a frame is very handy.
Image control
An image is displayed by an Image control. To show your company's logo in a dialog box, you
may wish to utilize an Image control. A dialog box with an Image control displays a photo of a
cute little kitten in the image.

The characteristics of Image control that are most helpful are listed below:
The displayed graphical image is called a picture.
If the control size does not match the image size, PictureSizeMode determines how the picture
is displayed.
To find images on the web, open Excel and select Insert Illustrations Online Pictures, then search
for an image to include in your worksheet. Then pick the picture and copy it to the Clipboard by
pressing Ctrl + C. Then activate your UserForm, click the Image control, and choose the Picture
property. To paste the copied picture, use Ctrl + V.
Some graphical pictures are rather huge, and they may significantly increase the size of your
workbook. Use the smallest image possible for the best results.
ListBox control
The ListBox control displays a menu of options from which the user may choose one or more.
The ListBox controls are very adaptable.
A scroll bar appears if a ListBox isn't tall enough to display all of the items in the list. The user
can scroll down to see more items.
The properties of the most useful ListBox control are described in the following list:
ControlSource: A cell that stores the value selected in the ListBox.
IntegralHeight: This is True if the ListBox height adjusts automatically to display full lines of
text when the list is scrolled vertically. If False, the ListBox may display partial lines of text
when it is scrolled vertically. Note that when this property is True, the actual height of your
ListBox may be slightly different, when your UserForm is shown, from what you had set it
originally. In other words, the height may adjust to ensure that the last entry is entirely visible.
Value: The text of the selected item in the ListBox.
If the ListBox has its MultiSelect property set to 1 or 2, the user can select multiple items in the
ListBox. In such a case, you cannot specify a ControlSource; you need to write a macro that
determines which items are selected. Chapter 18 demonstrates how to do so.
MultiPage control
A MultiPage control lets you create tabbed dialog boxes, like the Format Cells dialog box (the
one that appears when you press Ctrl+1 in Excel). Descriptions of the most useful MultiPage
control properties follow:
Style: Determines the appearance of the control. The tabs can appear normally (on the top), on
the left, as buttons, or hidden (no tabs — your VBA code determines which page is displayed).
Value: Determines which page or tab is displayed. A value of 0 displays the first page, a value of
1 displays the second page, and so on.
By default, a MultiPage control has two pages. To add pages, right-click a tab and select New
Page from the resulting shortcut menu.
OptionButton control
OptionButtons are always used in groups of at least two. The following is a description of the
most useful OptionButton control properties:
Accelerator: A letter that lets the user select the option by using the keyboard. For example, if
the accelerator for an option button is C, pressing Alt+C selects the control.
GroupName: A name that identifies an option button as being associated with other option
buttons with the same GroupName property.
Value: If your dialog box contains more than one set of OptionButtons, you must change the
GroupName property for all OptionButtons in a particular set. Otherwise, all OptionButtons
become part of the same set. Alternatively, you can enclose each set of OptionButtons in a Frame
control, which automatically groups the OptionButtons in the frame.
ScrollBar control
When you add a ScrollBar control, you may make it horizontal or vertical. A SpinButton control
is similar to a ScrollBar control (described later). The difference is that with the ScrollBar, the
user can drag the control button to change the value in larger increments. Another difference is
that on a vertical ScrollBar when you hit the up button, the number drops, which is paradoxical.
As a result, a ScrollBar isn't always an appropriate replacement for a SpinButton.
SmallChange: The amount that the control’s value is modified by a click.
Clicking either side of the button changes the value of the control by a large amount.
The ScrollBar control comes in handy when you need to provide a value that spans a large range
of possibilities.
SpinButton control
The user may pick a value by clicking the SpinButton control, which contains two arrows (one
to increase the value and the other to decrease the value). Like a ScrollBar control, a SpinButton
may be oriented either horizontally or vertically.
If you use a ControlSource for a SpinButton, you should realize that the worksheet is
recalculated every time the control’s value is modified. As a result, changing the value from 0 to
12 causes the worksheet to be computed 12 times. If your worksheet takes a lengthy time to
compute, you may want to avoid utilizing a ControlSource to store the data.
TabStrip control
A TabStrip control is similar to a MultiPage control, but it is less user-friendly. In fact, I'm not
sure why this control exists in the first place. You can pretty much ignore it and use the
MultiPage control instead.
TextBox control
The user may input text into a TextBox control. Following are the most useful TextBox control
properties:
ControlSource: The address of a cell that consists of the text in the TextBox.
IntegralHeight: If True, the TextBox height adjusts automatically to display full lines of text
when the list is scrolled vertically. If False, the TextBox may display partial lines of text when
scrolled vertically.
TextAlign: This property controls how the text in the TextBox is aligned.
WordWrap: This property determines whether or not the control allows for word wrapping.
ScrollBars: Determines the type of scroll bars for the control: horizontal, vertical, both, or none.
When you add a TextBox control, its WordWrap property is set to True, and its MultiLine
property is set to False. What's the end result? Word wrap doesn't work!.
ToggleButton control
There are two states for a ToggleButton control: on and off. When you click the button, it
toggles between these two states and changes its look. Its value is either True (when pushed) or
False (when not touched) (not pressed).
Working with Dialog Box Controls
I'll go through how to interact with dialog box controls in a UserForm object in this part.
Moving and resizing controls
You can move and resize controls in dialog boxes using ordinary mouse methods after they've
been placed.
Ctrl + clicking on numerous controls will select them all. You may also "lasso" a set of controls
by clicking and dragging. When several controls are chosen, the Properties pane only shows the
properties that are shared by all of them. You may modify those common attributes once, and the
change will be applied to all controls you pick, saving you time over updating them one by one.
Aligning and spacing controls
Several actions are available on the Format menu in the VBE window to assist you in exactly
aligning and spacing the controls in a dialog box. Select the controls you wish to deal with before
using these instructions. I'm not going to describe these instructions since they operate as
expected.
When you choose numerous controls, the final one you pick has white handles instead of the
usual black handles. When you utilize the Format menu, the control with the white handles
serves as the foundation for aligning and resizing the other chosen components.
Accommodating keyboard users
Many users (including yourself) prefer to use the keyboard to move between dialog boxes:
hitting Tab or Shift + Tab cycles through the controls, while pressing a hotkey activates a
specific control immediately.
You must know the two factors to make sure that your dialog box functions effectively for
keyboard users:

Tab order is important


Accelerator buttons

Changing the tab order


When the user pushes Tab or Shift + Tab, the tab order dictates the order in which the controls
are active. When Excel initially shows a dialog box, the first control in the tab sequence has the
emphasis.
Select View Tab, then Order to change the order of the control tabs. You may also pick Tab
Order from the shortcut menu by right-clicking the dialog box.
All of the controls in the UserForm are listed in the Tab Order dialog box. The arrangement of
the tabs in the UserForm conforms to the order of the list elements. Select-control in the list and
then click the Move Up or Move Down button to modify its tab order. You may select several
controls (click while holding down Shift or Ctrl) and move them all at once.
Rather than utilizing the Tab Order dialog box, you may utilize the Properties window to change
the position of a control in the tab order. The TabIndex attribute of the first control in the tab
order is 0. Set the TabStop attribute of control to False to remove it from the tab order.
Frame and MultiPage controls operate as boxes for other components. Within a container
control, every control has its tab order. Select the Frame control before selecting the View Tab
Order command to configure the tab order for a collection of OptionButtons within a Frame
control.
Setting hotkeys
In most cases, you'll want to attach a hotkey or accelerator key to dialog box controls. You do so
by changing the Accelerator property in the Properties box to a letter. If a control doesn't have an
Accelerator attribute, you may still provide it direct keyboard access by utilizing a Label control.
That is, give the Label an accelerator key and place it exactly before the TextBox in the tab
order.
Aesthetics of Dialog Boxes
Dialog boxes might be attractive, unattractive, or something in between. A well-designed box is
pleasing to the sight and contains well-sized positioning buttons. The user is confused by bad-
looking dialog boxes, which have misaligned buttons and give the appearance that the developer
didn't prepare ahead (or a clue).
Reduce the number of controls on your form as much as possible. If you have a large number of
controls (more than ten), consider utilizing a MultiPage control to divide the work the user must
complete into logical (and smaller) parts.
Making your dialog boxes seem like the Excel built-in dialog boxes is a good guideline to
follow. You can practically replicate all of the functionality of the Excel dialog boxes as you get
more skilled with dialog box creation.
CHAPTER EIGHTEEN
USERFORM TECHNIQUES AND TRICKS
The preceding chapters demonstrated how to create a UserForm (which includes a custom dialog
box), add controls to the UserForm, and change the attributes of some of the controls. These
abilities, however, will be useless unless you know how to incorporate UserForms into your
VBA code. This chapter fills in the blanks and teaches you some important tips and tricks in the
process.
Using Dialog Boxes
You usually create VBA code that accomplishes the following when you utilize a custom dialog
box in your application:
The UserForm controls are initialized. You could, for example, add code to set the controls'
default settings.
Responds to events that occur for the different controls, such as a CommandButton being
clicked.
Validates the data that the user has supplied (if the user did not cancel the dialog box). It is not
always required to do this step.
Uses the information given by the user to take action (if the information is valid).
A UserForm Example
This illustration exemplifies the five principles I discussed in the prior section. The name is
obtained using a TextBox control, and the sex is obtained using three OptionButtons (Male,
Female, or Unknown). The data obtained in the dialog box is subsequently transmitted to the
worksheet's next blank row.

Creating the dialog box


To enable the VBE, press Alt+F11.
Select the empty workbook and choose Insert UserForm.
The project is given an empty UserForm.
Change the Caption property of the UserForm to Get Name and Sex.
Press F4 if the Properties window isn't displayed. Follow the directions on the
screen.
Take a few minutes to develop this UserForm using the previous information if you're following
along on your computer
In certain circumstances, replicating an existing control may be more convenient than creating a
new one. To duplicate a control, hold down Ctrl while dragging it.
Making the macro available
The following stages make it simple for the user to carry out the procedure:

Excel should be opened.


In the Form Controls section, choose Developer Controls Insert and click the
Button icon.
To make the button, drag it into the spreadsheet.
The Macro Assign dialog box opens.
The GetData macro should be assigned to the button.
Change the caption of the button to Data Entry.
You may add an icon to your Quick Access toolbar if you want to go very fancy. The GetData
macro is then launched by clicking the icon. To do so, right-click your Quick Access toolbar and
choose Customize Quick Access Toolbar, which opens the Excel Options dialog box's Quick
Access Toolbar Tab. Select Macros from the Choose Commands From drop-down menu. Then
click Add after selecting the GetData macro. If you like, you can modify the icon by clicking the
Modify button.
Trying out your dialog box
To test your dialog box, follow these steps:

Click the Data Entry button on the worksheet, or if you have one, the Quick Access
toolbar icon.
The dialog box displays. In the edit box, type some text
Enter or close the window.
Nothing occurs, which is acceptable given that you haven't yet defined any
procedures.
To exit the dialog window, click the X button on the title bar.

Adding event-handler procedures


In this part, I'll show you how to construct methods to handle the events that happen when the
dialog box appears.
Take the following steps:

To enable the VBE, press Alt+F11, then check that the UserForm is visible.
Double-click the UserForm's Close button.
The VBE opens the UserForm's Code window and adds an empty method called
CloseButton Click.
Make the following changes to the procedure:
Private Sub CloseButton_Click()
Unload UserForm1
End Sub
When the user presses the Close button, this code simply unloads the dialog box from memory.
Redisplay UserForm1 by pressing Shift+F7.
Enter the following process by double-clicking the Enter button:
Private Sub EnterButton_Click()
Dim NextRow As Long
' Make sure Sheet1 is active
Sheets("Sheet1").Activate
' Determine the next empty row
NextRow = Application.WorksheetFunction. _
CountA(Range("A:A")) + 1
' Transfer the name
Cells(NextRow, 1) = TextName.Text
' Transfer the sex
If OptionMale Then Cells(NextRow, 2) = "Male"
If OptionFemale Then Cells(NextRow, 2) = "Female"
If OptionUnknown Then Cells(NextRow, 2) = "Unknown"
' Clear the controls for the next entry
TextName.Text = ""
OptionUnknown = True
TextName.SetFocus
End Sub
Now open Excel and click the Data Entry option to rerun the operation.

The EnterButton Click routine operates as follows:

COUNTA function in Excel is then used to count the number of items in column A
and calculate the column's next blank cell.
The text from the TextBox is then transferred to column A via the process.
It then determines which OptionButton was picked using a sequence of If
statements and puts the relevant text (Male, Female, or Unknown) to column B.
The dialog box is then reset to create room for the following item. Because the user
is likely to wish to submit more data, hitting the Enter button does not dismiss the
dialog window. Click the Close button to finish entering data.

Validating the data


Play around with this procedure some more, and you'll see that the macro has a flaw: it doesn't
check to see whether the user has entered a name in the TextBox. The following code, which is
put before the text is transmitted to the worksheet in the EnterButton Click method, guarantees
that the user writes some text in the TextBox.

Now the dialog box works


After you've made these changes, you'll see that the dialog box works perfectly. In real life, you'd
probably need more information than simply a person's name and gender. However, the
fundamental fundamentals remain the same. All you have to do now is deal with additional
UserForm controls.
Another thing to keep in mind is that the counting for the NextRow variable will be incorrect if
the data does not begin in row 1 or if the data region includes any blank rows. The COUNTA
function is used to count the number of cells in column A, with the assumption that no blank
cells exist above the final name.
Another method for detecting the next empty row is as follows:
NextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
The statement mimics pushing End, hitting the up-arrow key, and then going down one row by
activating the final cell in column A, pressing End, and then pressing the up-arrow key. Even if
the data area doesn't start in row 1 and comprises blank rows, the cell pointer will be in the next
empty cell in column A if you do it manually.
More UserForm Examples
I could probably fill a whole book with fascinating and helpful ideas for dealing with custom
dialog boxes, but there are only so many pages in this book, so I'll end with a few more
examples.
A ListBox example
ListBoxes are valuable controls, but they may be difficult to deal with. You must first populate
the ListBox with items before showing a dialog box with a ListBox. You must then determine
which item(s) the user selected after the dialog box has been closed.
The following properties and methods are important to know when working with ListBoxes:
AddItem: This function is used to add a new item to a ListBox.
ListCount: The number of items in the ListBox is returned by this property.
ListIndex: This property either returns or sets the index number of the currently selected item
(single selections only). The first item has a ListIndex of 0; the second item has a ListIndex of 1.
(not 1).
This attribute specifies whether or not the user may choose multiple items from the ListBox.
RemoveAllItems: To remove all items from a ListBox, use this method.
Selected: This property returns an array of objects that have been selected (applicable only when
multiple selections are allowed).
Value: The chosen item in a ListBox is returned via this property.
ComboBoxes provide the majority of methods and attributes as ListBoxes. So, after you've
worked out how to deal with ListBoxes, you can apply what you've learned to ComboBoxes.
Filling a ListBox
Start by utilizing a blank worksheet to keep things simple. This section's example assumes
the following:
You've added a UserForm to your page.
A ListBox control called ListBox1 is included in the UserForm.
OKButton is a CommandButton on the UserForm.
The CancelButton CommandButton on the UserForm includes the following event-handler
procedure:
Private Sub CancelButton_Click()
Unload UserForm1
End Sub
In the UserForm's Initialize process, the following method is stored. Take the following steps:
Add the form's startup code:
Sub UserForm_Initialize()
' Fill the list box
With ListBox1
.AddItem "January"
.AddItem "February"
.AddItem "March"
.AddItem "April"
.AddItem "May"
.AddItem "June"
.AddItem "July"
.AddItem "August"
.AddItem "September"
.AddItem "October"
.AddItem "November"
.AddItem "December"
End With
' Select the first list item
ListBox1.ListIndex = 0
End Sub
When your UserForm is loaded, this startup code executes automatically. When you use the
UserForm's Show function, the code is run, and your ListBox is filled with 12 items, each of
which was added using the AddItem method.
To show the dialog window, insert a VBA module and write the following short Sub procedure:
Sub ShowList()
UserForm1.Show
End Sub

Determining the selected item


The code above just shows a dialog window with a ListBox containing month names. A
mechanism to detect which item in the ListBox is chosen is still lacking.
This operation shows a message box with the specified item number and item name.
The ListIndex property returns –1 if no item in the ListBox is chosen. This will never be the case
for this ListBox since the first item was chosen by code in the UserForm Initialize method.
Unselecting one item without choosing another is impossible. If the user does not choose a
month, there will always be a chosen item.
Determining multiple selections
Set the MultiSelect property to 1 or 2 to allow multiple selections in a ListBox. You may
accomplish this either at design time using the Properties window or at runtime with a VBA line
like this:
UserForm1.ListBox1.MultiSelect = 1
Choosing a range
The Create Table dialog box, which appears when you pick Home Insert Tables Table, is an
example of this sort of range selection. The range picker control in the Create Table dialog box
includes Excel's best estimate for the range to be converted; however, you may adjust the range
by choosing cells in the worksheet.
Add a RefEdit control to your dialog box to facilitate range selection. The process boldens the
range when the user hits OK.
Using a TextBox and a SpinButton
The user may specify a number by clicking arrows on a SpinButton control. Because this control
simply has arrows and no text, you'll need the means to show the chosen number. The usage of a
Label control is one possibility, but it has one drawback: the user cannot input text in a Label.
Using a TextBox is a better option.
Excel frequently uses the SpinButton and TextBox controls together as a natural pair. The
SpinButton and associated TextBox should, in theory, always be in sync: when the user presses
the SpinButton, the value of the SpinButton should display in the TextBox. In addition, if the
user types a value into the TextBox, the SpinButton should reflect that value
The controls on this UserForm are as follows:
A SpinButton called SpinButton1 with the Min and Max properties set to 1 and 100,
respectively.
TextBox1 is a TextBox that is placed to the left of the SpinButton.
OKButton is a CommandButton.
The SpinButton's event-handler method is as follows. The Change event is triggered anytime the
SpinButton value is updated, and this code handles it. This procedure assigns the SpinButton's
value to the TextBox when the SpinButton's value changes (when it's clicked). To construct this
process, double-click the SpinButton to open the UserForm's Code window. Then type in the
following code:
Private Sub SpinButton1_Change()
TextBox1.Text = SpinButton1.Value
End Sub
The TextBox event handler, which is listed next, is a little more complicated. To construct this
process, double-click the TextBox to open the UserForm's Code window. When the user updates
the text in the TextBox, this process is called.
Private Sub TextBox1_Change()
Dim NewVal As Long
NewVal = Val(TextBox1.Text)
If NewVal >= SpinButton1.Min And _
NewVal <= SpinButton1.Max Then _
SpinButton1.Value = NewVal
End Sub
The text in the TextBox is stored in a variable in this operation. It then double-checks that the
value is within the acceptable range.
When you use F8 to single-step through the code in debugging mode, you'll observe that the
change event of the SpinButton fires immediately after the line SpinButton1.Value = NewVal is
performed. However, you may imagine that this impact could have unexpected consequences on
your UserForm. Confused? Just keep in mind that if your code modifies a control's Value, the
Change event for that control will fire.
How this example works
When the EnterRandomNumbers method is run, it inserts a duplicate of UserForm1 into the
ProgressIndicator module variable. The width of the LabelProgress label is then set to 0 and the
UserForm is shown in a modeless state (so the code will continue to run).
The active sheet is checked by the EnterRandomNumber method. The UserForm
(ProgressIndicator) is closed if it isn't a worksheet, and the method finishes with no action.
The technique performs the following if the current sheet is a worksheet:
Removes all data from the current worksheet's cells.
Inserts a random integer after looping over the rows and columns (given by the RowMax and
ColMax variables).
The Counter variable is incremented, and the percentage finished is calculated (which is stored in
the PctDone variable).
Calls the UpdateProgress procedure, which updates the caption of the frame control and changes
the width of the LabelProgress label to show the % finished.
The UserForm is unloaded.
Because the code is performing extra work updating the UserForm when you utilize a progress
indicator, your macro will run a little slower. If speed is crucial, you should reconsider utilizing a
progress indication.
To utilize this approach on your own, you'll need to find out how to track the macro's
development, which differs based on the macro. Then, while your macro is running, call the
UpdateProgress method at regular intervals.
Creating a modeless tabbed dialog box
Tabbed dialog boxes are helpful because they allow you to deliver data in discrete, well-
organized pieces. The Format Cells dialog box in Excel (which appears when you right-click a
cell and choose Format Cells) is an excellent example. Three tabs are used in this dialog box to
assist arrange some of Excel's display settings.
The MultiPage control makes creating your own tabbed dialog boxes very simple. Due to the
single document interface in Excel 2013 and Excel 2016, modeless UserForms behave
differently (every workbook displays in its own separate window). In prior versions of Excel, a
modeless UserForm remained at the top of the screen regardless of whatever workbook was
open. A modeless UserForm only remains on top of the workbook window that was active when
the UserForm was displayed in Excel 2013 and later.
When using the MultiPage control to build a tabbed dialog box, keep the following
considerations in mind:
Per dialog box, only one MultiPage control should be used.
Use the MultiPage control instead of the TabStrip control.
Place certain controls outside the MultiPage control to keep them visible at all times.
When you right-click a tab on the MultiPage control, a shortcut menu appears, allowing you to
add, delete, rename, or relocate the tab.
To activate a page during design, click a tab. After it's been active, use standard processes to add
further controls to the page.
Click the border of the MultiPage control to choose the control itself (rather than a page on the
control).
The Style and TabOrientation attributes of the MultiPage control may be changed to vary the
appearance of the control.
A MultiPage control's Value attribute decides which page is shown. If you set the Value value to
0, for example, the first page of the MultiPage control is shown.
Displaying a chart in a UserForm
When you need to show a chart in a UserForm, Excel does not give a convenient means to do so.
As a result, think beyond the box. This section explains how to use a method to show one or
more charts in a UserForm.
Image control is seen on the UserForm. The approach is to save the chart as a GIF file using
VBA code and then designate that file as the Picture attribute of the Image control (which loads
the image from your disk). The Previous and Next buttons change the chart that is presented.

A Dialog Box Checklist


This chapter concludes with a checklist for designing dialog boxes:

Are the controls in a logical order?


Is the size of related controls the same?
Is there an equitable distribution of controls?
Is there a suitable caption for the dialog box?
Is the dialog box too much for you? If that's the case, you could wish to employ a
succession of dialog boxes or break them up into many pages using a MultiPage
control.
Are there any duplicate accelerator keys?
Are the controls arranged in a logical, function-based order?
Is the tab arrangement in the right place? The user should be able to navigate the
dialog box via tabs and access the controls in order.
Will your dialog box fit on the screen at the lowest possible resolution (often
1024x768 mode)? In other words, if you create your dialog box in a high-quality
video mode, it may be too large to fit on a screen with a lesser resolution.
Is the necessary validation configured for all TextBox controls?
Is the MultiLine property set to True if you plan to utilize the WordWrap property?
Is it true that all ScrollBars and SpinButtons can only accept valid values?
Is the MultiSelect attribute correctly set on all ListBoxes?
The easiest approach to learning how to make custom dialog boxes is to make a lot
of them. Begin with the basics and play around with the controls and their
attributes. Also, don't overlook the Help system; it's the greatest place to go for
information on each control and feature.
CHAPTER NINETEEN
ACCESSING YOUR MACROS THROUGH THE USER
INTERFACE
People utilized drop-down menus and toolbars back then. Microsoft Office now uses Ribbon as
its user interface, and Ribbon fever has extended to other products, including Windows.
You would anticipate VBA to allow you to build new Ribbon commands. The bad news is that it
is impossible to change the Ribbon using VBA. The good news is that your situation isn't
hopeless. This chapter explains how to utilize Excel's user interface in a few different ways.
Customizing the Ribbon
This section explains how to personalize the Ribbon. You can edit the Ribbon manually, but you
can't use VBA to do so. Unfortunately, this is true. If you're writing an application and want to
add a few additional buttons to the Ribbon, for example, you'll need to program such
modifications outside of Excel using RibbonX.
Manually customizing the Ribbon
The Ribbon may be customized in the following ways:
Tabs
Create a brand-new custom tab.
Delete any custom tabs you've created.
To tab, add a new group.
Rearrange the tabs in whatever way you choose.
A tab's name may be changed.
Hide the pre-installed tabs.

Groups
New custom groups may be created.
Create a custom group and add commands to it.
Commands in custom groups should be removed.
A tab's groups may be removed.
Transfer a group to a new tab.
Within a tab, change the order of the groups.
A group's name should be changed.
Although that is a rather thorough list of customization choices, you will be unable to do
the following tasks (no matter how hard you try):

Built-in tabs cannot be removed, although they may be hidden.


It is not possible to delete commands from built-in groups.
The sequence of instructions in a built-in group cannot be changed.
In the Customize Ribbon section of the Excel Options dialog box, you may make manual
modifications to the Ribbon. Right-click anywhere on the Ribbon and pick Customize the
Ribbon from the shortcut menu to bring up this dialog box quickly.
Configuring the Ribbon is comparable to customizing the Quick Access toolbar, which is
covered later in this chapter. The only difference is that you must pick where the command
should be placed in the Ribbon. Follow the steps below to get started:
To see different groupings of commands, use the Choose Commands From the drop-down list on
the left.
Locate and pick the command from the list box on the left.
Choose a set of tabs from the drop-down list on the right (labeled Customize the Ribbon)
Tool tabs relate to the context tabs that display when a certain item is chosen; main tabs refer to
the tabs that are always visible.
Select the tab and group where you want the command to go in the list box on the right.
To extend the hierarchical lists, click the plus-sign controls.
To add the chosen command from the left to the group on the right, click the Add button.
Remember that you may create a new tab with the New Tab button and a new group inside a tab
with the New Group button. New tabs and groups are assigned generic names, so you'll want to
give them titles that are more relevant. Rename the chosen tab or group using the Rename
button. Built-in tabs and groups may also be renamed.
I created a custom group to the View tab called Text To Speech, as seen in the picture (to the
right of the Zoom group). There are five commands in this new category.

A built-in tab cannot be removed; however, it may be hidden by unchecking the check box next
to its name.
Adding a macro to the Ribbon
Fortunately, macros may be added to the Ribbon as well. Follow the steps in the previous
section, but in Step 1 choose Macros from the left-hand drop-down menu. All of the macros that
are presently available are listed and ready to be placed on the Ribbon. All you have to do now is
choose a tab and a group for the macro.
If you add a macro to the Ribbon, the macro command appears on the Ribbon even if the
workbook containing the macro is not open. When you click the command, it opens the
worksheet that includes the macro and then runs it.
If you add a button to the Ribbon that runs a macro, the Ribbon change only affects your copy of
Excel. The Ribbon changes are not included in the worksheet. In other words, if you give a
coworker your worksheet, the Ribbons changes you made will not display on their machine.
Using XML to customize the Ribbon
You may wish to change the Ribbon automatically when a workbook or add-in is opened in
various cases.
With Excel 2022 and other versions, you can make automated changes to the Ribbon, but it's not
a straightforward operation. Writing XML code in a text editor, copying that XML file into the
workbook file, editing a bunch of XML files (which are also stashed away inside the Excel file,
which is nothing more than a zipped container of individual files), and then writing VBA
procedures to handle the clicking of the controls you put in the XML file are all part of the
Ribbon modification process.
Fortunately, the software is available to aid you in customizing the Ribbon, but you must be
knowledgeable with XML to do it.
Adding a new item to the Cell shortcut menu
This section includes code for adding a new item to the shortcut menu that appears when you
right-click a cell. I won't get into technical details, but you are to customize these examples to
your specific requirements.
The Change Case utility is described in Chapter 16. By making it available from the Cell
shortcut menu, you can improve the utility.
To the Cell shortcut menu, the AddToShortcut function adds a new menu item. You can change
the Caption and OnAction properties of the object named NewControl to point to your own
macros.
When you make a change to a shortcut menu, it stays in effect until you restart Excel. In other
words, when you close the worksheet containing the VBA code, updated shortcut menus do not
automatically reset. As a result, if you write code to change the appearance of a shortcut menu,
you nearly always write code to reverse the effect of your change.
The procedure DeleteFromShortcut deletes the new menu item from the Cell shortcut menu:
Sub DeleteFromShortcut()
On Error Resume Next
Application.CommandBars("Cell").Controls _
("&Change Case").Delete
End Sub
When you right-click a cell, a new menu item appears, as shown in the image.

After declaring a few variables, the first actual command executes the DeleteFromShortcut
method. This sentence ensures that the shortcut Cell menu contains only one Change Case menu
item. Try commenting out that line (starting the line with an apostrophe) and executing the
method a few times — but don't get too carried away! When you right-click a cell, the Change
Case menu item appears in many places. Run DeleteFromShortcut many times to remove all of
the entries (once for each extra menu item).
PART FIVE
PUTTING IT ALL TOGETHER
CHAPTER TWENTY
CREATING WORKSHEET FUNCTIONS
VBA's biggest draw for many macro enthusiasts is the ability to construct custom worksheet
functions that appear, work, and feel just like those included in Microsoft Excel. A custom
function has the added benefit of functioning exactly as you want it to (because you wrote it). In
Chapter 5, I present custom functions. In this chapter, I get down to business and share a few
tips and tricks.
Make Custom Functions to Make Your Work Easier
You're probably aware of Excel's worksheet functions; even Excel newbies can utilize basic
worksheet functions like SUM, AVERAGE, and IF. Excel 2016 has around 450 predefined
worksheet functions, according to my count. If that isn't enough, you can also use VBA to build
functions.
You might ask why you'd ever need to develop functions with all the capabilities available in
Excel and VBA. The solution is to make your task easier. Custom functions may be highly handy
in spreadsheet formulas and VBA procedures with a little planning. Creating a custom function
can often drastically shorten a calculation. Shorter formulas are, after all, easier to read and deal
with.
What Custom Worksheet Functions Can't Do?
It's critical that you understand a vital point as you create custom functions for use in spreadsheet
formulas. Function procedures in VBA worksheets are generally passive. A Function procedure's
code, for example, cannot alter ranges, change formatting, or do many of the other things that a
Sub procedure can. An illustration might be useful.
Here is a formula that makes use of the function. Only if cell A1 already has a comment will it
function. The comment is modified when the formula is calculated.
=ChangeComment(A1,"I changed the comment!")
Working with Function Examples
A function with one argument
This section's single-argument function is for sales managers who need to figure out how much
their salespeople are paid in commissions. The commission rate is determined by the amount of
money sold each month; individuals who sell more money get a greater commission rate. The
method returns the commission amount based on monthly sales (the function's lone — and
needed — input). This example's calculations are based on the image below.
You may compute commissions for sales amounts entered into a worksheet using a variety of
methods.
You may write something like this in a long worksheet formula:
=IF(AND(A1>=0,A1<=9999.99),A1*0.08,IF(AND(A1>=10000,
A1<=19999.99),A1*0.105,IF(AND(A1>=20000,A1<=39999.99),
A1*0.12,IF(A1>=40000,A1*0.14,0))))
This is a problematic strategy for several reasons. To begin with, the formula is unnecessarily
complicated. A better technique is to generate a table of commission values and compute the
commissions using the LOOKUP table function:
=VLOOKUP(A1,Table,2)*A1
A function with two arguments
The following example builds on the previous one. Consider this scenario: The sales manager
launches a new strategy to reward long-term employees: For every year the salesperson has been
with the company, the total commission paid increases by 1%.
I changed the custom Commission function (described in the previous section) to accept two
arguments, one of which is necessary.
A function with a range argument
It's not difficult to use a worksheet range as an argument; Excel takes care of all the specifics.
Another function that takes a range argument is this one. Assume you want to find the average of
the five highest values in the Data range. Because there isn't a function in Excel that can achieve
this, you'll have to develop a formula:
=(LARGE(Data,1)+LARGE(Data,2)+LARGE(Data,3)+
LARGE(Data,4)+LARGE(Data,5))/5
The LARGE function in Excel returns the nth largest value in a range. It multiplies the five
largest values in the Data range by five and divides the result by five. The formula works well,
but it's a bit cumbersome.
Wouldn't it be easier if Excel had a TopAvg function? Then you might use the (nonexistent)
function to compute the average:
=TopAvg(Data,5)
InRange (a worksheet range) and N are the two inputs for this function (the number of values to
average). It begins by setting the Sum variable to zero. The sum of the N greatest values in the
range is then calculated using a For-Next loop. Within the loop, you'll notice that I'm using the
Excel LARGE function. Finally, the value of the Sum divided by N is allocated to TopAvg.

A function with an optional argument


Optional arguments are used by many Excel built-in worksheet functions.
LEFT(text[,num chars])
The first parameter (in square brackets) is necessary, whereas the second (in parentheses) is
optional.
As a result, the formulas below provide the same result:
=LEFT(A1,1)
=LEFT(A1)
I utilize the Randomize line to ensure that each time the workbook is opened, a different random
number "seed" is chosen. Without this statement, the workbook generates the same random
integers every time it is opened.
This function can be used to pick lottery numbers, choose a winner from a list of names, and so
on.
Introducing Wrapper Functions
This section includes some highly useful custom worksheet routines that are reasonably basic.
These routines are referred to as function wrapper functions because they contain code that
wraps around intrinsic VBA parts. They let you employ VBA functions in worksheet formulas,
in other words.
In essence, this function allows your formulas to access the Application object's UserName
attribute.
Additional wrapper functions are included in the remainder of this section.
The ExtractElement function
This is without a doubt my favorite wrapper method. It extracts a substring from a text string
with several parts separated by a separator character.
=ExtractElement("dog horse cow cat", 3, " ")
The code, which is a wrapper for VBA's Split function, is as follows:
=ExtractElement("dog horse cow cat", 3, " ")
The ExtractElement function is used in spreadsheet formulas, as shown in the image. The text
string is in Column A, the element number to be extracted is in Column B, and the delimiter is in
Column C. (cells that appear to be blank contain a space character).
The SayIt function
This simple function is a wrapper for the Application. Speech object's Speak method. The
argument is "spoken" by a synthesized voice.

Here's an illustration:
=IF(C10>10000,SayIt("Over budget"),"OK")
Cell C10 is checked by the formula. If the amount exceeds 10,000, the function speaks the text
"Over budget," whereas if the value is not more than 10,000, the function displays the word OK
(and says nothing).
Only use a small amount. Also, keep in mind that this function is evaluated each time the
worksheet is calculated, so if you're making a lot of changes, the voice may become very
annoying. This function is more likely to be used for entertainment.
The IsLike function
The Like operator in VBA is a powerful tool for comparing text strings. Check out the VBA
Help system for further information.
This function gives your spreadsheet formulas the power:

Working with Functions That Return an Array


One of Excel's most useful tools is array formulas. If you're used to working with array formulas,
you'll be pleased to learn that VBA functions can return an array.
Returning a sorted list
This section's custom function does exactly that: it accepts a single-column range of cells as an
argument and returns a sorted array of those cells. The illustration depicts how it works. Some
names can be found in the range A2:A13. This multicell array formula is found in the C2:C13
range.
=Sorted(A2:A13)
Using the Insert Function Dialog Box
The Insert Function dialog box does not show function procedures defined with the Private
keyword. As a result, you should declare a Function procedure as Private if it's intended to be
used only by other VBA processes (and not in formulae).
Displaying the function’s description
Each built-in function is described in the Insert Function dialog box. A custom function, on the
other hand, displays the following text as its explanation, as shown in the image: No help
provided.
Open the worksheet that has the custom function
Developer Code Macros (or Alt+F8) is the option to select.
The Macro dialog box appears.
Type the name of the function in the Macro Name field.
You must type the name of the function because it does not appear in the list of macros.
Select the Options tab.
A dialog window called Macro Options displays.
Type a description of the function in the Description area.
Click the OK button.
Click the Cancel button.
The description of your function is now displayed in the Insert Function dialog box.

Adding argument descriptions


The Function Arguments dialog box displays descriptions of the arguments when you use the
Insert Function dialog box to access a built-in function.
Adding argument descriptions was previously impossible. However, Microsoft finally
implemented this feature with Excel 2010. The MacroOptions method is used to provide
argument descriptions.
This chapter covers a lot of ground when it comes to creating custom worksheet functions. When
creating functions for your own work, use these examples as a guide. The online help, as usual,
provides additional information. Turn to Chapter 21 if you want to find out how to make your
custom functions more accessible by storing them in an add-in.
CHAPTER TWENTY-ONE
CREATING EXCEL ADD-INS
One of the slickest features of Excel — at least in my perspective — is the capability to develop
add-ins. In this chapter, I explain why I enjoy this feature and show you how to construct add-ins
by using solely the tools built into Excel.
Add-Ins Defined
The Add-In is a feature of excel that extends the capabilities of Excel. Some of them bring in lots
of worksheet functions. These functions are used in formulae while some add new instructions or
functions. The add-in works well when it is designed perfectly. It will mix with the initial
interface.
The Analysis ToolPak and Solver: These are two add-ins that come standard with Excel. Excel
add-ins are also available from third-party vendors or as shareware. An example of an add-in is
My Power Utility Pak
Add-ins may be created by any informed user, although VBA programming abilities are
necessary.
Reasons to Create Add-Ins
Make accessing your code more challenging. Casual users are unable to examine the sheets in
the workbook when a program is distributed as an add-in (and its VBA project is protected). You
can make it more difficult for people to copy your VBA code if you employ exclusive strategies.
However, Excel's security protections aren't perfect, and password-cracking software is
accessible.
Avoid being perplexed. When a user installs your application as an add-in, the file is hidden,
making it less likely to confuse or obstruct beginner users. The contents of an add-in, unlike a
hidden workbook, cannot be revealed.
Access to worksheet functionalities should be made easier. The workbook name qualifier is
not required for custom worksheet functions stored in an add-in.
Make it easier for users to get around. After you've found your add-location, in's it shows up
in the Add-Ins dialog box with a pleasant name and a brief description of what it does. Your add-
in can be easily enabled or disabled by the user.
Working with Add-Ins
Choose File > Options > Add-Ins to bring up this dialog box. Then, at the bottom of this dialog
page, pick Excel Add-Ins from the drop-down list and click Go. Choose Developer Add-Ins
Add-Ins if you want to skip ahead. However, pressing Alt+TI is the simplest method (the old
Excel 2003 keyboard shortcut).
Checkmarks in this list indicate any add-ins that are currently open. By selecting or deselecting
the checkboxes in the Add-Ins dialog box, you can launch and close add-ins.
You may also use the File Open Browse command to open most add-in files (as if they were
workbook files). The Add-Ins dialog box does not show an add-in that has been opened in this
way. Furthermore, if you open the add-in with the Open command, you won't be able to close it
with File Close. Only closing and restarting Excel or developing a macro to close the add-in will
remove the add-in.
You may or may not notice anything different when you open an add-in. However, in many
cases, the Ribbon is altered in some way; Excel adds a new tab or one or more new groups to an
existing tab. When you open the Analysis ToolPak add-in, for example, a new item called
Analysis Data Analysis appears on the Data tab.
Understanding the Basics of Add-Ins
Although any workbook can be converted to an add-in, not all workbooks benefit from it. A
macro-free workbook is a useless add-in. A worksheet with general-purpose macros is an
excellent add-in. Creating an add-in isn't difficult, but it does necessitate some additional effort.
To make an add-in from a regular workbook file, follow these steps:
Looking at an Add-In Example
In this section, I'll go over the fundamentals of designing a useful add-in. The example is based
on the text conversion utility Change Case, which I discuss in Chapter 16.
This example's XLSM version may be found on the book's website. This worksheet can be used
to construct an add-in.
Setting up the workbook
The utility's original version had settings for uppercase, lowercase, and appropriate case. I add
two more choices to the UserForm in the add-in version so that it has the same options as the
built-in tool in Microsoft Word.
Sentence Case: Uppercases the initial letter and lowercases the other letters in the sentence.
Toggle Case converts all capital characters to lowercase and vice versa.
Testing the workbook
In a new workbook, fill in the blanks in some cells
Enter various forms of data, such as text, values, and formulas, for testing reasons. Alternatively,
you may just open an existing workbook and use it for your testing. Remember that any changes
you make to the worksheet are permanent, so make a backup.
Choose one or more cells to work with (or entire rows and columns).
Choose the new Change Case command from your Cell (or Row or Column) shortcut menu to
run the ChangeCase macro.
The most likely cause for the Change Case command not appearing on your shortcut menu is that
you did not enable macros when you entered the change case.
Workbook in xlsm format. Close the workbook and then reopen it, making sure macros are
enabled.
Protecting the VBA code
Select the change case after it has been activated.
Open the xlsm workbook.
Select Tools VBAProject Properties and then the Protection tab in the resulting
dialog box.
Check the box labeled "Lock Project for Viewing" and type in a password (twice).
Click the OK button.
Save the workbook in the VBE by selecting File Save or by returning to the Excel
window and selecting File Save.

Creating the add-in


You've verified the change case.xlsm file is working properly at this point. The creation of the
add-in is the following stage.
Take the following steps:

Reactivate Excel if necessary.


Activate the case.xlsm workbook and select File Save As Browse from the File
menu.
The Save As dialog box appears in Excel.
Choose Add-In (*.xlam) from the Save as Type drop-down box.
Click Save after you've specified the location.
The original XLSM version remains open while a new add-in file (with an.xlam
extension) is produced.

Opening the add-in


Close the XLSM workbook before launching the add-in you built from it to avoid any confusion.
Follow these steps to open the add-in:

Select Developer Add-Ins Add-Ins (or press Alt+TI) from the drop-down menu.
The Add-Ins dialog box appears in Excel.
Select Browse from the menu.
Locate and select the newly created add-in.
To close the Browse dialog box, click OK.
The Add-Ins dialog box lists your new add-in when you've found it.
Select the new Add-In.
Click OK.
The add-in is launched by Excel. It's now compatible with all of your workbooks.
The add-in will launch every time you start Excel as long as it is chosen in the Add-
Ins dialog box.

Distributing the add-in


If you're feeling kind, you may simply provide a copy of the XLAM file to other Excel users to
distribute the add-in. (The XLSM version isn't required.) When they launch the add-in and pick a
range, one or more rows, or one or more columns, the new Change Case command shows on the
shortcut menu. Others won't be able to see your macro code unless they know the password if
you lock the VBA project with a password.
Modifying the add-in
An add-in, like any other worksheet, can be changed:

If it isn't already open, open your XLAM file.

On the VBE.
Double-click the project's name.
If you password-protected the code, you'll be asked for it.
Click OK after entering your password.
Make the necessary adjustments to the code.
By selecting File Save, you can save the file.
PART SIX
OTHER EXCEL PROGRAMMING ETHICS WORTH
KNOWING
CHAPTER TWENTY-TWO
TEN HANDY VISUAL BASIC EDITORS TIPS
If you're going to be working with the Visual Basic Editor, why not take advantage of some of
the built-in tools that can help you out? These suggestions can dramatically improve your macro
programming experience, whether you're a fresh-faced analyst new to programming or a jaded
veteran living on Mountain Dew and sunflower snacks.
Applying Block Comments
Any statement that consists of the single apostrophe in front of it is effectively skipped by Excel.
Commenting out code is what it's called. The single apostrophe can also be utilized in adding
comments or notes to your code.

Commenting out many lines of code can be useful at times. You can test certain lines of code
while directing Excel to ignore the commented lines in this manner.
You can use the Edit toolbar to comment out entire blocks of code instead of commenting out
one line at a time.
By selecting View Toolbars Edit, you may access the Edit toolbar.
Select the lines of code you want to comment out, then click the Edit toolbar's Comment Block
icon.
By sliding the Edit toolbar up to the VBE menu bar, you can ensure that it is always visible. It
firmly establishes itself in the location you specify.
Copying Multiple Lines of Code at Once
You can copy large blocks of code by highlighting the lines you need and then dragging the
block to where you need it while holding down the Ctrl key on your computer. This is a tried-
and-true Windows method that works even while dragging modules across the screen.
When your mouse pointer shows a + symbol next to it, you're dragging a copy.
Jumping between Modules and Procedures
It can be difficult to switch between modules and procedures after your macro code cache has
grown.
Using a few shortcuts can help alleviate the pain:
To swiftly switch between modules, press Ctrl + Tab.
To switch between procedures within a module, press Ctrl + Page Up and Ctrl + Page Down.
Teleporting to Your Functions
When evaluating a macro, you can come across a variable or function name that clearly refers to
another line of code. Instead of searching through all of the modules to identify where that
function or variable name originates, simply set your mouse on the name and hit Shift+F2.
You're teleported to the origin of that function or variable name, as seen in the image.

You can get back to where you started by pressing Ctrl +Shift +F2.
Staying in the Right Procedure
It can be difficult to browse through a procedure without accidentally scrolling into another when
your modules have several procedures. You frequently find yourself scrolling up and down in an
attempt to return to the correct code.
Click the Procedure View button in the lower-left corner of the VBE to prevent this. This button
restricts navigation to the procedure you're now in.

Stepping Through Your Code


VBA provides a number of tools to assist you in "debugging" your code. Debugging in
programming is the process of identifying and correcting potential programming mistakes.
Going through your code is a valuable debugging tool when you do it one line at a time. You
literally watch as each line of the code executes when you step through the code.
Place your cursor anywhere within your macro and hit F8 to step through it. Debug mode is on
for your macro.
To run the highlighted line of code and continue to the next line, press F8 once more. You can
keep hitting F8 to watch each line of the macro run until it finishes.
You may also see the current value of any string or integer variable by hovering over it while
going through the code.
To get out of debugging mode, choose Debug ⇒ Step Out.
Stepping to a Specific Line in Your Code
By moving your cursor anywhere within your macro and pressing F8, you can step through your
code as shown in the previous section.
This is fantastic, but what if you want to begin stepping through your code at a particular line?
That's exactly what you can do by simply moving the arrow!
When a line of code is highlighted in debug mode, drag the arrow in the left margin of the Code
window higher or downward, dropping it on the line of code you wish to execute next.
Stopping Your Code at a Predefined Point
Setting a breakpoint in your code is another useful debugging tool. When you set a breakpoint,
your code continues to run normally until it reaches the line where you defined the breakpoint.
When you want to run tests on small blocks of code at a time, this debugging technique comes in
handy. For example, if you suspect a bug in your macro but know the rest of it runs smoothly,
you can place a breakpoint at the suspect line of code and then execute the macro. The execution
of the macros comes to a halt when it reaches your breakpoint. Press F8 to run the macro once...
Set a breakpoint by placing your cursor anywhere to begin and pressing F9. VBA clearly marks
the breakpoint with a dot in the Code window's left margin, and the code line itself is tinted
maroon, as shown in the image.
When your macro reaches a breakpoint, it goes into debug mode. Debug Step Out will get you
out of debug mode.
Seeing the Beginning and End of Variable Values
You can then watch the values being sent in and out of variables, which is quite useful. These
tooltips, however, are limited to 77 characters (including the variable name). This simply implies
that if your variable's value is too long, it will be chopped off.
Hold down the Ctrl key while hovering to see the last 77 characters.
Turning Off Auto Syntax Check
Often, when working on code, you'll discover that you need to duplicate something from another
line. You're not through with the line yet; you simply need to take a break. The VBE stops you
dead in your tracks with an error notice.
These warning windows make you stop what you're doing and pick OK to recognize the issue.
You'll be ready to slam your PC against the wall after a half-day of these startling message
windows. You can save your machine and your sanity by selecting Tools Options and turning off
Auto Syntax Check.
To avoid these unpleasant error messages, disable the Auto Syntax Check option on the Editor
tab of the Options dialog box. Don't be concerned about missing a real error. If you make a
mistake, your code still becomes red, giving you a visual signal that something is wrong.
CHAPTER TWENTY-THREE
RESOURCES FOR VBA HELP
No one can become a VBA expert in a single day. VBA is a process that takes time and
experience to master. The good news is that there are several resources available to assist you on
your journey. In this chapter, you'll learn about 10 of the most helpful resources for getting a
boost in the correct direction.
Allowing Excel to Generate Code for You
The macro recorder in Excel is one of the greatest locations to receive macro support. Excel
writes the underlying VBA for you when you record a macro using the macro recorder. After
you've finished recording, check the code to see what the recorder performed, and then attempt
to modify the code it generates to make it more suitable for your purposes.
Let's imagine you want a macro that refreshes all of the pivot tables in your worksheet and clears
all of the filters in each one. It would be difficult to write this macro from scratch. You may
instead use the macro recorder to film yourself refreshing all of the pivot tables and removing all
of the filters. After you've finished recording, go through the macro and make any adjustments
you think are necessary.
However, if you've figured out how to utilize the Excel Assistance system properly, it's typically
the quickest and simplest method to acquire further help on a subject. The Excel Help system has
two key ideas that you should remember:
When seeking assistance, the location is important. Excel includes two help systems: one for
Excel features and the other for VBA programming subjects. Rather than doing a worldwide
search with your parameters, Excel applies them solely to the Help system that is relevant to
your present location. This basically implies that the level of assistance you get is governed by
the Excel section in which you're working. If you require assistance with an issue that includes
macros or VBA programming, you must do your search in the VBE. This guarantees that your
keyword search is carried out on the appropriate Help system.
Online assistance is preferable to offline assistance. Excel checks to determine whether you're
connected to the Internet when you look for assistance on a subject. If you are, Excel will
provide you with guidance based on Microsoft's website information. Excel utilizes the Help
files that are saved locally with Microsoft Office if you aren't. Online assistance is often superior
since the material is more thorough and frequently updated, as well as connections to additional
resources that are not accessible offline.
Pilfering Code from the Internet
The ugly secret of programming in the era of the Internet is that there is no longer any original
code. Every piece of macro syntax you'll ever need is documented someplace on the internet. In
many respects, programming has evolved from the ability to write code from scratch to the
ability to apply existing code imaginatively to a given circumstance.
If you're having trouble creating a macro for a certain job, use your preferred search engine to
explain the task you're attempting to do. Enter "Excel VBA" before your description for the best
results.
You can wager two months' pay that someone has already handled the issue and given a sample
code that will provide you with the knowledge you need to get started on your own macro.
Leveraging User Forums
If you're stuck, submit your question in a forum to receive personalized advice depending on
your situation.
User forums are online communities focused on a specific topic. You may ask about issues in
these forums, and experts will respond with advice on how to address specific difficulties. The
people who answer the questions are usually volunteers who are passionate about assisting the
community in solving real-world problems.
There are several communities devoted to all things Excel. Type "Excel Forum" into your
preferred search engine to discover an Excel Forum.
Here are some pointers on how to get the most out of user forums:

Before you begin, always read and respect the forum rules. These rules often
contain standards for asking questions and community decorum.
Check to see whether your question has been asked and answered before. Why not
make use of the forum's question archive to save time? Make a quick scan of the
forum to determine whether your question has already been asked.
Make sure your question titles are succinct and precise. Don't ask queries on the
forum with vague names like "Need advice" or "Please Help."
Limit the scope of your inquiries as much as possible. Don't ask anything like,
"How do I make an Excel invoicing macro?"
Patience is required. Remember that the people addressing your inquiries are
mostly volunteers with day jobs. Allow time for the community to respond to your
question.
Return often. You may get requests for further information about your case after
publishing your inquiry. Return to your posting to either evaluate the answers or
react to follow-up inquiries as a courtesy to everyone.
Thank you to the expert who responded to your query. If you get a helpful
response, please take the time to thank the expert who assisted you.

Visiting Expert Blogs


There is a handful of committed Excel Gurus that write about their experiences. These blogs are
often troves of advice, providing tidbits that might help you improve your talents. The best part
is that they're completely free!
Although these blogs may not address your specific requirements, they do include articles that
will help you improve your Excel skills and give general advice on how to use Excel in real-
world scenarios.
Here's a roundup of some of today's greatest Excel blogs:
ExcelGuru: Ken Puls is a Microsoft Excel MVP who blogs at http://www.excelguru.ca/blog to
share his skills. In addition to his blog, Ken provides a number of instructional materials to help
you improve your Excel skills.
Chandoo.org: Purna "Chandoo" Duggirala, a Microsoft Excel MVP from India, first appeared
on the scene in 2007. His unique site (http://chandoo.org/) provides a wealth of free Excel
templates and articles geared at "making you fantastic in Excel."
Debra Dalgleish is a Microsoft Excel MVP and the proprietor of http://www.contextures.com, a
prominent Excel site. With over 350 Excel subjects listed alphabetically, you're likely to discover
something that interests you.
Daily Dose: Dick Kusleika is the proprietor of http://www.dailydoseofexcel.com, the longest-
running Excel blog. With over 10 years of articles and examples, he is the king of Excel VBA
blogging.
MrExcel: Excel's larger-than-life ambassador is Bill Jelen. On his website,
http://www.mrexcel.com, this long-time Excel MVP provides over a thousand free videos and a
vast collection of training tools.
Mining YouTube for Video Training
Consider mining YouTube if you discover that you absorb video instruction better than articles.
Hundreds of channels are operated by wonderful people who are passionate about sharing their
expertise. You'd be astonished at how many high-quality video lessons are available for free.
Go to www.youtube.com and type "Excel VBA" into the search box.
Attending Live and Online Training Classes
Live and online training sessions are fantastic ways to learn Excel from a wide range of
individuals. Not only will the teacher teach you methods, but the spirited conversations that take
place throughout the session will provide you with a plethora of fresh ideas and
recommendations that you may not have considered before. Consider looking for Excel lessons if
you thrive on the excitement of live training sessions.
Here are a few websites that provide great Excel classes taught by instructors:
http://academy.excelhero.com/excel-hero-academy-tuition
http://chandoo.org/wp/vba-classes
https://exceljet.net
Learning from the Microsoft Office Dev Center
The Microsoft Office Dev Center is devoted to assisting new developers in learning how to
program Office products quickly. Go to https://msdn.microsoft.com/en-
us/library/office/fp179694.aspx to access the Excel section of this site.
Despite the site's difficulty in navigation, it's worth a visit to examine all of the free resources,
which include example code, tools, step-by-step tutorials, and much more.
Dissecting the Other Excel Files in Your Organization
The current files in your company are typically a treasure trove for learning, similar to
discovering gold in your garden. Examine any Excel files that include macros by opening them
and looking behind the hood. Look at how others in your company utilize macros. Try going line
by line through the macros to see if you can find any new methods.
You may learn a few new techniques that you hadn't considered before. You could even come
across whole sections of valuable code that you can copy and paste into your own workbooks.
Asking Your Local Excel Guru
Do you work for a firm, a department, an organization, or a community that has an Excel whiz?
Today, become friends with that individual. You've got yourself a personal Excel forum there.
The vast majority of Excel specialists like sharing their expertise. So don't be shy about
approaching your local Excel Guru with queries or seeking help on how to solve specific macro
issues.
CHAPTER TWENTY-FOUR
TEN VBA DO’S AND DON’TS
You've presumably read most of this book and are acquainted with Excel VBA if you're reading
this last chapter. Maybe you simply wanted to discover whether the butler was the one who did
it, so you jumped to the conclusion.
When you begin designing your own VBA solutions, you should consider the guidance in this
chapter. Following these principles isn't a guarantee that you'll stay out of (programming)
trouble, but it may help you avoid the difficulties that others have encountered.
Declaring All Variables
How practical it is: Simply begin entering the VBA code without having to go through the
tiresome process of defining each and every variable. Although Excel permits the usage of
undeclared variables, doing so is a recipe for disaster.
This should be the first commandment of VBA programming:
Every variable must be declared.
Add an "Option Explicit" declaration to the top of your modules if you lack self-discipline. If
your code has one or more undeclared variables, it will not execute. There is just one benefit to
not declaring all variables: you save a few seconds. However, utilizing undeclared variables will
ultimately catch up with you. And figuring out the issue will take more than a few seconds.
Don’t Confuse Passwords with Security
You worked for months on fantastic Excel software with some incredible macros. You're ready
to share it with the rest of the world, but you don't want anybody else to see your amazing macro
programming. Isn't it enough to just password-protect the VBA project? Wrong.
Most casual people won't be able to see your code if you use a VBA password. However, if
someone is serious about checking it, he will find out how to breach the password.
What's the bottom line? Excel isn't the ideal option for a development platform if you absolutely,
certainly need to keep your code hidden.
Do Clean Up Your Code
You should clean up your app after it is operating to your satisfaction. The following are
examples of code cleaning tasks:
Make certain that all variables are stated.
Make sure that all of the lines are appropriately indented so that the code structure is visible.
Remove all debugging assistance, such as the Debug MsgBox commands.
Statements should be printed.
Any variables with bad names should be renamed. If you use the variable MyVariable, for
example, there's a strong possibility you could make the variable name more informative. You'll
be glad you did it afterward.
You most likely have a few "test" processes in your modules that you built while attempting to
figure out anything. Delete them since they've fulfilled their function.
Add comments so you'll know how the code works when you come back to it in six months.
Make that everything, particularly text in UserForms and message boxes, is spelled properly.
Look for any code that is superfluous. Consider establishing a new procedure that other
procedures may call if you have two or more procedures with identical blocks of code.
Don’t Put Everything in One Procedure
Do you want to develop software that is unintelligible? Putting all of your code into one huge
process is an effective way to do this. You're certain to make errors and add some fine-looking
problems if you return this application to make modifications again.
Modular coding is the answer. Divide your software into smaller sections, each with its set of
instructions. You'll discover that developing bug-free code is simpler than ever after you get into
this habit.
Do Consider Other Software
Excel is a very adaptable application, but it isn't appropriate for every situation. Take some time
to explore all of your possibilities when you're ready to start a new project. "When all you know
is Excel VBA, everything looks like a VBA macro," as an old adage goes.
Don’t Assume That Everyone Enables Macros
As you may be aware, Excel enables you to open a workbook with macros turned off. It's almost
as if the makers of newer Excel versions encourage users to turn off macros.
Of course, enabling macros while opening a worksheet from an unknown source is not a smart
idea. As a result, you must be familiar with your users. All Microsoft Office macros are disabled
in certain business contexts, and the user has no option.
Adding a digital signature to workbooks you share with others is something to think about. As a
result, the user may be certain that the workbooks are genuine and have not been tampered with.
For additional information about digital signatures, go to the Help system.
Do Get in the Habit of Experimenting
Spend time composing little VBA "experiments" while working on a huge Excel project. If
you're attempting to learn about a new object, method, or property, for example, build a small
Sub procedure and play about with it until you're confident that you understand how it works —
and the possible difficulties.
Simple experiments are nearly usually more efficient than implementing a new concept into
existing code without first knowing what those experiments provide.
Don’t Assume That Your Code Will Work with Other Excel Versions
You have no assurance that an Excel app will run properly in previous versions of Excel when
you design it (or in future versions for that matter). The incompatibilities will be clear in certain
circumstances. If your code, for example, refers to a new feature in Excel 2019, you know it
won't operate in previous versions. However, you'll notice that several features that should
operate with a previous version don't.
Excel has a compatibility checker (select File Info Check for Issues Check Compatibility),
however, it just looks at the worksheet and ignores the VBA code. Testing your application in
versions other than the one you designed it with is the only way to ensure that it works in those
versions.
Do Keep Your Users in Mind
There are two types of Excel apps: those that you create for yourself and those that you create
for others to use. Your task is significantly more difficult if you design applications for others
since you can't make the same assumptions. If you're the sole user, for example, you may be
more lenient with error handling. If a problem occurs, you'll know exactly where to search for it
and how to correct it. If someone else tries to use your program and gets the same error, he or she
is out of luck. You can typically get by without instructions while working with your own
program.
You must first determine the ability level of individuals who will use your workbooks and then
attempt to anticipate any issues that may arise. Consider yourself a new user of your program,
and look for any locations that might create confusion or troubles.
Don’t Forget About Backups
Nothing is more demoralizing than losing data due to a hard disk failure without a backup. If
you're working on a critical project, ask yourself this basic question: "What would I lose if my
computer dies tonight?" You should examine your data backup method carefully. Isn't it true that
you have a data backup process in place? Obtain One!
INDEX

A
Accelerator, 231, 239, 243, 246, 247
Accelerator property controls, 231
Activation Events, 158
ActiveX Controls, 84
AddChart, 199, 200, 201
AddEmUp, 21
Addin, 64
Add-In objects, 22
Add-Ins, 283, 284, 285, 287
add-ins for Excel, 19
AddItem, 255, 256, 257
additional parameters., 223
Analysis Tool Pak, 19
Analysis ToolPak, 283, 285
apostrophe, 31, 104, 105, 106, 232, 270, 290
Application object, 22, 63, 64, 67, 68, 117, 133, 163, 217, 219, 276
Application.WorksheetFunction, 137, 139, 231, 252
AppName, 116
argument descriptions, 281
Array declarations, 122
Arrays, 122, 123
Assignment Statements, 120
Auto Data Tips option, 58
Auto Indent, 59
Auto List Members, 57, 72, 75, 139
Auto List Members option, 57, 139
Auto Quick Info option, 58
Auto Syntax, 56, 295, 296
automatic calculation, 208
AUTOMATIC PROCEDURES, 151
Automating a task, 18
AVERAGE, 19, 272

B
Bar option, 61
battery, 18
Big Event, 151
Bold attribute, 131
Boolean settings, 197, 198
Break mode, 182, 183, 184, 185
budgeting, 17
BUG EXTERMINATION TECHNIQUES, 176
Bug Reduction, 186
Bugs, 176, 177, 178
Built-in Dialog Boxes, 220
Built-In Functions, 136
built-in tab, 267
Bunch of Text, 18

C
Case structure, 146, 148, 198
Case structures, 143, 148
Cell shortcut menu, 268, 269
Cells property, 128, 130
Cells technique, 193, 234
Center dialog box, 33, 35
Chandoo, 300
Chandoo.org, 300
ChangeCase, 228, 231, 232, 233, 286
chart formatting, 205
chart properties, 204
chart type, 200, 202, 203
ChartData, 200, 201
ChartMods, 205
ChartObject, 201, 202, 203
charts, 38, 66, 198, 201, 204, 207, 262
Charts, 22, 65, 66, 198
ChartShape, 200, 201
Check option, 56, 296
CheckBox, 239
CheckBox control, 239
Clear method, 134
ClearContents, 23, 70, 71, 134
code, 20, 24, 30, 31, 35, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 57, 58, 59, 60, 61, 68, 69, 70, 71, 73, 81, 85, 86,
90, 92, 94, 97, 98, 101, 102, 104, 105, 106, 109, 112, 115, 116, 117, 124, 125, 127, 129, 136, 137, 141, 142, 143, 146, 147,
148, 149, 158, 159, 160, 161, 163, 167, 168, 169, 170, 171, 173, 174, 175, 176, 178, 179, 180, 181, 182, 183, 184, 186, 187,
188, 189, 192, 194, 197, 199, 201, 202, 203, 206, 208, 209, 210, 218, 219, 220, 221, 222, 226, 227, 228, 231, 234, 240, 249,
251, 253, 256, 257, 258, 259, 260, 261, 268, 269, 272, 276, 277, 283, 288, 290, 291, 292, 293, 294, 295, 296, 297, 298, 301,
302, 303, 304, 305, 306
Code Colors, 60
Code Pane, 45
Code window, 40, 45, 46, 53, 59, 153, 159, 160, 226, 251, 259, 294, 295
Code windows, 45, 46
ComboBox, 239, 240
CommandBars, 222, 270
CommandButton, 225, 228, 240, 249, 256, 259
CommandButtons, 228, 240
Comment, 64, 106, 291
computer's memory, 107
Const statement, 116
ControlSource, 239, 242, 244, 245
Copy and Paste methods, 133
COUNTA function, 253, 254
CurrentRate, 109, 114
custom button, 19
Custom Functions, 140, 272
Customizing message boxes, 215
CutCopyMode, 189

D
data backup process, 307
Data Data Tools, 162, 163
data validation, 162
Data Validation, 162, 163
data validation cell., 163
Debug button, 170, 177
debugger’s tools, 180
Debugging, 177, 178, 186, 293
Debugging Techniques, 178
debugging tool, 185, 293, 294
Decisions, 143
Declarations, 46, 113, 114, 116, 123
Default attribute, 231
Delete method, 134
DeleteFromShortcut, 269, 270
Description box., 27
Dev Center, 301
Developer Code Visual Basic, 29, 38
Developer Controls, 83, 169, 250
Developers Tab, 25
dialog box, 19, 25, 28, 32, 33, 50, 52, 54, 56, 60, 79, 81, 82, 83, 85, 87, 88, 89, 96, 97, 109, 115, 120, 132, 133, 137, 139, 179,
183, 184, 190, 197, 213, 215, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 231, 232, 233, 236, 237, 240, 241, 243,
245, 246,247, 248, 249, 250, 251, 253, 254, 255, 258, 261, 262, 263, 266, 279, 280, 281, 284, 285, 286, 287, 296
Dialog Box Checklist, 263
Dialog Box Controls, 236, 238, 245
dialog boxes, 19, 43, 57, 90, 213, 214, 221, 238, 243, 245, 246, 248, 255, 261, 263, 264
Dialog Boxes, 247, 249
DIALOG BOXES, 213
dialog window, 27, 44, 220, 251, 253, 257, 258, 280
Dim statement, 110, 112, 113, 118
DisplayAlerts, 209
Docking tab, 62
Drag-and-Drop, 59
dragging the block, 291
drop-down menu, 28, 29, 40, 43, 53, 54, 82, 87, 180, 224, 236, 239, 250, 267, 287
Dynamic arrays, 124

E
Editor tab, 56, 109, 139, 296
ElseIf, 144, 146
End Function, 77, 86, 115, 174, 175
End Sub, 31, 50, 51, 70, 71, 72, 77, 85, 86, 92, 94, 101, 102, 112, 114, 115, 117, 134, 149, 154, 159, 160, 167, 173, 191, 192,
193, 195, 197, 198, 199, 200, 201, 203, 205, 206, 207, 208, 215, 218, 227, 232, 251, 252, 256, 257, 259, 260, 270
EnterButton, 252, 253, 254
EnterSquareRoot, 170
Entomology 101, 176
equal sign, 51, 71, 120, 121, 131
equal-sign operator, 122
ERROR HANDLING TECHNIQUES, 168
Error management, 175
Error Trapping, 61
ErrorHandler, 172, 173
event-handler, 152, 153, 154, 157, 159, 231, 240, 251, 256, 259
Event-Handler Procedure, 154
EVENTS, 151
Excel coder, 25, 55
Excel file, 268
Excel Gurus, 300
EXCEL MACRO RECORDER, 89
Excel menu, 18
Excel Preferences, 196
Excel programming, 16, 25, 63, 126
EXCEL VBA, xv
Excel workbooks, 18
ExcelGuru, 300
Excel's debugger, 186
Excel's RAND function, 137
Explicit Option, 57
ExtractElement, 277

F
Font option, 60
Font property, 130, 131
Forecasting, 17
Format tab, 60
Formula bar, 34
Formula property, 131, 132
formulae, 19, 38, 76, 88, 120, 122, 131, 136, 140, 279, 283
FormulaLocal, 132
Frame control, 241, 243, 247
Full Module, 59
Full Module View option, 59

G
GetOpenFilename, 218, 219, 220
GetOpenFilename Statement, 218
GetSetting, 155
global (public) variables, 115
GoTo method, 133
GoTo Statement, 142
grade point averages, 17
graph paper, 66
graphic depicts, 56, 113, 189, 215, 224
GuessName, 49, 50, 52

H
Habit of Experimenting, 306
hard disk failure, 307
Hierarchy of Objects, 64
HouseCost, 121
Hyperlink, 64

I
Image control, 241, 242, 262
Immediate window, 41, 80, 118, 182, 184
importing objects, 44
incorrect context bugs, 176
index number, 66, 122, 123, 255
InputArea, 163
InputBox, 137, 195, 216, 217, 218
InputRange, 163
Integer, 112, 114, 116, 123, 124, 211, 215
IntegralHeight, 242, 245
Intentional Error, 173
Interior property, 131
Internet, 41, 298

K
keyboard users, 246
Keypress events, 166
keypresses, 164
keystroke, 18, 166, 167

L
LabelProgress, 260, 261
Leveraging User Forums, 298
ListBox, 239, 242, 255, 256, 257, 258
ListBox control, 239, 242, 256
ListCount, 255
ListIndex, 255, 257, 258
Local Excel Guru, 302
Locals window, 185
Logic errors, 176
lowest index, 123

M
Macro, 17, 26, 27, 28, 29, 31, 32, 33, 35, 36, 42, 52, 79, 81, 82, 83, 84, 85, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 169, 170,
232, 250, 280
macro recorder, 18, 28, 31, 47, 52, 53, 55, 77, 78, 82, 88, 89, 90, 91, 94, 96, 98, 102, 132, 133, 187, 188, 189, 192, 197, 198,
297
macro recording button, 27
macro works., 18
macro-driven applications, 19
MacroOptions, 281
Macros, 28, 32, 34, 54, 79, 81, 82, 87, 116, 152, 232, 233, 250, 267, 280, 305
MACROS, 25, 265
makros, 17
Margin Indicator, 61
mathematical calculation, 149
menu bars, 39
Microsoft Office, 16, 265, 298, 301, 305
Microsoft's website, 41, 73, 298
Mining, 301
modeless tabbed dialog, 261
ModName, 116
module-level variables, 115
Modules, 30, 42, 184, 291
Mount Olympus, 31
mouse pointer, 183, 291
MsgBox, 50, 51, 58, 69, 70, 77, 86, 114, 120, 130, 137, 144, 149, 160, 172, 173, 178, 179, 180, 198, 205, 206, 214, 215, 216,
218, 232, 304
multicell array formula, 279
Multidimensional arrays, 123
MultiPage, 243, 244, 247, 248, 261, 262, 263
MultiPage control, 243, 244, 248, 261, 262, 263
Multiple Lines of Code, 291
multiple selections, 195, 255, 258

N
nested Select Case, 148
NextTick, 165
Number Format property, 132
Number tab., 132
numeric computations, 108
NumQuarters, 116

O
Object Browser, 72, 74
object hierarchy, 21, 22, 63
object references, 68, 210
objects properties, 69
official syntax, 200, 219
offline assistance, 298
Offset property, 129
OnTime event, 164, 165
Option Explicit, 57, 109, 303
optional parameters, 219
OptionButton control, 241, 243

P
Page Layout Page, 98
PageSetup, 64, 98, 99, 101, 102
perfect macros, 169
pesky alert messages, 209
Pilfering Code, 298
PivotTable, 22, 64
Power Utility Pak add-in, 19
Premade Constants, 117
PrintReport, 227
Procedure Separator option, 59
PROGRAM FLOW, 141
PROGRAMMING, xv, 103, 142, 187
Programming event-handler procedures, 153
project explorer, 42
Project window, 29, 40, 42, 43, 44, 46, 49, 226

Q
Quick Tips, 207

R
Range, 22, 23, 64, 67, 68, 69, 70, 71, 92, 94, 121, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 137, 138, 159, 187, 190,
191, 192, 193, 194, 195, 199, 200, 201, 210, 217, 221, 252
RANGE OBJECTS, 126
Ranges, 187
RangeSelection, 162, 201
recorder, 18, 31, 52, 89, 94, 98, 187, 297
Recording Basics, 89
regular workbook file, 285
relative mode, 91, 93, 129
Relative References button, 27, 91, 93
RemoveAllItems, 255
repetitive operations, 18
resizing controls, 245
Ribbon, 19, 25, 41, 79, 80, 96, 221, 222, 265, 266, 267, 268, 285
robot, 16
RowNumber, 110
RunReport, 215
runtime error, 115, 162, 170, 173, 177

S
SaveSetting, 155
Saving Workbooks, 32
SayIt function, 277
Scientific data analysis, 17
ScrollBar control, 243, 244
ScrollBars, 245, 264
ScrollLock, 180
Select method, 132
Sentence Case, 286
Setting hotkeys, 247
Sheets, 65, 67, 133, 160, 190, 191, 252
Shell, 137
Shortcut key, 97, 232
shortcut menus, 155, 269
Shortcut menus, 40
ShowCubeRoot, 80, 82, 85
ShowMessage, 77
Size setting, 61
SmallChange, 244
Smooth operators, 122
Software, 305
solid grasp, 35, 175
space bar, 59
spacing controls, 246
SpecialCells, 194
SpinButton, 243, 244, 258, 259, 260
SpinButton control, 243, 244, 258
standard Clipboard, 55
Static variable, 115
Stop, 28, 53, 89, 90, 92, 93, 182
StopClock, 165
string manipulation, 108
strings, 107, 116, 118, 119, 132, 278
SUB AND FUNCTIONS, 76
Sub or Function statement, 112, 116
Sub procedure, 31, 48, 51, 76, 77, 79, 80, 81, 86, 140, 257, 272, 306
Sub procedures, 20, 47, 76, 79, 82, 87, 90
Sub-Procedures, 77
Subs versus Functions, 76
Sudoku problem, 55, 123
SUM, 19, 47, 76, 132, 136, 137, 272
supplemental materials, 16
syntax problems, 56

T
Tab key., 59
tab order, 246, 247
TabStop, 247
TabStrip, 244, 262
TabStrip control, 244, 262
Teleporting, 292
Text property, 130
TextAlign, 245
TextBox, 244, 245, 247, 249, 253, 258, 259, 260, 263
TextBox control, 244, 245, 249
Toggle Breakpoint, 181
Toggle Case, 286
toggle switch, 93
ToggleButton control, 245
toolbar, 19, 40, 41, 49, 59, 79, 80, 87, 106, 115, 182, 233, 250, 251, 266, 290, 291
Toolbar, 40, 233, 250
Toolbars, 40, 106, 291
Turning off screen updating, 207
Types of Errors, 168

U
Uncomment Block, 106
Understanding Functions, 136
UpdateClock, 165
USER INTERFACE, 265
UserForm, 50, 79, 81, 182, 213, 223, 224, 225, 226, 227, 228, 229, 231, 233, 234, 236, 237, 240, 242, 245, 247, 249, 250, 251,
254, 255, 256, 257, 258, 259, 260, 261, 262, 285
USERFORM BASICS, 223
USERFORM CONTROLS, 236
UserForms, 213, 223, 249, 261, 304

V
Validating the data, 253
Value property, 69, 128, 130
Variable Declaration option, 57
variable types, 210
variables, 23, 46, 51, 90, 104, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 119, 120, 122, 128, 129, 179, 181, 182,
185, 201, 210, 261, 270, 295, 303, 304
variable-size range, 189
Variant data type, 108
VBA, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 28, 30, 31, 32, 33, 35, 37, 38, 40, 41, 43, 44, 45, 46, 47, 48, 49, 51, 52, 55, 56, 57,
60, 61, 63, 65, 66, 69, 70, 72, 73, 76, 77, 78, 79, 81, 85, 89, 90, 94, 96, 98, 102, 104, 105, 107, 108, 109, 111, 112, 113, 114,
116, 117, 118, 119, 120, 121, 122, 123, 125, 126, 127, 128, 129, 132, 133, 136, 137, 138, 139, 140, 141, 142, 143, 145, 147,
148, 151, 153, 164, 165, 168, 169, 171, 175, 176, 178, 180, 181, 182, 183, 184, 186, 187, 188, 189, 191, 192, 193, 195, 198,
201, 202, 207, 209, 211, 213, 214, 217, 218, 220, 221, 222, 223, 227, 231, 237, 243, 249, 257, 258, 262, 265, 268, 269, 272,
276, 277, 278, 279, 283, 286, 288, 293, 295, 297, 298, 300, 301, 303, 304, 305, 306
VBA code, 21, 23, 24, 28, 30, 32, 38, 40, 45, 47, 48, 52, 55, 56, 57, 60, 66, 69, 76, 89, 94, 96, 98, 120, 136, 168, 178, 180, 181,
187, 202, 222, 227, 237, 243, 249, 262, 269, 283, 286, 303, 306
VBA module, 20, 21, 43, 44, 45, 46, 47, 48, 49, 52, 55, 57, 73, 81, 85, 89, 102, 109, 111, 139, 153, 164, 257
VBAProject, 30, 40, 286
VBE, 20, 29, 31, 32, 34, 38, 39, 40, 41, 42, 43, 45, 46, 49, 51, 53, 55, 56, 57, 58, 59, 60, 62, 74, 75, 79, 80, 81, 92, 95, 96, 97,
98, 109, 110, 114, 115, 129, 139, 153, 154, 155, 169, 180, 182, 184, 185, 224, 227, 236, 246, 250, 251, 286, 288, 291, 292,
296, 298
VBE program window's boundaries, 62
VBE window., 29, 30
VBProject, 64
vertical margin indication bar, 61
Video Training, 301
Visible attribute, 70
Visiting Expert Blogs, 300
Visual Basic Editor, 20, 29, 38, 76, 153, 223, 290
VISUAL BASIC EDITOR, 38, 41, 290

W
Watch window, 183
Window, 40, 41, 45, 46, 64, 162, 185
WordWrap, 245, 264
workbook, 18, 21, 22, 30, 32, 34, 35, 38, 42, 43, 49, 52, 53, 66, 67, 68, 70, 71, 72, 80, 91, 97, 111, 114, 115, 116, 139, 140, 151,
152, 153, 155, 156, 157, 158, 160, 161, 162, 164, 165, 167, 173, 174, 175, 177, 204, 224, 233, 235, 242, 250, 261, 268, 276,
283, 284, 285, 286, 287, 305
Workbook, 22, 27, 29, 32, 36, 42, 44, 45, 64, 65, 67, 72, 97, 153, 154, 155, 157, 158, 160, 161, 166, 167, 286
Workbook object, 22, 42, 64, 65, 67, 72, 155
Workbooks, 22, 65, 67, 68, 70, 71, 72, 75, 174, 210, 220
WorkRange, 194
Worksheet, 22, 64, 65, 67, 73, 102, 126, 134, 137, 138, 152, 159, 162, 187, 272
worksheet formula, 78, 87, 274
Worksheet Function, 64
worksheet functions, 19, 76, 121, 136, 137, 138, 139, 140, 272, 276, 282, 283, 284
WORKSHEET FUNCTIONS, 136, 272
Worksheet objects, 22, 65
WorksheetChange, 152
WorksheetFunction, 137, 138, 139
Worksheets, 22, 23, 65, 66, 67, 68, 69, 71, 130, 210
Wrapper Functions, 276

X
xlCalculationAutomatic, 198, 209
XLSM version, 285, 287, 288

You might also like