Microsoft Office 2007 - VBA
Microsoft Office 2007 - VBA
Your Classroom Learning experience is just one part of the New Horizons learning solution; an enriching, dynamic
and valuable experience that includes Web-based resources during and after class.
The New Horizons learning solution includes online resources such as assessments, eCourseware and self-study
tutorials, making it the finest and most robust learning environment available.
A full electronic version of the user manual - eCourseware - is available for reference and use post-class. Updates to
the content within the eCourseware manual are automatic, providing you with access to the latest version of the
course material at all times.
To access eCourseware and other online resources for this class, visit www.newhorizons.com and select Student
Resources. New Horizons Learning Port a hosted, Web-based platform supports the delivery and management of
your post-class resources. For more information about other available learning options, contact your local New
Horizons Computer Learning Center.
(Note: Access keys are case-sensitive and must be entered exactly as displayed.)
Username:
Password:
This login provides access to class resources only. When creating your “Username” enter something unique such as adding the
letters ILT (Instructor Led Training) to the end of the name. This will set it apart from logins that you may use for other types of
online training.
Microsoft® Office Excel® 2007 - VBA
Part Number: 3424
Course Edition: 1.0
ACKNOWLEDGMENTS
Project Team
Content Developer: Mariya Mubarak and Theophilus Benjamin • Content Manager: Pradeep PM • Graphic Designer: Ganesh
Kumar B • Project Manager: Yogesh Aravindhakshan • Media Instructional Designer: Bhoopathy R • Content Editor: Vanitha
Kesavan • Materials Editor: Banupriya • Project Quality Support: Shobana T.S • Technical Reviewer: • Project Technical
Support: Mike Toscano
NOTICES
DISCLAIMER: While Element K Corporation takes care to ensure the accuracy and quality of these materials, we cannot guarantee their accuracy, and all materials are provided without any warranty
whatsoever, including, but not limited to, the implied warranties of merchantability or fitness for a particular purpose. The name used in the data files for this course is that of a fictitious company. Any
resemblance to current or future companies is purely coincidental. We do not believe we have used anyone’s name in creating this course, but if we have, please notify us and we will change the name in
the next revision of the course. Element K is an independent provider of integrated training solutions for individuals, businesses, educational institutions, and government agencies. Use of screenshots,
photographs of another entity’s products, or another entity’s product name or service in this book is for editorial purposes only. No such use should be construed to imply sponsorship or endorsement of
the book by, nor any affiliation of such entity with Element K. This courseware may contain links to sites on the Internet that are owned and operated by third parties (the ″External Sites″). Element K is
not responsible for the availability of, or the content located on or through, any External Site. Please contact Element K if you have any concerns regarding such links or External Sites.
TRADEMARK NOTICES: Element K and the Element K logo are trademarks of Element K Corporation and its affiliates.
Microsoft® Office 2007 is a registered trademark of Microsoft Corporation in the U.S. and other countries; the Microsoft products and services discussed or described may be trademarks of Microsoft
Corporation. All other product names and services used throughout this course may be common law or registered trademarks of their respective proprietors.
Copyright © 2008 © 2008 Element K Corporation. All rights reserved. Screenshots used for illustrative purposes are the property of the software proprietor. This publication, or any part thereof, may not
be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, storage in an information retrieval system, or otherwise, without express written
permission of Element K, 500 Canal View Boulevard, Rochester, NY 14623, (585) 240-7500, (800) 478-7788. Element K Courseware’s World Wide Web site is located at
www.elementkcourseware.com.
This book conveys no rights in the software or other products about which it was written; all use or licensing of such software or other products is the responsibility of the user according to terms and
conditions of the owner. Do not make illegal copies of books or software. If you believe that this book, related materials, or any other Element K materials are being reproduced or transmitted without
permission, please call (800) 478-7788.
Contents iii
CONTENTS
LESSON 2 - FORMATTING WORKSHEETS USING MACROS
A. Insert Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
The Selection Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
The ActiveSheet Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
The Name Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
The Value Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
B. Format Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
C. Sort Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
The Range Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
The Select Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
The CurrentRegion Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
D. Duplicate Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Variable Naming Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
The Assignment Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
The For Next Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
The Do Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
The Worksheets Collection Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
The Count Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
The Offset Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
The Copy Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
The Paste Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Contents v
CONTENTS
D. Print Worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
The PrintPreview Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
The PrintOut Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Course Description
Target Student
Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using
Visual Basic for Applications (VBA).
Course Prerequisites
Knowledge of Microsoft® Office Excel® 2007, including how to create, edit, format, and print
worksheets that contain charts, and sorted and filtered data. To ensure your success, we recom-
mend the following New Horizons courses, or equivalent knowledge: Microsoft® Offıce Excel®
2007 - Level 1, Microsoft® Offıce Excel® 2007 - Level 2, and Microsoft® Offıce Excel® 2007 -
Level 3.
Introduction vii
INTRODUCTION
How to Use This Book
As a Learning Guide
Each lesson covers one broad topic or a set of related topics. Lessons are arranged in the order
of increasing proficiency with Microsoft® Offıce Excel® 2007; skills you acquire in one lesson
are used and developed in the subsequent lessons. For this reason, you should work through
the lessons in sequence.
We organized each lesson into results-oriented topics. Topics include all the relevant and sup-
porting information you need to master Microsoft® Offıce Excel® 2007, and activities allow
you to apply this information to practical hands-on examples.
You get to try out each new skill on a specially prepared sample file. This saves you typing
time and allows you to concentrate on the skill at hand. Through the use of sample files,
hands-on activities, illustrations that give you feedback at crucial steps, and supporting back-
ground information, this book provides you with the foundation and structure to learn
Microsoft® Offıce Excel® 2007 quickly and easily.
As a Review Tool
Any method of instruction is only as effective as the time and effort you are willing to invest
in it. In addition, some of the information that you learn in class may not be important to you
immediately, but it may become important later on. For this reason, we encourage you to
spend some time reviewing the topics and activities after the course. For an additional chal-
lenge when reviewing activities, try the “What You Do” column before looking at the “How
You Do It” column.
As a Reference
The organization and layout of the book makes it easy to use as a learning tool and as an
after-class reference. You can use this book as a first source for definitions of terms, back-
ground information on given topics, and summaries of procedures.
Course Objectives
In this course, you will apply automation to job tasks in Microsoft® Office Excel® 2007.
You will:
• create, edit, and debug a macro.
• format worksheets using macros.
• create an interactive worksheet.
• work with multiple worksheets.
• perform calculations.
Software
• Windows® XP Professional with Service Pack 1 or Windows® 2000 Professional with
Service Pack 3This course was developed using the Windows® XP operating system;
however, the manufacturer’s documentation states that it will also run on Vista. If you use
Vista, you might notice some minor differences in the interface when keying the course.
• Microsoft® Office 2007 Professional Enterprise Edition
Class Setup
For Initial Class Setup
1. Install Windows® XP Professional on an empty partition.
— Leave the Administrator password blank.
— For all other installation parameters, use values that are appropriate for your environ-
ment (see your local network administrator if you need details).
2. On Windows XP Professional, disable the Welcome screen. (This step ensures that stu-
dents will be able to log on as the Administrator user regardless of what other user
accounts exist on the computer.) Choose Start→Control Panel→User Accounts. Click
Change The Way Users Log On And Off. Uncheck Use Welcome Screen. Click Apply
Options.
3. In Windows XP Professional, install Service Pack 2. Use the Service Pack installation
defaults.
4. For Windows XP Professional, choose Start→Settings→Printers to install a printer
driver (a physical print device is optional). Run the Add Printer wizard and follow the
prompts.
Introduction ix
INTRODUCTION
5. Verify that file extensions are visible.
6. Run the Internet Connection wizard to set up the Internet connection as appropriate for
your environment, if you did not do so during installation.
7. Log on to the computer as the Administrator user if you have not already done so.
8. Perform a complete installation of Adobe Reader 6.0.
9. Perform a complete installation of Microsoft® Office Professional Edition 2007.
10. Minimize the language bar if it appears.
11. Extract the course data files from the CD-ROM provided with the course manual. The
files will be extracted to the C:\084037Data folder.
Developing Macros
In this lesson, you will create, edit, and debug a macro.
You will:
• Use the Macro Recorder to create a macro.
• Edit a macro.
• Debug a macro.
• Customize the Quick Access Toolbar and Hotkeys.
• Work with macro security options.
TOPIC A
Create a Macro with the Macro
Recorder
You are familiar with most of the features offered by Microsoft Office Excel and ready to cre-
ate a macro. The simplest way to create a macro in Microsoft Office Excel is to use the Macro
Recorder. In this topic, you will automate procedure steps, so that the number of steps required
to complete a task is dramatically reduced.
It is easy to see that the idea of automating repetitive tasks in Microsoft Office Excel is a good
one. Excel uses Visual Basic for Applications (VBA) programming to accomplish this. But
what if you don’t know how to program VBA? That is where the Macro Recorder comes in.
The Macro Recorder automates the creation of VBA code and eliminates coding errors by
recording actions as you perform them.
Object-Oriented Programming
Object-Oriented Programming is a methodology where all entities are treated as objects. These
objects are modeled like real-time objects and have two characteristics: attributes and behav-
iors. For example, a person’s bank account can be treated as an object, where his name,
account number, and balance can be the attributes of the object. Transactions such as deposits
and withdrawals that control the bank account can be treated as behaviors. Object-Oriented
Programming works by assembling various objects, their features, and their interactions to cre-
ate an application.
Example:
Macro Options
The Macro dialog box provides you with various options to work with a macro.
Option Description
Run Executes the macro.
Step Into Allows you to start the VBA Editor.
Edit Allows you to make changes to the macro.
If any of these rules are not followed, you will receive an invalid procedure name
error message.
Relative References
If you are using formulas frequently, these formulas are repeatable or extendable to
other rows or columns, which can be done by AutoFill.
ACTIVITY 1-1
Recording and Running Macros
Data Files:
• Record Macro.xlsx
Scenario:
You keep track of spreadsheet data for a workgroup that compiles different reports for other
departments. The look and feel of the reports are different. Some use the Times New Roman
font and some use the Courier font. You decide to create macros to implement font changes to
the worksheet.
1. Enter the identifying characteristics a. On the Developer tab, in the Code group,
for a new macro named click Record Macro, to dis-
font2TimesNewRoman, using the play the Record Macro dialog box.
Record Macro dialog box.
3. Enter the identifying characteristics a. In the Code group, click Record Macro to
for a new macro named font2Courier, display the Record Macro dialog box.
using the Record Macro dialog box.
b. In the Macro name text box, type
font2Courier
4. Record a macro that changes the font a. Click OK to start the Macro Recorder.
style for the entire worksheet to
Courier.
b. On the worksheet, to the left of the Col-
umn A heading, click the Select All button
to select the entire worksheet.
Part Description
Project Explorer A tree-like navigation tool similar to Windows
Explorer that enables you to access stored macro
code.
Code Editor A word processing window where you can enter,
modify, and debug macro code.
Object Explorer A reference tool used to describe the parts of the
VBA language.
Although a useful tool for advanced VBA programmers, the Object Explorer is beyond the scope of this course.
Modules
Definition:
A module is a project entity that stores macro code. It is similar to a text file. When
opened, modules display stored macro code as a list in the Visual Basic Editor. Manu-
ally entered code and recorded macro code are stored in modules.
Example:
Objects
Definition:
An object is a programming language component that, for the most part, mimics the
characteristics and behaviors of the components in an Excel workbook. Objects are
uniquely named and represent an element of an application such as a cell, a chart, a
form, or a report.
Properties
Definition:
A property is a set of built-in storage locations that affects the characteristics of the
worksheet component to which it refers. It keeps track of work and functions with the
worksheet component. The components can be size, color, or screen location.
Example:
Methods
Definition:
A method is a set of short programs whose action changes the referenced worksheet
component. Methods are built-in programs. Methods can be associated with a particu-
lar object or class.
VBA Comments
Definition:
VBA comments are lines of explanatory text that you can enter in a macro to help iden-
tify and document the macro. Comments provide the programmer with reminders on
what the macro should do. Comments have no effect on the VBA code in a macro.
Each comment line begins with an apostrophe as the first character, indicating Excel to
ignore the line because it contains no VBA code.
Example:
ACTIVITY 1-2
Editing a Macro
Data Files:
• Edit Macro.xlsm
Scenario:
You are informed that the reports that were supposed to go out in the Courier font must now
go out in the Verdana font. Rather than starting over, you decide to edit the macro, so that
instead of Courier, it changes the worksheet font to Verdana.
1. Modify the font2Courier macro’s code a. Select Macros, and from the Macro name
and commenting so that it now for- list box, select font2Courier, and click
mats the worksheet with the Verdana Edit to locate the code block starting with
font. the code Sub font2Courier().
Code Sample 1
' The completed edits to font2Verdana:
Sub Font2Verdana()
'
' Font2Verdana Macro
' This macro changes the worksheet to Verdana font.
'
'
Cells.Select
Selection.Font.Name = "Verdana"
Range("A1").Select
End Sub.
Code Groups
A code group is a series of VBA commands that together form a logical unit of code.
An entire macro can be considered a code group, if it is called by another macro to
accomplish part of a complex task.
ACTIVITY 1-3
Debugging Macros that Format a Report
Data Files:
• Debugging Example.xlsm
Scenario:
One of your coworkers, who was assigned the task of creating a report-formatting macro that
calls several macros to format raw worksheet data into a report by inserting rows, columns,
report title and header text, and formatting the report has incorrectly edited the macro code.
You are asked to debug the code by finding and correcting the errors using Visual Basic Edi-
tor’s debugging tools.
1. Review the final product data a. Select the End Product worksheet.
example and then prepare an easy-
access raw data backup.
b. Select the Original Data worksheet to
view the raw data, after reviewing the
End Product worksheet.
3. Run the CreateReport macro to get a a. Click the View Microsoft Excel button.
general idea of where the problems
are.
b. Select the Original Data worksheet.
5. Step through the CreateReport macro a. Click the Microsoft Visual Basic Editor
code until you find the first error. title bar.
6. Edit the code so that it selects the a. In the line of code immediately above the
first four rows of the worksheet. yellow highlighted code, place the inser-
tion point between 2 and the colon.
b. Press Backspace.
c. Type 1
8. Progress through the code until you a. Click Step Out, to run the rest of the
find the next error. code in the InsertRowsCols macro.
f. Click Paste.
ACTIVITY 1-4
Customizing the Quick Access Toolbar and Hotkeys
Data Files:
• Hotkey.xlsm
Scenario:
You would like to add frequently used commands to the Quick Access toolbar where they
would be easily visible and in a convenient location.
1. Customize the Quick Access toolbar a. Click the Microsoft Office button and
using the Excel Options dialog box. then click Excel Options.
2. Add the font group and the cells a. On the Home tab, right-click Font.
group to the Quick Access toolbar
using the right-click option.
b. Click Add to Quick Access Toolbar.
TOPIC E
Work with Macro Security
You have created macros in Excel. You now need to protect the macros. In this topic, you will
work with macro security.
You have developed a macro, which is to be used by other staff in your office. By protecting
your macro with appropriate security settings you can ensure the integrity of the macro.
Digital Certificates
Definition:
A Digital Certificate is an electronic file that contains unique information about a spe-
cific person. It contains a serial number, the digital signature of the certificate issuing
authority, expiration date, a name, and a copy of the certificate holder’s public key so
that a recipient can verify the authenticity of the certificate. It is issued by a Certifica-
tion Authority (CA), which is a trusted third party, or from your own company’s
computer service professional. A digital certificate is also known as a digital ID
because it is used to digitally sign a document.
Digital Signatures
Definition:
A Digital Signature is a content authentication tool that authenticates the originator of
a file and ensures the integrity of digital documents. It validates the authenticity, integ-
rity, and origin of the document. The digital signature is not visible within the contents
of the workbook. The Signature icon on the Microsoft Office Status bar at the bot-
tom of the application window is indicative of the fact that the workbook has been
digitally signed. When you open a document with a digital signature, the details will
be visible in the Signatures pane of your workbook. Users cannot make modifications
to a digitally signed document until the signature is removed.
Example:
ACTIVITY 1-5
Setting Macro Security
Data Files:
• Macro Security.xlsx
Scenario:
You have created a macro, but as other users will also be using it you would now like to take
adequate security measures so that your workbook’s security is set as desired. Before you do
this, you would also add a digital signature to the document to authenticate it.
f. Click OK.
n. Click Create.
p. Click Sign.
c. Click OK.
Lesson 1 Follow-up
In this lesson, you created, edited, and debugged a macro, customized the Quick Access
toolbar and worked with macro security. These skills will help you automate repetitive tasks in
Excel, saving time and expanding the capabilities of Excel.
1. Do you think that the Macro Recorder is a useful tool? Why or why not?
2. How does the Personal Macro Workbook relate to the creation and use of custom
toolbars, buttons, and menus?
Formatting Worksheets
Using Macros
In this lesson, you will format worksheets using macros.
You will:
• Insert text.
• Format text.
• Sort data.
• Duplicate data.
• Generate reports.
TOPIC A
Insert Text
You know how to manually enter text into a worksheet. There may be times when you want
text to frequently appear in the worksheet. In this topic, you will store text in a macro and
automatically insert it into a worksheet.
If you have ever created worksheets that required you to type the exact same text into cells
several times in a worksheet, then you know how frustrating the repetition could be. Applying
VBA allows you to create macros to insert frequently used text without requiring the user to
manually enter the text into the worksheet.
Analogy:
In many respects, the Selection object functions like the pronoun it—you can use
it to refer to different previously selected objects.
Example:
Example:
Example:
Example:
'Original code:
Range("CellAddr").Select
Selection.Value = Name of the worksheet
Modified code:
Range("CellAddr").Select
Selection.Value = ActiveSheet.Name & " Portfolio"
ACTIVITY 2-1
Inserting Report Text
Data Files:
• Balance Sheet.xlsx
Scenario:
You are assigned the task of building a report. You need to start off with entering the
boilerplate text that forms the title and headers for the stock price data.
Code Sample 1
'The altered code:
Range("B4").Select
ActiveCell.FormulaR1C1 = ActiveSheet.Name & " Portfolio"
4. Run the InsTxt macro on the a. In the workbook, select the Balanced
worksheets. worksheet.
2. True or False? Concatenation refers to the act of connecting two or more pieces of
text information together with an ampersand to form a single, longer piece of text.
True
False
ACTIVITY 2-3
Formatting Report Text
Data Files:
• My Balance Sheet.xlsm
Scenario:
You have inserted text for the report title and stock price data headers. You need to format the
header text differently from the body text so that it is easy to distinguish between the two.
2. Format the report text and then a. Click cell A1, and on the Home tab, in the
complete the macro recording. Font group, from the Font Size drop-
down list, select 18.
TOPIC C
Sort Data
You know how to sort independent columns and rows. Now, you need to sort data while pre-
serving the relationship between data in multiple columns and rows. In this topic, you will
create a macro that sorts related data in multiple columns and rows.
You are working with a spreadsheet that displays the names of students in rows with their
quarterly test averages contained in columns. You decide to change the order of the students so
that the student with the highest average in the fourth quarter is displayed at the top of the
worksheet. Excel’s default sorting behavior would change the order of the grades only in the
fourth quarter column without affecting the remaining rows. This breaks the relationship
between the data and causes the information to be inaccurate. Applying VBA allows multiple
related rows and columns to be sorted together.
Example:
Range("CellAddr").Select
ActiveCell.CurrentRegion.Select
Selection.Sort Key1:=Range("CellAddr"), _
Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom
Scenario:
You work for an investment company and need to prepare daily reports on the performance of
three stock portfolios. The portfolio components vary over time, causing the sizes of the ranges
holding the price information to vary. You start coding a report builder by sorting the original
data.
1. Display the code for SortLastCol a. Display the Macro dialog box.
macro that performs a descending
sort on the last column of a selected
b. Select the SortLastCol macro and click
range.
Edit to display the code in Visual Basic
Editor.
b. Press Enter.
c. Type
ActiveCell.CurrentRegion.Select
to select the entire range in which the
cell is located.
Code Sample 1
' The completed code for the SortLastCol macro:
Sub SortLastCol()
'
'
Range("A1").Select
ActiveCell.CurrentRegion.Select
Selection.Sort Key1:=Range("D1"), Order1:=xlDescending, _
Header:=xlGuess, OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom, DataOption1:=xlSortNormal
End Sub
3. Sort the portfolios on the other two a. In the workbook, select the Balanced
worksheets. worksheet.
5. Save the file and then close it. a. Save the file as My Raw Data.xlsm
TOPIC D
Duplicate Data
You know how to manually copy and paste data in a worksheet. Using VBA, the text that you
want to copy and paste can be duplicated automatically by applying a macro. In this topic, you
will create a macro that duplicates unknown number of cells in a column or row.
To manually duplicate data in a worksheet, you know that you need to perform multiple steps
to select, copy, and paste data. Applying VBA reduces the number of steps required to dupli-
cate data in a worksheet.
Data Types
Definition:
Data types refer to text, numeric, and true/false data you work with when creating
macros to process information. The String data type refers to text; the Integer data
type, to positive and negative whole numbers; and the Boolean data type, to true/false
or yes/no logical values.
Example:
Example:
Types of Variables
Variables come in two forms:
• Weakly typed variables can hold any data type and are created in the macro when
the code that first uses them is run.
• Strongly typed variables can hold only one data type and must be created, or
declared before they are used. Attempting to store the wrong data type in a
strongly typed variable creates an error, which causes the macro to cease before it
can complete its work.
Operators
Definition:
Operators are symbols you use to carry out tasks between two operands. These tasks
can include performing arithmetic, comparing two numbers, assigning data to a
worksheet cell, or answering questions of logic.
Example:
Arithmetic Operators
Arithmetic operators are similar to the operators you use in calculating mathematical expres-
sions.
Comparison Operators
Comparison operators are used to evaluate data to true or false to check whether a data
value meets a criterion.
Name Purpose
> (Greater than) Returns a true value if the number on its left is larger than the number on its
right; false, otherwise.
< (Less than) Returns a true value if the number on its right is larger than the number on
its left; false, otherwise.
>= (Greater than or equal Returns a true value if the number on its left is larger or the same as the
to) number on its right; false, otherwise.
<= (Less than or equal Returns a true value if the number on its right is larger or the same as the
to) number on its left; false, otherwise.
= (Equal to) Returns a true value if the numbers on both sides are the same; false, other-
wise.
<> (Not equal to) Returns a true value if the numbers on both sides are not the same; false,
otherwise.
Logical Operators
Logical operators compare two or more true/false values.
Name Purpose
AND Returns a true value if the expressions on its left and right are both true;
false, otherwise.
OR Returns a true value if the expression on its left or right is true; false,
otherwise.
NOT Returns a true value if the expression on its right is false; false, other-
wise.
Example:
The Do Loop
Definition:
A Do loop is a code group that repeats the execution of a series of VBA commands.
Consisting of the Do command, which marks the beginning of the loop, the Loop
command, which marks the end of the loop, and the While command, containing an
evaluative criterion placed just after Do or Loop, the Do loop repeats the lines of
VBA code placed within the loop until the While criterion is evaluated to a Boolean
value of false.
Example:
Example:
Example:
Measuring Distances
Positive coordinate values designated in the Offset property indicate that the offset
location is either below or to the right of the currently active cell; negative coordinate
values indicate that the offset location is either above or to the left.
Example:
Example:
A data range on the Clipboard is pasted to the active worksheet.
Depending on the VBE’s debugger settings, an error indicating that the For statement is incomplete
might appear; ignore the message.
1. Type For.
2. Press Enter at least twice to provide blank lines where repeating code will be
entered.
3. Type Next.
4. In the For statement, add a variable name after the word For.
5. In the Next statement, add the same variable name after the word Next.
For VariableName
Next VariableName
Range("CellAddr").Select
ActiveCell.CurrentRegion.Select
Selection.Copy
Worksheets(Name of the worksheet).Select
Range("CellAddr").Select
ActiveSheet.Paste
Range("CellAddr").Select
' Selecting the new active cell via the Offset property:
ActiveCell.Offset(num1, num2).Select
Scenario:
Knowing that you are in the process of building macros to generate reports, your manager
expresses her wish to view the work-in-progress. She wants you to include a fourth page in the
workbook that contains all the three portfolios. Hesitant to alter your existing work, you go
back to the drawing board with the original data to explore how to duplicate data ranges from
one worksheet to another.
1. Enter the code necessary to declare a. Display the Macro dialog box.
the variable x as an integer.
b. In the Macro dialog box, verify that the
DuplData is selected and click Edit.
Code Sample 1
Option Explicit
____________________
Sub DuplData()
Dim x As Integer
End Sub
c. Type Next
3. Add x as the counter variable used to a. Click at the end of the For statement,
count the number of times the loop add a space, and then type x after the
should run. word For.
4. Indicate the number of times the a. In the For statement, after the x counter
code in the loop should run should be variable name, type an equals sign fol-
one less than the total number of lowed by a space.
worksheets in the workbook, using
the Worksheet object and its Count
b. Type 1 as the starting value for the x
property.
counter variable followed by a space.
c. Type
ActiveCell.CurrentRegion.Select
to select the current region of the active
cell and press Enter.
e. Type Worksheets("All
Portfolios").Select to select the All
Portfolios worksheet, where the range
will be pasted and press Enter.
Code Sample 2
Sub DuplData()
'
For x = 1 to Worksheets.Count - 1
Worksheets(x).Select
Range("A1").Select
ActiveCell.CurrentRegion.Select
Selection.Copy
Worksheets("All Portfolios").Select
ActiveSheet.Paste
Next x
End Sub
b. Type ActiveCell.Offset().Select
and then press Enter.
Code Sample 3
'The completed DuplData macro:
Option Explicit
____________________________
Sub DuplData()
Dim x As Integer
For x = 1 To Worksheets.Count - 1
Worksheets(x).Select
Range("A1").Select
ActiveCell.CurrentRegion.Select
Selection.Copy
Sheets("All Portfolios").Select
Range("A1").Select
ActiveCell.Offset(x * 10, 0).Select
ActiveSheet.Paste
Next x
End Sub
7. Duplicate the data onto the All Port- a. In the workbook, run the DuplData macro.
folios worksheet.
b. Scroll up to observe the data that is added
to the All Portfolios worksheet.
9. Save the file and then close it. a. Save the file as All Portfolios Final.xlsm
Example:
Example:
Example:
A master macro calls a series of macros to perform specialized tasks that together for-
mat a report.
Selection.Font.Name = "Arial"
Selection.Font.Size = 14
Selection.Font.ld = True
With Selection.Font
.Name = "Arial"
.Size = 14
.Bold = True
End With
Example:
The End property locates the bottom of the body of a report.
Direction Commands
The following table describes the four built-in direction commands used with the End
property.
Command Effect
xlUp Same as pressing End+Up Arrow
xlToRight Same as pressing End+Right Arrow
xlToleft Same as pressing End+Left Arrow
xlDown Same as pressing End+Down Arrow
Worksheets(SheetRef).Select
Range("CellAddr").Select
Selection.End(xlUp).Select
ActiveCell.Offset(num1,num2).Select
ActiveCell.Offset(num1,num2).Select
ActiveSheet.Paste
5. If necessary, format the generated report.
a. Call a macro to find and format the unformatted areas.
Sub MacName()
Dim CV As Integer
For x = 1 To Worksheets.Count - 1
Worksheets(CV).Select
Call Macro 1
Call Macro 2
Call Macro 3
Call Macro 4
Range("CellAddr").Select
Selection.CurrentRegion.Select
Selection.Copy
Worksheets(SheetRef).Select
Range("CellAddrBelow").Select
Selection.End(xlUp).Select
ActiveCell.Offset(num1,num2).Select
ActiveCell.Value = Worksheets(CV).Name & " AddlTxt"
ActiveCell.Offset(num3,num4).Select
ActiveSheet.Paste
Next CV
Columns("ColRange").Select
Selection.Columns.AutoFit
End Sub
Setup:
From the C:\084037Data\Formatting Worksheets folder, open the Report Generator.xlsm file.
Scenario:
You are confident that the parts you have built will come together to generate formatted reports
for each stock portfolio and the additional All Portfolios worksheet, and set about writing the
code for the report generator.
The use of the rArr (⇒) symbol indicates that all code should be typed on one line and not broken up. This sym-
bol is used due to the constraints of the table.
1. Create a loop structure, in the a. In Visual Basic Editor, display the GenRep
GenRep macro that cycles through macro code.
the set of worksheets.
b. In the GenRep macro, type Dim x As
Integer to declare a counter variable
named x as an integer.
Code Sample 1
Sub GenRep()
Dim x As Integer
For x = 1 To Worksheets.Count - 1
Worksheets(x).Select
Next x
End Sub
Code Sample 2
Sub GenRep()
Dim x As Integer
For x = 1 To Worksheets.Count - 1
Worksheets(x).Select
Call SortLastCol
Call InsColRow
Call InsertTxt
Call FmtTxt
Next x
b. Type
Selection.CurrentRegion.Select
to select the entire data range, and then
press Enter.
c. Type Selection.End(xlUp).Select
and then press Enter.
d. Type ActiveCell.Offset⇒
(2, 0).Select to select a cell offset to
enter the portfolios’ names, and then
press Enter.
e. Type ActiveCell.Value = ⇒
Worksheets(x).Name & ⇒
" Portfolio" to insert portfolio header
text, and then press Enter.
Code Sample 3
Sub GenRep()
Dim x As Integer
For x = 1 To Worksheets.Count - 1
Worksheets(x).Select
Call SortLastCol
Call InsColRow
Call InsertTxt
Call FmtTxt
Next x
End Sub
5. Format the report generated on the a. Scroll down, and in the blank line after
All Portfolios worksheet. the Next x statement, type
Columns("B:E").Select to select col-
umns B to E, and then press Enter.
b. Type Selection.Columns.AutoFit to
resize the columns on the All Portfolios
worksheet.
7. True or False? The report generator generated the reports without error.
True
False
Scenario:
Your report generator lacks one final element, the formatted portfolio name headers. You begin
creating a macro to find and format the portfolio name headers to call from the report genera-
tor function.
1. Enter the code necessary to declare a. Display the Visual Basic Editor with the
and initialize a string variable named FindFormatPortHeaders macro code.
FoundCellAddress with the
address of the first found active cell,
in the FindFormatPortHeaders macro b. Type Dim FoundCellAddress ⇒
As String
to build the Do loop criterion.
d. Type FoundCellAddress = ⇒
ActiveCell.Address and press Enter.
Code Sample 1
Sub FindFormatPortHeaders()
FoundCellAddress = ActiveCell.Address
Do
Code Sample 2
Sub FindFormatPortHeaders()
Range("B4").Select
Cells.Find(What:="portfolio", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False).Activate
FoundCellAddress = ActiveCell.Address
Do
With Selection.Font
.Name = "Arial"
.Size = 14
.Bold = True
End With
Cells.FindNext(After:=ActiveCell).Activate
End Sub
6. True or False? The report was successfully generated with fully formatted text.
True
False
1. How are methods and properties, such as AutoFit and Address, attached to various ref-
erences?
a) With a period
b) With a comma
c) With a semi-colon
d) With a pair of parentheses
Lesson 2 Follow-up
In this lesson, you created VBA code to automate the application of several formatting proper-
ties to a worksheet.
1. Do you think that creating a report generator is a useful tool?
Creating an Interactive
Worksheet
In this lesson, you will create an interactive worksheet.
You will:
• Determine the appropriate dialog box for capturing user input.
• Capture user input.
TOPIC A
Determine the Dialog Box Type
You know how to create macros that don’t require any interaction from a user. In some cases,
you may want to develop a macro that is based on specific user interaction. In this topic, you
will determine the appropriate dialog box to capture specific information from a user.
Creating a macro that asks users for input can be tricky. If possible, you must use a dialog box
whose interactive controls minimize the consequences of user error like ruined data or a
crashed computer. By determining user input and then creating a dialog box to capture user
input while minimizing error, you will be able to create VBA-scripted macros that get the job
done without unintended errors and crashes.
Message Boxes
A message box is used by macro developers to capture user input when a macro is run. Mes-
sage boxes consist of a message along with at least one button, which the user can click.
When a running macro displays a message box, the code in the macro ceases execution until
the user’s input is received and evaluated. Subsequent code in the macro can then be executed
or skipped, based on the user’s response.
Input Boxes
Definition:
An input box is a type of dialog box used by macro developers to capture entered text
data from a user when a macro is run. It consists of a message, a text box into which a
user can type data requested by the message, and the OK and Cancel buttons, which
the user can click. When a running macro displays an input box, the code in the macro
ceases execution until the user’s input is received and evaluated. Subsequent code in
the macro can then be executed or skipped, based on the text entered in the text box.
Example:
ACTIVITY 3-1
Determining the Dialog Box Type
Scenario:
A coworker, who is given charge of an in-house training session for new employees on VBA
scripting, plans to talk about the dialog box usage. She has prepared some scenarios for the
class to determine whether the input or message boxes should be used, and wants you to test
out her work beforehand.
1. Which box would you use for a program that requires the user to enter the new name
of a worksheet that’s being renamed?
a) Input box
b) Query box
c) Message box
d) Exclamation box
2. True or False? You would use a message box to create a warning dialog box to inform a
user of a prior input error and halt the program until the user acknowledges the mes-
sage by clicking OK.
True
False
3. True or False? A macro that sends and monitors the printing of an Excel workbook
causes a dialog box to appear, when the print job fails. The dialog box asks whether
the user wants to try sending the file to the printer again, or cancel the print job. To
create such a dialog box, you would use an input box.
True
False
5. True or False? After submitting search information to a large database, a user waits for
a response. Suddenly, a dialog box appears with an animated icon and a ″Searching
Records″ message. When the data is retrieved from the database, the dialog box disap-
pears automatically from the screen, and the data is displayed. To create such a dialog
box, you would use a message box.
True
False
6. Which box would you use to create a warning dialog box to inform a user of a prior
input error and halt the program until the user acknowledges the message by clicking
OK?
a) Query box
b) Message box
c) Input box
d) Exclamation box
TOPIC B
Capture User Input
You know how to determine the type of dialog box you should use to gather appropriate infor-
mation from user interaction. Gathering useful information allows you to modify a worksheet
based on an interaction. In this topic, you will create a macro that depends on user interaction
to modify a worksheet.
Imagine you need to create two different views of sales data in a worksheet depending on
whether the user is a manager or a salesperson. One way to determine the correct view to be
displayed would be to create a macro that asks if the user is a manager. Using VBA to capture
user input modifies a worksheet or its content based on the input.
Example:
Constants
Definition:
Constants are variables whose values are predefined and unchangeable in VBA.
Because they are often used to designate a numeric value required by a function, their
names reflect their purpose. Constants typically begin with the letters vb followed by a
brief description of their usage.
Example:
Example:
Example:
Select Case
Case
Case
Case Else
End Select
2. Enter the variable name to be evaluated by the Case structures and the cases’
criteria values.
a. In the Select Case statement, after the word Case, type the name of the
variable whose value will be evaluated by the Case statements.
b. In the first Case statement, enter a data value as the evaluative criterion.
c. In the next Case statement, enter a different data value as the evaluative
criterion.
d. If necessary, in the subsequent Case statements, enter unique data values as
the statements’ evaluative criteria.' Adding criteria:
Case Criterion1
Case Else
End Select
3. Enter the code to be run based on the criterion evaluated in each Case
statement.
a. For the first Case statement, in between the first and second Case
statements, enter the code to be run if the criterion for the first Case
statement is met.
b. For the second Case statement, in between the second Case statement and
the next Case or Case Else clause, enter the code to be run if the crite-
rion for the second Case statement is met.
c. If necessary, for the subsequent Case statements, in between the Case
statement for which you want to enter the code and the next Case, Case
Else, or End Select clause, enter the code to be run if the criterion for
the Case statement is met.' Adding criteria:
Case Criterion1
Case Criterion2
Case Else
End Select
4. If necessary, enter the code to be run if none of the criteria for the Case state-
ments are met.
a. For the Case Else statement, in between the Case Else and End
Select clauses, enter the code to be run if the criteria for the Case
statements are not met.' Adding criteria:
Case Criterion1
Case Criterion2
Case Else
Code to run if no criteria met
End Select
If comparison1 Then
Else
End If
Scenario:
Your manager reviews an extensive log generated by a call center, and has recorded several
macros to sort the data differently. Instead of remembering the different macro names, he
wants to run a single macro that asks him to sort data and perform action. He hands off the
project to you and asks you to come up with a prototype that sorts using the DateThenTime
and RepSort macros, or displays an error message followed by a macro reset, if bad input is
entered by a user.
1. Declare the variables necessary to a. In Visual Basic Editor, display the code for
hold the information for the InputBox the SortBy macro.
function parameters and the user’s
response.
b. In the SortBy macro, in the first blank line
below the comment lines, declare Mes-
sage, TitlebarTxt, DefaultTxt, and
SortVal as string variables.
Code Sample 1
Sub SortBy()
'
'
'
Dim Message, TitlebarTxt, DefaultTxt, SortVal As String
Dim YNAnswer As Integer
End Sub
d. Press Enter.
Code Sample 2
Sub SortBy()
'
'
'
Dim Message, TitlebarTxt, DefaultTxt, SortVal As String
Dim YNAnswer As Integer
Message = _
"Enter a number to sort by the following fields:" & _
vbCrLf & _
" 1 -- By Date and Time" & vbCrLf & _
" 2 -- By Customer Service Rep, Date, and Time"
End Sub
Code Sample 3
Sub SortBy()
'
'
'
Dim Message, TitlebarTxt, DefaultTxt, SortVal As String
Dim YNAnswer As Integer
Message = _
"Enter a number to sort by the following fields:" & _
vbCrLf & _
" 1 -- By Date and Time" & vbCrLf & _
" 2 -- By Customer Service Rep, Date, and Time"
End Sub
Code Sample 4
Sub SortBy()
'
'
'
Dim Message, TitlebarTxt, DefaultTxt, SortVal As String
Dim YNAnswer As Integer
Message = _
"Enter a number to sort by the following fields:" & _
vbCrLf & _
" 1 -- By Date and Time" & vbCrLf & _
" 2 -- By Customer Service Rep, Date, and Time"
End Sub
Code Sample 5
Sub SortBy()
'
'
'
Dim Message, TitlebarTxt, DefaultTxt, SortVal As String
Dim YNAnswer As Integer
Message = _
"Enter a number to sort by the following fields:" & _
vbCrLf & _
" 1 -- By Date and Time" & vbCrLf & _
" 2 -- By Customer Service Rep, Date, and Time"
Select Case
Case
Case
Case Else
End Select
End Sub
Code Sample 6
Select Case SortVal
Case "1"
Case "2"
Case Else
End Select
6. Enter the code to run the sorts based a. Click in the blank line below Case “1” and
on the criteria evaluated in each call the DateThenTime macro for the first
Case statement. case.
Code Sample 7
Select Case SortVal
Case "1"
Call DateThenTime
Case "2"
Call RepSort
Case Else
End Select
c. Type End If
d. Press Enter.
Code Sample 8
' The completed SortBy macro code:
Sub SortBy()
Case "1"
Call DateThenTime
Case "2"
Call RepSort
Case Else
End Sub
10. Provide user input that directs the a. In the Input text box that appears, type 2
macro to sort the data by the Reps’
names.
b. Click OK.
11. Test to see if the Yes/No message a. On the worksheet, choose Macros to dis-
box works correctly if the user’s play the Macro dialog box.
input is incorrect.
b. From the list of macros, select the SortBy
macro, and click Run.
d. Click OK.
g. Click OK.
Scenario:
Pleased with your prototype, your manager asks you to include the other sorts.
1. Building on the code you entered to complete the last activity, add additional
Case statements to sort by the other three sort macros.
• Have the ClientDateTime macro run if 3 is entered by the user.
• Have the ProductDateTime macro run if 4 is entered by the user.
• Have the ProblemProduct macro run if 5 is entered by the user.
2. Alter the input box message so that the user knows to enter 3, 4, or 5 to perform
the additional sorts.
• Add the text ″ 3 -- By Client, Date, and Time″
• Add the text ″ 4 -- By Product, Date, and Time″
• Add the text ″ 5 -- By Problem and Product″
Be sure to add the appropriate concatenation and line feed characters so that the
choices are presented in list format in the input box.
3. Alter the default text message and warning message box message to reflect the
new changes.
5. Save the file as My User Interactive Practice.xlsm and then close it.
2. How will you determine whether to use an input box versus a message box?
TOPIC A
Insert, Copy, and Delete Worksheets
You know how to manually insert, copy, and delete worksheets. You are working with a work-
book that requires you to do these tasks frequently. In this topic, you will create macros to
insert, copy, and delete worksheets.
Inserting, copying, and deleting worksheets are the most commonly performed tasks in an
Excel workbook. Repeatedly performing these tasks could become taxing at times. Thus, VBA
helps you to automate multiple worksheets related tasks.
Example:
Example:
Example:
Worksheets.Add Before:=Worksheets(SheetRef)
Worksheets.Add After:=Worksheets(SheetRef)
Worksheets("Name").Delete
Worksheets(PositionNumber).Delete
Worksheets("Name").Copy
Worksheets(PostionNumber).Copy
Worksheets(SheetRef).Copy _
Before:=Worksheets(SheetRef)
Worksheets(SheetRef).Copy _
After:=Worksheets(SheetRef)
ACTIVITY 4-1
Inserting Worksheets
Data Files:
• New Sheets.xlsm
Scenario:
Your manager works with different forms that must be replicated on separate worksheets
named for the months of the year. Although the form hasn’t been finalized, he wants you to
get started on figuring out a way to copy and rename the monthly worksheets from the origi-
nal. You begin by coding a macro that inserts the new worksheets into a workbook.
b. Press Enter.
b. Type Next x
Code Sample 1
Sub AddSheets()
'
'
'
Dim x As Integer
For x = 1 To 12
Next x
End Sub
3. Enter the code for inserting a a. In between the For and Next statements,
worksheet. type Worksheets.Add to insert a
worksheet and press the Spacebar.
Code Sample 2
Sub AddSheets()
Dim x As Integer
For x = 1 To 12
Worksheets.Add After:=Worksheets(x)
Next x
End Sub
ACTIVITY 4-2
Deleting a Worksheet
Data Files:
• Project.xlsm
Scenario:
After inserting the 12 new worksheets, you realize that you have 13 sheets in the workbook;
one for the original form, and 12 for the months. Since you know that the template-like form
is not needed once the monthly sheets are created, you decide to have the macro delete it after
the new sheets are inserted.
1. Add a line of code to the DeleteSheet a. Display the Visual Basic Editor for the
macro that deletes Sheet1 after the DeleteSheet macro.
12 other sheets are inserted.
b. In the code editing window, in the
DeleteSheet macro, in between the
Next x and End Sub statements, type
Worksheets.Delete
Code Sample 1
Next x
Worksheets.Delete
End Sub
Code Sample 2
Next x
Worksheets(1).Delete
End Sub
ACTIVITY 4-3
Copying Worksheets
Data Files:
• OG Corp.xlsm
Scenario:
You are informed by your manager that the form content has been finalized, and you need to
modify the code to copy the finalized form into the 12 monthly worksheets.
1. Use the Worksheets collection a. Within the For Next loop, type
object, the Copy method, and the Worksheets.Copy
After optional variant, in the For
Next loop to copy the first
b. Insert a pair of parentheses after the
worksheet to 12 new copies at the
Worksheets object reference.
end of the worksheet list.
Code Sample 1
'The completed code for the CopySheets macro:
Sub CopySheets()
Dim x As Integer
For x = 1 To 12
Worksheets(1).Copy After:=Worksheets(x)
Next x
Worksheets(1).Delete
End Sub
4. True or False? Sheet2 through Sheet13 contain the same information originally con-
tained in Sheet1.
True
False
1. When a macro is executed, by default, where does the Add method place the new
worksheet?
a) At the end of the worksheet list.
b) At the beginning of the list.
c) After a selected worksheet.
d) In alphabetical order by the worksheet name.
Expressions
Definition:
Expressions are combinations of data, operators, functions, and variables that, together,
process information to yield a single data value. Depending on their length, complex-
ity, and repetitive use, expressions can either stand alone within a macro or have their
results assigned to variables that are then used to represent them in subsequent code.
Example:
Example:
Example:
Worksheets(SheetRef).Name = Expression
Scenario:
Your form-replicating project lacks one final feature, naming the copied worksheets with the
months of the year. You insert the code designed to rename the new sheets.
1. Enter the code necessary to rename a. In the RenameSheets macro, in the For
the newly inserted worksheet with Next loop, below the statement that
the appropriate month of the year. copies in the new worksheet, type
Worksheets()
e. Type Format(DateSerial⇒
(1,x,1), "mmmm") to enter the expres-
sion that assigns the full name of the
appropriate month to the newly inserted
worksheet.
Code Sample 1
Sub RenameSheets()
Dim x As Integer
For x = 1 To 12
Worksheets(1).Copy After:=Worksheets(x)
Worksheets(x + 1).Name = Format(DateSerial(1,x,1), "mmmm")
Next x
Worksheets(1).Delete
End Sub
1. What is the syntax you would use to rename a single worksheet with a macro?
a) Worksheets(SheetRef).Name = Expression
b) Worksheets (x+1)
c) Worksheets(SheetRef)
d) Worksheets Expression = Name(SheetRef)
2. How should the valid integer value for the DateSerial function for the year be dis-
played?
a) Always use four digits to show the year as 2005.
b) Always display the year with only two digits such as: 08 for 2008.
c) Any representation of 1 to 9999.
d) Always display the year following the month and day such as 01/01/2008.
Example:
' By name:
Worksheets("SheetName").Move
' By position:
Worksheets(Number).Move
Worksheets(SheetRef1).Move Before:=Worksheets(SheetRef2)
Worksheets(SheetRef1).Move After:=Worksheets(SheetRef2)
ACTIVITY 4-7
Moving Worksheets Within a Workbook
Data Files:
• OGC Sales.xlsm
Scenario:
Due to your company’s growth, your manager finds it difficult to manually handle too many
pages in a workbook. She asks you to build some navigation controls to rearrange the
worksheets automatically so that she is not in need to scroll all the time. You start by writing a
macro that moves the Southeast division’s sheets to the beginning of the worksheet list.
1. Identify the worksheet to be moved. a. Within the SEMove macro, after the com-
mented lines, type Worksheets().Move
to enter the code necessary to move a
worksheet.
Code Sample 1
Sub SEMove()
Worksheets("SE Sales").Move Before:=Worksheets(1)
End Sub
3. Add the additional code necessary to a. Copy and paste the line of code you just
move the SE Team, Clients, and Mar- entered onto the next line.
keting worksheets, under the code
you just entered.
b. In the newly pasted code, change the
name of the worksheet being moved to
SE Marketing.
Code Sample 2
Worksheets("SE Sales").Move Before:=Worksheets(1)
Worksheets("SE Marketing").Move Before:=Worksheets(1)
Worksheets("SE Clients").Move Before:=Worksheets(1)
Worksheets("SE Team").Move Before:=Worksheets(1)
2. True or False? When moving a worksheet, within the parentheses, you need to identify
the sheet to be moved by its name only.
True
False
Example:
Worksheets.PrintPreview
Worksheets("SomeName").PrintPreview
Worksheets(Number).PrintPreview
3. Run the macro.
4. Preview the printout in the Print Preview window.
Worksheets(x) Preview
Next x
Worksheets(SheetRef1).Preview
Worksheets(SheetRef2).Preview
Worksheets(SheetRef3).Preview
Scenario:
Your manager asks you to figure out a way to have all the worksheets in her workbook printed
at once without having to specify the sheets for printing. You begin with a test macro that pre-
views the worksheet pages.
Code Sample 1
Sub PrintAllSheets()
Worksheets.PrintPreview
End Sub
2. Run the macro to preview the print- a. Display the Macro dialog box.
out.
b. Select the PrintAllSheets macro and click
Run.
ACTIVITY 4-10
Previewing Selected Adjacent Worksheets
Data Files:
• New Divisions.xlsm
Scenario:
Your manager wants you to write another custom macro that prints the first four sheets in the
workbook. That way, she can print the sheets for any division by positioning them as the first
four sheets, and then print. Mindful of wasting paper, you build a test macro that previews the
selected sheets.
Code Sample 1
Sub PrintDivision()
Dim x As Integer
For x = 1 To 4
Worksheets(x).PrintPreview
Next x
End Sub
3. Run the macro to preview the print- a. Close the Visual Basic Editor.
out.
b. Display the Macro dialog box.
4. Preview each sheet. a. View the preview for the first sheet, and
then click Close Print Preview.
Scenario:
Before you show your manager the new macro, you test it by reordering the worksheets to see
if the first four sheets in the worksheets list are still selected and previewed.
1. Using any of the following macros, reorder the worksheets in the worksheet list.
• NEMove
• SEMove
• NWMove
• SWMove
• MWMove
• FWMove
2. Run the PrintDivision macro again to see which sheets are printed.
3. True or False? The macro always prints the first four worksheets in the list, so if the
list is reordered, different worksheets would be printed.
True
False
Scenario:
Your manager would also like to print out worksheets by type, not region. You code a test
macro that previews the Sales worksheets for the NE and SE divisions.
2. Copy and paste the code you just a. Select Worksheets("NE Sales")
entered onto the next blank line. .PrintPreview.
c. Type S
Code Sample 1
Sub PrintSales()
Worksheets("NE Sales").PrintPreview
Worksheets("SE Sales").PrintPreview
End Sub
4. Run the macro to preview the print- a. Close the Visual Basic Editor.
out.
b. Display the Macro dialog box.
5. Preview each sheet. a. View the preview for the first sheet, and
then click Close Print Preview.
Lesson 4 Follow-up
In this lesson, you created macros that facilitate the process of inserting, copying, deleting,
renaming, reordering, and printing worksheets. Doing these tasks will save ample time and
enable you to perform other important tasks.
1. List the various activities you can perform on multiple worksheets.
2. How will working with multiple sheets simultaneously help in your job role?
Performing Calculations
In this lesson, you will perform calculations.
You will:
• Create a user-defined function.
• Automate a SUM function.
TOPIC A
Create User-Defined Functions
You know that you can use VBA’s default functions to create macros. Sometimes, however,
the default macros may not suit your needs. In this topic, you will augment VBA’s capabilities
by creating a user-defined macro.
Believe it or not, Excel can’t do it all—there are times when you need to calculate or manage
data on a worksheet that can’t be accomplished by the software’s copious supply of stock
functions. By creating a user-defined custom function, you can perform tasks that would other-
wise be unavailable to a casual Excel user.
User-Defined Functions
Definition:
A user-defined function is a custom function created with VBA code to return a data
value that cannot be achieved by using the set of built-in functions available in Excel.
It consists of the following parts:
• A beginning Function statement that lists the name of the user-defined func-
tion, followed by a pair of parentheses.
• One or more optional variable names listed within the parentheses.
• A closing End Function statement.
• Within the function, VBA code that processes data.
• Within the function, an assignment statement whose result is placed into a vari-
able having a name identical to the name of the function.
Function Calls
A function call occurs when a function causes another function to perform data calcu-
lations. Typically, function calls are used when the calling function needs data that can
be processed only by another function to complete the calling function’s data process-
ing goal.
Types of Functions
Similar to the Personal Macro Workbook, which enables any workbook to use the macros
stored in it, public functions are functions that can be shared by multiple projects. Their oppo-
site, private functions, can be used only by the project containing the module where the
function code exists.
Arguments
Definition:
Arguments are variables used to pass data from a worksheet to a function for process-
ing. The function’s arguments are defined within the parentheses of the Function
statement, and are used within the function’s processing code to obtain a result.
Depending on the processing goal, a function may require one or more arguments, or
none at all.
Example:
ACTIVITY 5-1
Creating and Applying a User-Defined Function
Data Files:
• Price Level.xlsm
Scenario:
You work for a local newspaper and report on business issues. Because a coworker was reas-
signed to another story, your editor asks you to complete a project she was working on,
creating a custom Excel function that compares the value of money between two years after
taking inflation into account.
e. Click OK.
2. Enter amount, byr, and eyr as the a. After the function name, between the
function’s arguments list. empty parentheses, click and type
amount
b. Type a comma.
e. Type a comma.
3. Enter the code to convert an amount a. Within the PriceLevel function, type
in a base year to an inflation- If Then and press Enter.
adjusted equivalent in an ending year
between 1913 and 2008, using the
b. In the line below, type Else and press
CPI_idx function.
Enter.
Code Sample 1
Public Function PriceLevel(amount, byr, eyr)
If byr < 1913 Or byr > 2008 Or eyr < 1913 Or eyr > 2008 Then
PriceLevel = 0
Else
e. Type a comma.
g. Type a comma.
Example:
Example:
Example:
Example:
Example:
When used in code that refers to two Declared Range objects, the Columns property functions
akin to a column offset; it provides the key to mapping the parts of one range to another.
Example:
Scenario:
Your manager asks you to take a multi-worksheet report that he has developed and create a
macro to automatically sum the last two columns of data presented on each worksheet. You
have already created a macro code for cycling through the pages with a For Next loop, and
now ready to build the rest.
1. Declare myData and myTotal as a. Under the “Declare the Range objects
Range objects, in the AddTotals here” comment, declare myData as a
macro, under the first comment. Range object.
c. Press Enter.
2. Set the myData Range object equal a. In the line below the “Set the data range
to the current region of cell A7, object” comment, use the Range object
under the second comment. to select cell A7.
Code Sample 1
Sub AddTotals()
Dim x As Integer
Worksheets(x).Select
End Sub
7. Check the macro results to view the a. Select the Northeast worksheet and scroll
inserted totals. down to view the inserted totals at the
bottom of the data columns.
Lesson 5 Follow-up
In this lesson, you used custom functions to perform calculations on worksheet data beyond
the limits of Excel’s built-in functions. You also automated the insertion of the SUM function at
the bottom of an unknown amount of data.
1. What is the primary reason for creating custom user-defined functions?
2. Which tools related to creating and applying macros are the most powerful in your day-
to-day use of Excel?
3. Can you think of additional ways in which VBA-scripted macros can solve business
problems besides the scenarios presented in this course?
What’s Next?
This is the last course in the series.
LESSON LABS
Due to classroom setup constraints, some labs cannot be keyed in sequence immediately fol-
lowing their associated lesson. Your instructor will tell you whether your labs can be practiced
immediately following the lesson or whether they require separate setup from the main lesson
content. Lesson-level lab setup information is listed in the front of this manual in the course
setup section.
LESSON 1 LAB 1
Recording Macros for a Toolbar
Data Files:
• LLL1.xlsx
Scenario:
You are asked to come up with a solution for quick-formatting your department’s worksheets.
You decide to create some prototype macros that can change the background color of any open
spreadsheet, and a custom toolbar having tools that run the macros.
2. In the Personal Macro Workbook, record three macros that change the worksheet’s
background color to:
• Red
• Blue
• Yellow
7. Using the custom toolbar, change the background color of the LLL1.xlsx file.
LESSON 2 LAB 1
Creating Grade Sheet Reports
Data Files:
• LLL2.xlsx
• xLLL2.xlsm
Scenario:
You work in the Registrar’s Office at a local university, and you are asked to prepare a report
that lists the grades received by students of Freshman English for the recently ended term.
After cutting and pasting the data for three class sections from the mainframe onto individual
worksheets, you decide to collate them into a single sheet that lists them all.
1. Open the xLLL2.xlsm file to view the finished version of the reports.
2. Open the LLL2.xlsx file to display the unformatted data and the headers for the
collated All Sections worksheet.
4. In Visual Basic Editor, at the bottom of the list of macros, in a blank line below
the last line of code, type Sub ReportGenerator() to create a new empty
macro.
You must be careful to test and debug your code during this phase of the lab. Otherwise, you might ruin your
data, if you don’t save before running the macro code after each code change.
Scenario:
It’s the end of the semester and you’re the faculty member in charge of collecting the first
semester grades for Freshman English. Your colleagues want to be able to review the grades
under four criteria:
• By course grade (from highest to lowest).
• By final exam score (from highest to lowest).
• By mid-term exam score (from highest to lowest).
• By student last name (in alphabetical order).
1. Record four macros that are sorted by the relevant score or student name. (Since
the data will not be changing, you do not have to worry about entering additional
code to resize the sort ranges).
2. In Visual Basic Editor, at the bottom of the list of macros, in a blank line below
the last line of code, type Sub InteractiveGradeSheet() to create a new
empty macro.
3. Using an input box, a Select Case structure, and a message box, enter the code
necessary to build a macro that performs the following actions.
a. Presents an input box that:
• Lists an appropriate name in its title bar.
• Directs the user to enter input to perform the four different sorts in the body of
its main message.
• Displays default text in its text box stating what the correct responses are.
b. Performs the sort based on the user’s response.
c. Upon a data entry error, displays a Yes/No message box containing:
• An error message.
• A question for the user to indicate whether the sort should be attempted again.
Scenario:
Your manager, who is managing a 52-sheet workbook, comes to you for help. He asks you to
figure out a way to move a quarter’s worth (13 weeks) of the worksheets for each quarter to
the beginning of the worksheet list, from where it can be printed out.
1. In the LLL4.xlsm file, review the existing code in the MoveQuarterForward macro.
It uses an input box and a Select Case construct to ask the user for input, and
then performs four different actions based on that input.
3. In the empty Case statements, enter the code necessary to move each quarter’s
worksheets to the beginning of the worksheet list such that they appear in a chro-
nological order (1 through 13, 14 through 26, 27 through 39, and 40 through 52).
4. Test your code entries until you are satisfied with your results.
5. In Visual Basic Editor, at the bottom of the list of macros, in a blank line below
the last line of code, type Sub PrintQuarter() to create a new empty macro.
6. In the PrintQuarter macro, enter a loop structure to print preview the first 13
worksheets in the workbook.
7. Test the PrintQuarter macro until you are satisfied with your results.
Scenario:
The manager of the mutual fund sales force at your firm wants you to figure out an easy way
to calculate the sales commissions based on the amount of money invested by a customer. He
provides you with the fee schedule, and asks you to come up with a solution.
1. In the LLL5.xlsx file, create a custom function called SalesFee to calculate the
sales commissions based on the following fee schedule.
The function should take one argument—the amount invested—and return a value
equal to the sales commission.
2. On the worksheet, in cell F7, use the SalesFee function as a formula. Designate
cell E7 as the argument for the function.
3. Copy the function you just entered into the other empty cells in the Commission
column.
Lesson 2
Activity 2-1
5. True or False? In cell B4, the name of each worksheet was inserted along with the text
″Portfolio″.
✓ True
False
Activity 2-2
2. True or False? Concatenation refers to the act of connecting two or more pieces of
text information together with an ampersand to form a single, longer piece of text.
✓ True
False
Activity 2-4
4. True or False? The macro successfully sorted the different stock tables having differ-
ent numbers of rows.
✓ True
False
Solutions 165
SOLUTIONS
Activity 2-5
8. Why did the data tables get duplicated on rows 11, 21, and 31?
a) Excel automatically gauged their size and inserted them in a ″best fit″ location.
✓ b) The Offset property of x * 10 caused the row offset values to be 10, 20, and 30 each
time the loop iterated.
c) Because of an error; the Offset values would have placed them on rows 10, 20, and
30.
d) None of these.
Activity 2-6
Activity 2-7
7. True or False? The report generator generated the reports without error.
True
✓ False
Activity 2-8
6. True or False? The report was successfully generated with fully formatted text.
✓ True
False
Activity 2-9
1. How are methods and properties, such as AutoFit and Address, attached to various ref-
erences?
✓ a) With a period
b) With a comma
c) With a semi-colon
d) With a pair of parentheses
Lesson 3
Activity 3-1
1. Which box would you use for a program that requires the user to enter the new name
of a worksheet that’s being renamed?
a) Input box
b) Query box
✓ c) Message box
d) Exclamation box
2. True or False? You would use a message box to create a warning dialog box to inform a
user of a prior input error and halt the program until the user acknowledges the mes-
sage by clicking OK.
✓ True
False
3. True or False? A macro that sends and monitors the printing of an Excel workbook
causes a dialog box to appear, when the print job fails. The dialog box asks whether
the user wants to try sending the file to the printer again, or cancel the print job. To
create such a dialog box, you would use an input box.
True
✓ False
4. True or False? When run, a macro displays a dialog box that enables the user to enter
information to sort a table of data on a spreadsheet in five different ways. To create
the dialog box in the macro code, you would use an input box.
✓ True
False
5. True or False? After submitting search information to a large database, a user waits for
a response. Suddenly, a dialog box appears with an animated icon and a ″Searching
Records″ message. When the data is retrieved from the database, the dialog box disap-
pears automatically from the screen, and the data is displayed. To create such a dialog
box, you would use a message box.
True
✓ False
6. Which box would you use to create a warning dialog box to inform a user of a prior
input error and halt the program until the user acknowledges the message by clicking
OK?
a) Query box
Solutions 167
SOLUTIONS
✓ b) Message box
c) Input box
d) Exclamation box
Lesson 4
Activity 4-1
Activity 4-2
4. Which worksheets are listed after you run the DeleteSheet macro?
a) Sheet1 through Sheet12
b) Sheet1 through Sheet13
c) Sheet2 through Sheet12
✓ d) Sheet2 through Sheet13
Activity 4-3
4. True or False? Sheet2 through Sheet13 contain the same information originally con-
tained in Sheet1.
✓ True
False
Activity 4-4
1. When a macro is executed, by default, where does the Add method place the new
worksheet?
✓ a) At the end of the worksheet list.
b) At the beginning of the list.
c) After a selected worksheet.
d) In alphabetical order by the worksheet name.
Activity 4-6
1. What is the syntax you would use to rename a single worksheet with a macro?
✓ a) Worksheets(SheetRef).Name = Expression
b) Worksheets (x+1)
c) Worksheets(SheetRef)
d) Worksheets Expression = Name(SheetRef)
2. How should the valid integer value for the DateSerial function for the year be dis-
played?
a) Always use four digits to show the year as 2005.
b) Always display the year with only two digits such as: 08 for 2008.
✓ c) Any representation of 1 to 9999.
d) Always display the year following the month and day such as 01/01/2008.
Activity 4-8
2. True or False? When moving a worksheet, within the parentheses, you need to identify
the sheet to be moved by its name only.
True
✓ False
Activity 4-11
3. True or False? The macro always prints the first four worksheets in the list, so if the
list is reordered, different worksheets would be printed.
✓ True
False
Activity 4-13
Solutions 169
SOLUTIONS
2. True or False? In PrintPreview, if no workbook is chosen, the default is to display all
worksheets in the workbook.
✓ True
False
GLOSSARY
ActiveSheet object code continuation character
An Excel VBA object that represents the cur- A VBA language component that enables the
rently active worksheet in the workbook. presentation of an unusually long VBA com-
mand as wrapped text on several lines.
Add method
A method of the Worksheets Columns object
collection object used to add a new, An Excel VBA object that represents one or
blank worksheet in a worksheet list. more columns on a worksheet.
Glossary 171
GLOSSARY
counter variable Else clause
A variable used in a For Next loop to An optional clause in the If Then decision
count the number of times the loop repeats structure invoked when the criterion expres-
the code inside it. sion in the If Then statement is evaluated to a
Boolean value of false.
CurrentRegion property
A property of the ActiveCell object that End property
describes the largest possible range of cells An Excel VBA property often used with the
holding data in which the currently active cell Selection object to locate the beginning or
is contained. end of data being generated on a worksheet.
Glossary 173
GLOSSARY
Range object cell addressing VBA comment
A VBA cell-addressing convention that orga- A line of explanatory text that you can enter
nizes a cell range assigned to a Declared in a macro to help identify and document the
Range object. macro, and to provide the programmer with
reminders on what the macro is supposed to
Range object do.
An Excel VBA object that represents a range
of cells on a worksheet. VBA
(Visual Basic for Applications) A program-
Rows property ming language used to create macros in
A property of a Declared Range object Microsoft Office applications. When you
that represents the rows in a range. record a macro, Excel automatically translates
the keystrokes and commands into VBA code
Select Case
language, and creates and stores the macro.
A VBA code structure that enables the code
in a macro to be executed or ignored based vbCrLf character
on a condition, such as an entered response A VBA language component used to indicate
from a user. where the text in a long input box or message
box should be broken and placed on the next
Select method
line.
An Excel VBA method used to select part of
a worksheet. VBE
(Visual Basic Editor) A part of the Excel
Selection object
application where you can create, edit, and
An Excel VBA object that represents the cur-
delete macro code.
rent selection on the worksheet: a selected
cell, a selected range, a selected column, and Worksheets collection object
so on. An Excel VBA object that manages the col-
lection of worksheets in the workbook.
Set statement
A VBA language component used to assign a
cell range to a Declared Range object.
User-defined function
A function created with VBA code to return a
data value that cannot be achieved by using
the set of functions available in Excel.
Value property
A VBA property that represents the data
stored in an object, such as a worksheet cell.
variable naming rules
Rules that prescribe the kinds of names you
can give to variables.
variables
Named locations you can create and use in a
macro to store data for processing.
INDEX
A G
argument, 139 groups
code, 17
C
character I
code continuation, 89 input box, 85
vbCrLf, 90
command L
Call, 66 loops
commands Do, 53
direction, 68 For Next, 53
concatenation, 37
M
constants, 88
Macro Recorder, 4
counter variable, 53
macros, 3
D message box, 84
data types, 49 methods, 11
dialog boxes Add, 108
Macro, 3 AutoFit, 64
Trust Center, 28 Copy, 56, 109
digital certificate, 27 Delete, 109
digital signature, 28 Move, 123
Paste, 56
E PrintOut, 127
Else clause, 140 PrintPreview, 127
expressions, 118 Select, 45
modules, 10
F
folders O
Modules, 10 Object-Oriented Programming, 2
function call, 139 objects, 10
functions ActiveSheet, 35
DateSerial, 118 Columns, 64
Format, 119 Declared Range, 145
InputBox, 87 Range, 44
MsgBox, 89 Selection, 34
private, 139 Worksheets collection, 54
public, 139 operators, 51
User-defined, 138 arithmetic, 51
Index 175
INDEX
assignment, 51
comparison, 52
logical, 52
P
Personal Macro Workbook, 5
process
debugging, 16
projects, 10
properties, 11
Address, 65
Columns, 148
Count, 54
CurrentRegion, 45
End, 67
Font, 66
Formula, 147
Name, 36
Offset, 55
Rows, 147
Value, 36
R
Range object cell addressing, 146
S
Set statement, 146
settings
macro security, 28
structures
Decision, 91
If Then, 92
Select Case, 91
T
tools
debugging, 17
V
variable naming rules, 50
variables, 50
Strongly typed, 50
Weakly typed, 50
VBA comment, 12
Visual Basic Editor (VBE), 9
Visual Basic for Applications (VBA), 2