0% found this document useful (0 votes)
132 views192 pages

Microsoft Office 2007 - VBA

Uploaded by

Sebas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
132 views192 pages

Microsoft Office 2007 - VBA

Uploaded by

Sebas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 192

Microsoft® Office Excel® 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.)

To access your online resources:


1. Go to the New Horizons homepage at www.newhorizons.com.
2. Click the Student Resources link on the lower left side of the New Horizons homepage.
3. Click on the Learning Port link to log in to the site.
4. Log in to the Learning Port using one of the options below:
Option 1: Returning User -- if you have an existing classroom Learning Port account, enter your
Username and Password in the Registered Student area and click Login.
a) Once you are successfully logged in to Learning Port, the homepage will display.
b) Enter the Access Key box and click on Send.
c) Your online learning resources will be added to your Catalog.
-OR-
Option 2: New User -- if you are a new classroom Learning Port user, you will need to complete
the Personal Information form.
a) Begin by clicking on the Enroll button. The Access Key box will display.
b) Enter the Access Key in the Access Key box and click on Send.
c) The Personal Information form will display. Enter your information and click on Submit.
(Note: Remember to write down your Username and Password for future reference. This login will be used to
access post class resources for current and future classes.)
d) The student login page will display. Enter the Username and Password you created in your
new student profile and click Login.
e) Your online learning resources will be added to your Catalog.

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.

ii Microsoft® Office Excel® 2007 - VBA


CONTENTS
MICROSOFT® OFFICE EXCEL® 2007-
VBA

LESSON 1 - DEVELOPING MACROS


A. Create a Macro with the Macro Recorder . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Visual Basic for Applications (VBA). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Macro Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
The Macro Recorder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Personal Macro Workbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
B. Edit a Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Visual Basic Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
The Modules Folder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
VBA Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
C. Debug a Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
The Debugging Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Debugging Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
D. Customize the Quick Access Toolbar and Hotkeys . . . . . . . . . . . . . . . . . . . 25
E. Work with Macro Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Digital Certificates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Digital Signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Macro Security Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

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

iv Microsoft® Office Excel® 2007 - VBA


CONTENTS
E. Generate a Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
The Columns Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
The AutoFit Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
The Address Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
The Call Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
The Font Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
The End Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

LESSON 3 - CREATING AN INTERACTIVE WORKSHEET


A. Determine the Dialog Box Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Message Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Input Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
B. Capture User Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
The InputBox Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
The MsgBox Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
The Code Continuation Character . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
The vbCrLf Character . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Decision Structures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
The Select Case Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
The If Then Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

LESSON 4 - WORKING WITH MULTIPLE WORKSHEETS


A. Insert, Copy, and Delete Worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
The Add Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
The Copy Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
The Delete Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
B. Rename Worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
The DateSerial Function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
The Format Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
C. Modify the Order of Worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
The Move Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

Contents v
CONTENTS
D. Print Worksheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
The PrintPreview Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
The PrintOut Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

LESSON 5 - PERFORMING CALCULATIONS


A. Create User-Defined Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
User-Defined Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Types of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
The Else Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
B. Automate SUM Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Declared Range Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
The Set Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Range Object Cell Addressing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
The Rows Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
The Formula Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
The Columns Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Address Property Cell Reference Settings . . . . . . . . . . . . . . . . . . . . . . . . . 148

LESSON LABS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157


SOLUTIONS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
GLOSSARY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175

vi Microsoft® Office Excel® 2007 - VBA


INTRODUCTION

ABOUT THIS COURSE


In the previous Excel courses, you used Excel to simplify business tasks, including the creation
of spreadsheets, graphs, charts, and formulas that were difficult to create and nearly impossible
to maintain using pencil and paper. You now want to simplify your work in the Excel environ-
ment by automating many of the repetitive tasks that are part of the spreadsheet development.
In this course, you will apply the Visual Basic for Applications (VBA) programming language
to simplify many of the tasks that you can perform using various tools and functions in Excel
2007.
Creating similar spreadsheets with different data from scratch, each and every day, for every
report that your company processes would add up to an endless number of repetitive steps.
Applying VBA to your spreadsheets automates repetitive tasks and deploys custom company-
wide functions to increase your productivity, and allows you to easily manage creating large
quantities of spreadsheets.

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.

viii Microsoft® Office Excel® 2007 - VBA


INTRODUCTION
Course Requirements
Hardware
For this course, you need one computer for each student and one for the instructor. Each com-
puter will need the following minimum hardware configuration:
• 500 MHz processor or higher
• 512 MB of RAM
• 20 GB of free hard disk space
• CD-ROM drive
• Mouse or other pointing device
• 1024 x 768 resolution video card and monitor
• Network cards and cabling for local network access
• Internet access
• Printer (optional)
• Projection system to display the instructor’s computer screen

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.

Before Every Class


1. Log on to the computer as the Administrator user.
2. Delete any existing data files from the My Documents folder.
3. Extract a fresh copy of the course data files from the CD-ROM provided with the course
manual.

List of Additional Files


Printed with each activity is a list of files students open to complete that activity. Many activi-
ties also require additional files that students do not open, but are needed to support the file(s)
students are working with. These supporting files are included with the student data files on the
course CD-ROM or data disk. Do not delete these files.

x Microsoft® Office Excel® 2007 - VBA


LESSON 1

LESSON 1 Lesson Time


1 hour(s), 50 minutes

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.

Lesson 1: Developing Macros 1


LESSON 1
Introduction
While working with Excel spreadsheets, you may have tasks that you frequently perform. Mac-
ros can be developed to automate these repetitive tasks. In this lesson, you will create, edit,
and debug a macro, and provide shortcuts for users to run macros.
Macros reduce multistep tasks to a button-click, a menu option, or a combination of key-
strokes. They can automate anything you can do in Excel and even enable you to do things
you might not have known were possible. Macros help save time and expand the capabilities
of Excel.

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.

Visual Basic for Applications (VBA)


Visual Basic for Applications (VBA) is the programming language that is used to create macros
in Microsoft Office applications. When you record a macro, Excel automatically translates the
keystrokes and commands into VBA code language and creates and stores the macro.

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.

2 Microsoft® Office Excel® 2007 - VBA


LESSON 1
Macros
Definition:
A macro is a task automation tool that executes a set of commands to automate fre-
quently repeated steps. Each macro is uniquely identified by a macro name. You can
use the macro recorder to record a sequence of actions, and then perform these tasks
by using the macro name or a simple command assigned to the macro. The commands
in the recorded macro are converted into programming code that can be edited if
required.

Example:

Macro Options
The Macro dialog box provides you with various options to work with a macro.

Figure 1-1: The Macro dialog box.

Option Description
Run Executes the macro.
Step Into Allows you to start the VBA Editor.
Edit Allows you to make changes to the macro.

Lesson 1: Developing Macros 3


LESSON 1
Option Description
Create Displays the Microsoft Visual Basic Editor.
Delete Allows you to delete a macro.
Options Allows you to assign a shortcut key to a macro.

The Macro Recorder


The Macro Recorder is an Excel tool that you can use to create a macro. It translates the
manual actions you perform in a workbook into a series of VBA commands that are saved in a
macro.

Figure 1-2: Recording action with a macro recorder.

Macro Naming Conventions


There are certain rules to follow when you create macro names:
• The name must begin with a letter.
• The name must not contain spaces.
• The name can contain letters, numbers, and the underscore character.

A macro-enabled Excel Workbook has .xlsm as the file extension.

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.

4 Microsoft® Office Excel® 2007 - VBA


LESSON 1
Personal Macro Workbook
A Macro Personal Workbook is a storage location in the Excel application where you can
create and save macros. Once created, the macros stored in the Personal Macro Workbook can
be used on any open Excel file.

Figure 1-3: Designating a macro to be stored in the Personal Macro workbook.

How to Create a Macro with the Macro Recorder


Procedure Reference: Add the Developer Tab to the Ribbon
To add the Developer tab to the Ribbon:
1. Click the Microsoft Office button, and then click Excel Options.
2. In the Excel Options dialog box, click Popular and check the Show Developer
tab in the Ribbon check box.
3. Click OK.

Procedure Reference: Create a Macro with the Macro Recorder


To create a macro with the Macro Recorder:
1. If necessary, on the Developer tab, click Record Macro to display the Record
Macro dialog box.
2. In the Macro Name text box, type a name for the new macro.
3. If necessary, in the Shortcut Key text box, type the keystroke you want to desig-
nate as a shortcut.
4. If necessary, from the Store macro in drop-down list, select the location where
you want to store the new macro.
5. If necessary, type a short description of the purpose of the new macro.
6. Click OK to start the Macro Recorder.
7. On the worksheet, perform the operations you want the macro to record.
8. On the Developer tab, click the Stop Recording button to end the recording.

Procedure Reference: Run a Macro


To run a macro:
1. In the Code group, click Macros to display the Macro dialog box.

Lesson 1: Developing Macros 5


LESSON 1
2. In the Macro dialog box, select the macro you want to run.
3. Click Run to run the macro.

ACTIVITY 1-1
Recording and Running Macros
Data Files:
• Record Macro.xlsx

Before You Begin:


1. Open the Excel application. In the Welcome to the 2007 Microsoft Office system dialog
box, click Next. Click I don’t want to use Microsoft Update and click Finish.
2. Display the Excel Options dialog box and check the Show Developer tab in the Ribbon
check box on the Popular tab.
3. On the Trust Center tab, click the Trust Center Settings button.
4. In the Trust Center dialog box, select the Macro Settings tab and select the Enable all
macros (not recommended; potentially dangerous code can run) option, and close the
Trust Center dialog box.
5. Close the Excel Options dialog box.
6. From the C:\084037Data\Developing Macros folder, open the Record Macro.xlsx file.

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.

What You Do How You Do It

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.

b. In the Macro name text box, type


font2TimesNewRoman

c. From the Store macro in drop-down list,


select Personal Macro Workbook.

d. In the Description text box, click and


type This macro changes the font for
the entire worksheet to Times New
Roman.

6 Microsoft® Office Excel® 2007 - VBA


LESSON 1
2. Record a macro that changes the font a. Click OK to start the Macro Recorder.
style for the entire worksheet to
Times New Roman.
b. On the worksheet, to the left of the Col-
umn A heading, click the Select All button
to select the entire worksheet.

c. On the Home tab, in the Font group, from


the Font drop-down list, scroll down and
select Times New Roman.

d. Select cell A1.

e. On the Developer tab, in the Code group,


click the Stop Recording button,
to end the recording.

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

c. Verify that Personal Macro Workbook is


selected in the Store macro in drop-down
list.

d. In the Description text box, click and


type This macro changes the font for
the entire worksheet to Courier.

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.

c. On the Home tab, in the Font group, from


the Font Selection drop-down list, scroll
up and select Courier.

d. Select cell A1 to deselect the worksheet.

e. On the Developer tab, in the Code group,


click Stop Recording to end the record-
ing.

Lesson 1: Developing Macros 7


LESSON 1
5. Run the font2TimesNewRoman macro a. In the Code group, click Macros to display
to change the worksheet back to the Macro dialog box.
Times New Roman.
b. In the Macro dialog box, in the Macro
name list box, select
PERSONAL.XLSB!font2TimesNewRoman.

c. Click Run to run the macro.

6. Run the font2Courier macro to a. In the Code group, click Macros.


change the worksheet to Courier.
b. In the Macro dialog box, verify that the
PERSONAL.XLSB!font2Courier macro is
selected.

c. Click Run to run the macro.

7. Save the file as My Record a. Choose File→Save As.


Macro.xlsm and then close the file.
b. If necessary, navigate to the C:\
084037Data\Developing Macros folder.

c. In the Save As dialog box, from the Save


as type drop-down list, select Excel
Macro-Enabled Workbook (*.xlsm).

d. In the File name text box, click and type


My Record Macro and click Save.

e. Close the file.

8 Microsoft® Office Excel® 2007 - VBA


LESSON 1
TOPIC B
Edit a Macro
You have recorded a basic macro that automates several steps that a user may perform in the
Excel environment. Many times a recorded macro will suit your needs, but sometimes you
may want to modify it. In this topic, you will edit an existing macro.
Imagine that you take the trouble to create a macro that performs a number of steps, including
modifying the font of a row to be red. Now imagine that you wanted to perform the same
steps, but format the same row to be blue. Instead of recording a new macro, you can modify
the existing macro. Editing a macro modifies an existing macro without the extra steps of
recording a new one.

Visual Basic Editor


Visual Basic Editor (VBE) is a part of the Excel application where you can create, edit, and
delete macro code. In addition to its own set of menus and toolbars, it consists of the follow-
ing parts.

Figure 1-4: The VBE environment.

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.

Lesson 1: Developing Macros 9


LESSON 1
Projects
A project is a VBE representation of a set of relationships that exist among the parts of an
open Excel workbook. Viewed in Project Explorer, projects are depicted in a hierarchic, tree
structure similar to the file and folder structures viewed in Windows Explorer.

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:

The Modules Folder


The Modules folder is the location in a project where macro code is stored. When opened, the
Modules folder displays at least one module.

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.

10 Microsoft® Office Excel® 2007 - VBA


LESSON 1
Example:

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.

Lesson 1: Developing Macros 11


LESSON 1
Example:

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:

How to Edit a Macro


Procedure Reference: Edit a Macro
To edit a macro:
1. On the Developer tab, click Visual Basic to open Visual Basic Editor.

12 Microsoft® Office Excel® 2007 - VBA


LESSON 1
2. If necessary, in the Project window, double-click the Modules folder to open it.
3. If necessary, double-click the module object you want to edit.
4. If necessary, in the Code editing window, from the Macro name list box, select
the name of the macro you want to display.
5. If necessary, scan the code block until you find its end, denoted with the code
End Sub.
6. Insert, modify, or delete code and commenting.
7. On the worksheet, run the edited macro.
8. Verify that the macro performed the intended tasks.
9. If necessary, edit the macro to correct any errors.

ACTIVITY 1-2
Editing a Macro
Data Files:
• Edit Macro.xlsm

Before You Begin:


From the C:\084037Data\Developing Macros folder, open the Edit Macro.xlsm file.

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.

Lesson 1: Developing Macros 13


LESSON 1
What You Do How You Do It

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().

b. If necessary, maximize the code block


until you find its end, denoted with the
code End Sub.

c. In the Microsoft Visual Basic Editor,


change the macro’s name to
“font2Verdana”.

d. In the commenting lines, change the word


Courier to Verdana.

e. In the Sub font2Verdana macro, below the


Cells.Select statement, delete With.

f. In the Sub font2Verdana macro, below


.Name = “Courier” delete the lines of
code from Strikethrough to End
With.

g. Move the font name assignment statement


so that it becomes part of the previous
line of code.

h. In the font name assignment statement,


replace Courier with Verdana.

If necessary, see the completed code block at


the end of this activity.

14 Microsoft® Office Excel® 2007 - VBA


LESSON 1
2. Test the edited macro. a. Choose File→Close and Return to
Microsoft Excel.

b. On the worksheet, run the font2Verdana


macro.

c. If the worksheet text does not change to


the Verdana font, open the Microsoft
Visual Basic Editor, modify your edits, and
retest.

See Code Sample 1.

d. Save the file as My Edit Macro.xlsm and


close it.

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.

Lesson 1: Developing Macros 15


LESSON 1
TOPIC C
Debug a Macro
You have modified a macro in the VBA editor. Sometimes, you may encounter instances where
your modifications prevent a macro from delivering the results that you expect. In this topic,
you will debug a macro that is not functioning as expected.
Humans make mistakes. Modifying a macro in the VBA editor introduces the possibility that
you may make an error that prevents your macro from delivering results that you expect.
Debugging a macro helps you quickly pinpoint the location and correct a problem within your
VBA code that is causing an unexpected result.

The Debugging Process


The debugging process is the means by which you can identify, locate, and fix errors in macro
code.
1. The application environment is set up so that both the macro code and the worksheet it
acts on can be viewed at the same time.
2. A backup is made of the data, so that it can be reloaded in case it’s destroyed by the
error.
3. Code containing the error is run.
4. Undesired results are evaluated to determine the problem.
5. If necessary, data is reset from the backup copy.
6. Code is executed line-by-line to observe when the error occurs.
7. When discovered, the error is fixed in the macro code and the data is reset.
8. The program is retested to make sure the error is successfully fixed.

16 Microsoft® Office Excel® 2007 - VBA


LESSON 1
Debugging Tools
Debugging tools are VBE tools that you can use to locate, examine, and fix mistakes in VBA
code. Their primary function is to either execute small portions of macro code or halt the
execution of code at a specific location during the debugging process.

Figure 1-5: Tools used in debugging a macro.

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.

How to Debug a Macro


Procedure Reference: Run a Macro from Visual Basic Editor
To run a macro from Visual Basic Editor:
1. If necessary, in the Project Explorer tool, select the module in which the macro
code is stored.
2. Above the Code editing window, from the Macro name drop-down list, select
the macro code you want to run.
3. If necessary, choose View→Toolbars→Debug to display the Debug toolbar.
4. On the Debug toolbar, click Run Sub/UserForm to run the macro.

Procedure Reference: Use the Step Into Tool


To use the Step Into tool to debug a macro:
1. On the Debug toolbar, click the Step Into tool to execute the next line of VBA
code.
2. If necessary, review the results of the executed line of code.

Procedure Reference: Use the Step Out Tool


To use the Step Out tool to debug a macro:
1. On the Debug toolbar, click the Step Out tool to execute the VBA code remain-
ing in the current code block.
2. If necessary, review the results of the executed line of code.

Procedure Reference: Use a Breakpoint to Debug a Macro


To use a breakpoint to debug a macro:
1. Place the insertion point in the line of code where you want the macro to stop.

Lesson 1: Developing Macros 17


LESSON 1
2. On the Debug toolbar, click Toggle Breakpoint to set the breakpoint.
3. If necessary, reset the worksheet data by copying and pasting it in from a backup
copy.
4. On the Debug toolbar, click Reset.
5. If necessary, above the Code editing window, from the Macro name drop-down
list, select the macro whose code you want to run.
6. On the Debug toolbar, click Run Sub/UserForm.
7. If necessary, review the results of the executed code.
8. Place the insertion point in the line of code containing the breakpoint.
9. On the Debug toolbar, click Toggle Breakpoint to remove the breakpoint.

Procedure Reference: Use the Step Over Tool


To use the Step Over tool to debug a macro:
1. On the Debug toolbar, click the Step Over tool to execute all the VBA codes in a
code block.
2. If necessary, review the results of the executed line of code.

ACTIVITY 1-3
Debugging Macros that Format a Report
Data Files:
• Debugging Example.xlsm

Before You Begin:


From the C:\084037Data\Developing Macros folder, open the Debugging Example.xlsm file.

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.

18 Microsoft® Office Excel® 2007 - VBA


LESSON 1
What You Do How You Do It

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.

c. On the Home tab, from the Insert drop-


down menu, choose Insert Sheet to
create a third worksheet to hold a copy of
the original data.

d. Right-click the new worksheet’s tab, and


then choose Rename to select the
worksheet tab’s text.

e. Type Backup as the name of the new


worksheet.

f. Select the Original Data worksheet.

g. Select all the cells in the worksheet.

h. Click Copy to copy the worksheet data to


the Clipboard.

i. Select the Backup worksheet.

j. Click Paste to paste the data from the


Original Data worksheet.

k. Select cell A1 to deselect the worksheet


cells.

Lesson 1: Developing Macros 19


LESSON 1
2. Modify the display of the worksheet a. Resize the application window so that it
and the VBE code editor to view how takes up the left half of the screen.
the worksheet is affected as you
debug the code.
b. On the Developer tab, choose Visual
Basic to display the Microsoft Visual Basic
Editor window.

c. Close the Project Browser and the Prop-


erties windows so that the code editing
window takes up the entire viewing area.

d. Resize the Microsoft Visual Basic Editor


window so that it takes up the right half
of the screen.

e. In the Microsoft Visual Basic Editor win-


dow, choose View→Toolbars→Debug to
display the Debug toolbar.

f. Position the Debug toolbar so that it


floats in the left window away from the
data in a blank area of the 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.

c. Display the Macro dialog box.

d. In the Macro dialog box, from the Macro


name list box, verify that the
CreateReport macro is selected and click
Run.

e. Click the Microsoft Visual Basic Editor


title bar to display the Debug toolbar.

f. On the Debug toolbar, click Run Sub/


UserForm.

g. Click the View Microsoft Excel button.

h. Select the End Product worksheet to view


the correctly formatted data.

i. Select the Original Data worksheet.

20 Microsoft® Office Excel® 2007 - VBA


LESSON 1
4. Reset the data in the Original Data a. Display the Backup worksheet.
worksheet.
b. Select all the cells in the worksheet.

c. On the Home tab, in the Clipboard sec-


tion, click Copy.

d. Display the Original Data worksheet.

e. Select all the cells in the worksheet.

f. Click Paste to paste the data into the


Original Data worksheet.

g. Select cell A1 to deselect the worksheet


cells.

5. Step through the CreateReport macro a. Click the Microsoft Visual Basic Editor
code until you find the first error. title bar.

b. In the Microsoft Visual Basic window,


verify that the CreateReport macro code
is selected.

c. On the Debug toolbar, click Step Into,


five times to execute the first five
lines of code.

d. Observe the rows that are selected in the


worksheet.

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

Lesson 1: Developing Macros 21


LESSON 1
7. Test the result of the edit. a. Place the insertion point within the yellow
highlighted code.

b. On the Debug toolbar, click Toggle


Breakpoint, to set a breakpoint at
the highlighted line.

c. On the Debug toolbar, click Reset,


to reset the macro.

d. On the Debug toolbar, click Run Sub/


UserForm to execute the previously
stepped through code up to the
breakpoint.

e. Click Step Into to execute the line of code


at the breakpoint.

f. Place the insertion point within the


breakpoint code.

g. On the Debug toolbar, click Toggle


Breakpoint to remove the breakpoint.

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.

b. Click Step Into four times.

9. Debug the error. a. Scroll down, and in the InsertTxt macro


code, place the insertion point in the
statement Range("A2").Select.

b. Click Toggle Breakpoint to set a


breakpoint.

c. In the range selection statement that


selects cell A10, modify the code so that
cell A1 is selected.

d. Click Reset to reset the InsertTxt macro.

e. Click Run Sub/UserForm to run the code


to the breakpoint.

22 Microsoft® Office Excel® 2007 - VBA


LESSON 1
10. Run through the rest of the code for a. Verify that the insertion point is within
the InsertTxt macro. the line of code containing the
breakpoint.

b. Click Toggle Breakpoint to remove the


breakpoint.

c. Click Step Out to execute the rest of the


code in the InsertTxt macro.

d. In the Microsoft Visual Basic Editor win-


dow, click the View Microsoft Excel
button.

Lesson 1: Developing Macros 23


LESSON 1
11. Cross-check your work by running the a. Select the Backup worksheet.
InsertRowsCols and InsertTxt macro
codes.
b. Verify that all the cells on the worksheet
are selected.

c. On the Home tab, choose Copy.

d. Select the Original Data worksheet.

e. Select all the cells on the worksheet.

f. Click Paste.

g. Click in the Microsoft Visual Basic Editor


title bar.

h. From the Visual Basic Procedure drop-


down list, select the CreateReport
macro.

i. On the Debug toolbar, click Reset.

j. Click Step Into two times.

k. In the InsertRowsCols macro, click Step


Over, to execute all the codes.

l. In the InsertTxt macro, click Step Over to


execute all the codes.

m. Choose File→Close and Return to


Microsoft Excel.

n. In the Microsoft Visual Basic message


box, click OK.

o. Save the file as My Debugging


Example.xlsm and close it.

24 Microsoft® Office Excel® 2007 - VBA


LESSON 1
TOPIC D
Customize the Quick Access Toolbar
and Hotkeys
You have created a macro. Now, you want to create shortcuts to quickly run the macros. In
this topic, you will create these shortcuts by customizing Excel’s Quick Access toolbar, and
assign hotkeys to the macros you have created.
If you are used to working with GUI software applications, then you are undoubtedly familiar
with common conventions such as buttons, menus, and keyboard shortcuts. Excel gives you
the opportunity to incorporate these conventions into your macro development. Customizing
the Excel Quick Access toolbar, or assigning hotkeys to macros provides a number of simple
choices for running macros.

How to Customize the Quick Access Toolbar and


Hotkeys
Procedure Reference: Customize the Quick Access Toolbar
To customize the Quick Access toolbar:
1. Display the Excel Options dialog box.
• Click the Microsoft Office button and then click Excel Options.
• Or, on the Quick Access toolbar, from the Customize Quick Access Toolbar
drop-down list, select More Commands.
2. In the Excel Options dialog box, click the Customize category.
3. From the Choose commands from drop-down list, select Macros to add a macro
on the Quick Access toolbar.
4. In the Macro name list box, select the desired command and click Add.
5. To restore the default Quick Access Toolbar options, click Reset.
6. To put the Quick Access toolbar below the Ribbon, check the Show Quick
Access Editor Toolbar below the Ribbon check box.
7. Click OK to close the Excel Options dialog box.

Procedure Reference: Add a Group or an Option to the Quick Access Toolbar


To add a group or an option to the Quick Access toolbar:
1. Select the tab on the Ribbon that has the desired group, and right-click the name
of the group.
2. Click Add to Quick Access Toolbar.

Procedure Reference: Assign a Hotkey to a Macro


To assign a hotkey to a macro:
1. On the Developer tab, click Macros.

Lesson 1: Developing Macros 25


LESSON 1
2. In the Macro name list box, click the macro you want to assign a hotkey.
3. Click Options.
4. In the Macro Options dialog box, in the Shortcut key text box, type any lower-
case letter or uppercase letter that you want to use and click OK.

ACTIVITY 1-4
Customizing the Quick Access Toolbar and Hotkeys
Data Files:
• Hotkey.xlsm

Before You Begin:


From the C:\084037Data\Developing Macros folder, open the Hotkey.xlsm file.
Maximize the Excel application.

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.

What You Do How You Do It

1. Customize the Quick Access toolbar a. Click the Microsoft Office button and
using the Excel Options dialog box. then click Excel Options.

b. In the Excel Options dialog box, click the


Customize category.

c. From the Choose commands from drop-


down list, select Macros.

d. From the Macro name list box, select


font2Arial and click Add.

e. In the Excel Options dialog box, click OK.

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.

c. On the Home tab, right-click Cells.

d. Click Add to Quick Access Toolbar.

26 Microsoft® Office Excel® 2007 - VBA


LESSON 1
3. Assign a hotkey to a macro. a. On the Developer tab, choose Macros.

b. In the Macro name list box, verify that


the font2Arial macro is selected and click
Options.

c. In the Macro Options dialog box, in the


Shortcut key text box, type m and click
OK.

d. Close the Macro dialog box.

e. On the keyboard, hold down Ctrl and


press m.

f. Observe that the macro is executed.

g. Save the file as My Hotkey.xlsm and close


it.

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.

Lesson 1: Developing Macros 27


LESSON 1
Example:

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:

Macro Security Settings


In order to protect macros, you can set security levels to them. You can view or change the
macro security level in the Macro Settings category of the Trust Center dialog box.

28 Microsoft® Office Excel® 2007 - VBA


LESSON 1
Option Description
Disable All Macros Without Notification Disables all macros in the workbook and their
security alerts. Documents stored in a trusted loca-
tion containing macros are allowed to run.
Disable All Macros With Notification Disables all macros but not their security alerts.
This is the default setting. This setting allows you
to choose which macros to run.
Disable All Macros Except Digitally Signed Disables all macros except those that are digitally
Macros signed by a trusted publisher.
Enable all Macros (Not Recommended, Poten- Enables all macros in the workbook to run. This
tially Dangerous Code Can Run) lowers the security of the computer, making it vul-
nerable to malicious code. This option is not
recommended as it may allow potentially danger-
ous code in the macro to run.
Trust Access To The VBA Project Object Model Enables macros to access the core Microsoft Visual
Basic objects, methods, and properties. This option
is for developers only, as it poses a security haz-
ard.

How to Work with Macro Security


Procedure Reference: Add a Digital Signature
To add a digital signature:
1. On the Insert tab, from the Signature Line drop-down menu, choose Microsoft
Office Signature Line.
2. In the Microsoft Office Excel dialog box, click OK.
3. In the Signature Setup dialog box, type the necessary information.
a. In the Suggested signer name text box, type a name.
b. In the Suggested signer’s title name text box, type a title.
c. In the Suggested signer’s e-mail adddress text box, type an email address.
4. Click OK.
5. In the document, double-click the signature line where your signature is requested.
6. In the Microsoft Office Excel dialog box, click OK.
7. In the Get a Digital Id dialog box, select Create your own digital ID and click
OK.
8. In the Create a Digital ID dialog box, in the Name text box, type a name.
9. In the E-mail address text box, type an email address.
10. In the Organization text box, type the name of an organization.
11. In the Location text box, type the desired location.
12. Click Create.
13. In the Sign dialog box, type the name of the signer and click Sign.

Lesson 1: Developing Macros 29


LESSON 1
14. In the Signature Confirmation message box, click OK.
15. In the Signatures pane, view the digital signature and the certificate icons on the
Microsoft Office Status bar.

Procedure Reference: Adjust Macro Settings


To adjust macro settings:
1. On the Developer tab, click Macro Security.
2. In the Trust Center dialog box, select the level of macro security you desire.
3. Click OK to save the macro security settings.

ACTIVITY 1-5
Setting Macro Security
Data Files:
• Macro Security.xlsx

Before You Begin:


From the C:\084037Data\Developing Macros folder, open the Macro Security.xlsx file.

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.

30 Microsoft® Office Excel® 2007 - VBA


LESSON 1
What You Do How You Do It

1. Add a digital signature. a. On the Insert tab, from the Signature


Line drop-down menu, choose Microsoft
Office Signature Line.

b. In the Microsoft Office Excel message


box, click OK.

c. In the Signature Setup dialog box, in the


Suggested signer (for example, John
Doe) text box, type Pat Smith

d. In the Suggested signer’s title (for


example, Manager) text box, type Man-
ager

e. In the Suggested signer’s e-mail address


text box, type [email protected]

f. Click OK.

g. Double-click in the Signature text box.

h. In the Microsoft Office Excel message


box, click OK.

i. In the Get a Digital ID dialog box, select


Create your own digital ID and click OK.

j. In the Create a Digital ID dialog box, in


the Name text box, double-click and type
Pat Smith

k. In the E-mail address text box, click and


type [email protected]

l. In the Organization text box, click and


type OGC

m. In the Location text box, click and type


NY

n. Click Create.

o. In the Sign dialog box, in the Signature


text box, type Pat Smith

p. Click Sign.

Lesson 1: Developing Macros 31


LESSON 1
q. In the Signature Confirmation message
box, click OK.

r. Observe that the signature is displayed in


the worksheet.

s. Close the file.

2. Set macro security. a. On the Developer tab, choose Macro


Security.

b. In the Trust Center dialog box, select the


Disable all macros with notification
option.

c. Click OK.

d. Close the Signatures panel.

3. What must be done to an electronic file in order to create a digital signature?


a) Disable all macros without notification.
b) Add revision tracking.
c) Disable all macros with notification.
d) Add a digital certificate.

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?

32 Microsoft® Office Excel® 2007 - VBA


LESSON 2

LESSON 2 Lesson Time


1 hour(s), 35 minutes

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.

Lesson 2: Formatting Worksheets Using Macros 33


LESSON 2
Introduction
You have recorded macros as a simple way to create VBA code in an Excel worksheet. While
recorded macros are certainly simple to create, additional flexibility can be gained by entering
the code manually. In this lesson, you will create your own VBA code to automate the applica-
tion of several formatting properties to a worksheet.
There may be instances at your workplace where you find yourself repeatedly applying the
same kind of formatting to different documents. This becomes absolutely tedious at one point
and you realize that automating the formatting tasks will save you a lot of time. Applying
VBA reduces the number of steps required to repetitively apply formatting to a worksheet.

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.

The Selection Object


Definition:
The Selection object is an Excel VBA object that represents a currently selected part of
the worksheet, such as a cell, column, or range. It is often used one line below macro
code in a statement that has used the Select method to select a worksheet part.
When used this way, you first need to enter the Selection command, followed by
an attached property or method.

34 Microsoft® Office Excel® 2007 - VBA


LESSON 2
Example:

Analogy:
In many respects, the Selection object functions like the pronoun it—you can use
it to refer to different previously selected objects.

The ActiveSheet Object


Definition:
The ActiveSheet is an Excel VBA object that represents the currently active worksheet
in the workbook. Like the Selection object, the ActiveSheet object can be used
in different contexts, but it refers only to the currently selected worksheet. By this
arrangement, you need to first enter the ActiveSheet command, followed by an
attached property or method.

Example:

Lesson 2: Formatting Worksheets Using Macros 35


LESSON 2
The Name Property
Definition:
The Name property is an Excel VBA property that contains text data representing the
name of the object using it. Using this property, you can change the name of a work-
book component or enter it in a worksheet cell. The Name property is invoked when
the Name command is attached with a period to an object name.

Example:

The Value Property


Definition:
The Value property is a VBA property that represents the data stored in an object, such
as a worksheet cell. Using this property, you can perform tasks such as assigning data
into or retrieving it from a cell for processing. The Value property is invoked when
the Value command is attached with a period to the object name.

Example:

36 Microsoft® Office Excel® 2007 - VBA


LESSON 2
Concatenation
Definition:
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. Using concatenation,
you can assemble text to be entered as a single data value into a worksheet cell.

Example:

How to Insert Text


Procedure Reference: Insert Text Headers with a Macro
To insert text headers with a macro:
1. Start the Macro Recorder to record a named macro.
2. On the worksheet, insert the text headers at the desired locations.
3. Stop the macro recording.

Procedure Reference: Insert a Worksheet Name Automatically


To insert a worksheet name automatically:
1. In the Visual Basic Editor, in the code that assigns text to the cell where the
worksheet’s name is to be located, erase the string data.
2. In its place, type ActiveSheet.Name.

Lesson 2: Formatting Worksheets Using Macros 37


LESSON 2
3. If desired, concatenate text to the newly entered code.

'Inserting the worksheet name into a cell:

'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

Before You Begin:


1. From the C:\084037Data\Formatting Worksheets folder, open the Balance Sheet.xlsx file.
2. Change the security settings to enable all macros.

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.

What You Do How You Do It

1. Start the Macro Recorder to record a a. Select the Conservative worksheet.


macro named InsTxt.
b. On the Developer tab, in the Code group,
click Record Macro to display the Record
Macro dialog box.

c. In the Macro name text box, type InsTxt

d. From the Store macro in drop-down list,


select This Workbook.

e. Click OK to start the Macro Recorder.

38 Microsoft® Office Excel® 2007 - VBA


LESSON 2
2. Insert the report title and headers for a. In cell A1, type OGC Investment Advisors
the stock price data on the
worksheet.
b. In cell A2, type Stock Prices

c. In cell B4, type Conservative

d. In cell B6, type Symbol: and press Tab.

e. In cell C6, type Open: and press Tab.

f. In cell D6, type Close: and press Tab.

g. In cell E6, type Net Chg: and then press


Enter.

h. On the status bar, click the Stop Record-


ing button.

Lesson 2: Formatting Worksheets Using Macros 39


LESSON 2
3. Edit the InsTxt macro code so that a. In the Code group, click Macros.
the worksheet’s name is assigned to
a cell.
b. In the Macro dialog box, select the InsTxt
macro and click Edit.

c. If necessary, maximize the Visual Basic


Editor and position the Debug toolbar in
the blank area.

d. In the InsTxt macro code, scroll down, and


under the code line that selects cell B4, in
the ActiveCell.FormulaR1C1 state-
ment, delete "Conservative".

e. Type ActiveSheet.Name and press the


Spacebar.

f. Type & to enter the ampersand concat-


enation character and then press the
Spacebar.

g. Type " Portfolio"

See Code Sample 1.

h. Close the Visual Basic Editor.

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.

b. In the Code group, click Macros.

c. Select InsTxt and click Run to run the


InsTxt macro on the Balanced worksheet.

d. Run the InsTxt macro on the Conservative


worksheet.

e. Run the InsTxt macro on the Aggressive


worksheet.

40 Microsoft® Office Excel® 2007 - VBA


LESSON 2
5. True or False? In cell B4, the name of each worksheet was inserted along with the text
″Portfolio″.
True
False

6. Save the worksheet. a. Click the Microsoft Office button and


choose Save As.

b. In the Save As dialog box, from the Save


as type drop-down list, select Excel
Macro-Enabled Workbook (*.xlsm).

c. In the File name text box, click and type


My Balance Sheet and click Save.

DISCOVERY ACTIVITY 2-2


Understanding How to Insert Report Text
Scenario:
You are now ready to review your knowledge of how to insert report text.

1. Which is a property of the Workbook object?


a) ActiveSheet
b) Name
c) Value
d) Selection

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

Lesson 2: Formatting Worksheets Using Macros 41


LESSON 2
TOPIC B
Format Text
You know how to format text manually. Using VBA, the text that you want to modify can be
formatted automatically by applying a macro. In this topic, you will create macros for format-
ting text in a worksheet.
Imagine that you are creating a worksheet that consistently formats its components using sev-
eral text styles. Getting the text of a worksheet to look the way you want it to can involve
quite a few steps. Applying VBA reduces the number of steps required to repeatedly format
text.

How to Format Text


Procedure Reference: Format Text with a Macro
To automatically format text with a macro:
1. Start the Macro Recorder to record a named macro.
2. On the worksheet, format the text at the desired locations.
3. Stop the macro recording.

ACTIVITY 2-3
Formatting Report Text
Data Files:
• My Balance Sheet.xlsm

Before You Begin:


The My Balance Sheet.xlsm file is open.

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.

42 Microsoft® Office Excel® 2007 - VBA


LESSON 2
What You Do How You Do It

1. Start the Macro Recorder to record a a. Select the Conservative worksheet.


macro named FmtTxt.
b. Display the Record Macro dialog box.

c. In the Macro name text box, type FmtTxt

d. Verify that in the Store macro in drop-


down list, This Workbook is selected.

e. Click OK to start the Macro Recorder.

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.

b. In the Font group, click the Bold button


to boldface the title.

c. Format cell A2 with a font size of 14 and


bold it.

d. Format cell B4 with a font size of 14 and


bold it.

e. Format the range B6:E6 with a font size of


12 and bold it.

f. Select the columns C through E.

g. In the Number group, from the Number


Format drop-down list, select Currency.

h. Select the columns B through E.

i. In the Cells group, from the Format drop-


down list, select AutoFit Column Width.

j. Click in cell A1 to deselect the selection.

k. On the status bar, click the Stop Record-


ing button.

Lesson 2: Formatting Worksheets Using Macros 43


LESSON 2
3. Run the FmtTxt macro on the other a. Select the Balanced worksheet.
worksheets.
b. On the Developer tab, click Macros, and
in the Macro dialog box, click Run to run
the FmtTxt macro.

c. Run the FmtTxt macro on the Aggressive


worksheet.

d. Save the file and close it.

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.

The Range Object


Definition:
The Range object is an Excel VBA object that represents a range of cells on a
worksheet. It consists of the Range object name, followed by a pair of parentheses.
Within the parentheses are range coordinates, contained in quotation marks.

44 Microsoft® Office Excel® 2007 - VBA


LESSON 2
Example:

The Select Method


Definition:
The Select method is an Excel VBA method used to select part of a worksheet. The
Select command, used to invoke this method, is attached with a period at the end of
an object name, representing the workbook component being selected.

Example:

The CurrentRegion Property


Definition:
The CurrentRegion property is a property of the ActiveCell object. It describes the
largest possible range of cells with data and the currently active cell. The
CurrentRegion command word, used to invoke this property, is attached with a
period at the end of the ActiveCell object name.

Lesson 2: Formatting Worksheets Using Macros 45


LESSON 2
Example:

How to Sort Data


Procedure Reference: Script a Macro to Sort Ranges
To script a macro to sort on ranges of indeterminate length:
1. Select a range containing the intended sort column.
2. Set the Macro Recorder to record a macro.
3. On the Home tab, in the Editing group, from the Sort & Filter drop-down menu,
select Custom Sort.
4. In the Sort dialog box, set the characteristics of the sort.
5. Click OK to perform the sort.
6. On the status bar, in the Code group, click the Stop Recording button.
7. In Visual Basic Editor, in the recorded sort macro, at the beginning of the code
block generated by the Macro Recorder, enter the code necessary to select a cell
within the range of cells to be sorted.
8. Press Enter.
9. Enter the code necessary to select the entire range in which the cell is located.

' Entering code to sort a range having


' an unknown number of rows:

' Selecting a cell in the sort range:

Range("CellAddr").Select

' Selecting the entire range:

ActiveCell.CurrentRegion.Select

Selection.Sort Key1:=Range("CellAddr"), _
Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, _
Orientation:=xlTopToBottom

46 Microsoft® Office Excel® 2007 - VBA


LESSON 2
ACTIVITY 2-4
Sorting Ranges
Data Files:
• Raw Data.xlsm

Before You Begin:


From the C:\084037Data\Formatting Worksheets folder, open the Raw Data.xlsm file.

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.

What You Do How You Do It

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.

Lesson 2: Formatting Worksheets Using Macros 47


LESSON 2
2. Edit the macro so that it selects a a. In Visual Basic Editor, in the SortLastCol
range of unknown row length. macro, at the beginning of the code
block, type Range("A1").Select to
select cell A1 within the range of cells to
be sorted.

b. Press Enter.

c. Type
ActiveCell.CurrentRegion.Select
to select the entire range in which the
cell is located.

See Code Sample 1.

d. Close the Visual Basic Editor.

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.

b. Run the SortLastCol macro to sort the


data.

Verify that This Workbook is selected to display


the macro.

c. Select the Aggressive worksheet.

d. Run the SortLastCol macro to sort the


data.

e. Run the SortLastCol macro on the Conser-


vative worksheet.

48 Microsoft® Office Excel® 2007 - VBA


LESSON 2
4. True or False? The macro successfully sorted the different stock tables having differ-
ent numbers of rows.
True
False

5. Save the file and then close it. a. Save the file as My Raw Data.xlsm

b. In the File window, click Close.

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:

Lesson 2: Formatting Worksheets Using Macros 49


LESSON 2
Variables
Definition:
Variables are named locations that you can create and use in a macro to temporarily
store data when the macro runs. Once stored in a variable, a data value continues to
exist in the variable until a new data value “writes over” the old one in subsequent
code, or the macro that created the variable stops running. When using variables, a
macro module must first be defined with the Option Explicit declaration at the
beginning of the list of macros; each macro in the list must then declare the variables
it uses with the Dim As command, which defines the data type allowed, before they
can be used.

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.

Variable Naming Rules


Variable naming rules prescribe the kinds of names you can give to variables:
• The first character of a variable name must be a letter.
• No spaces, periods, exclamation marks, ampersands, “at” symbols (@), dollar signs, or
pound signs are allowed.
• The name can’t be longer than 255 characters.
• The name can’t be the same as VBA’s language components.
• Two variables can’t share the same name.
Examples of correctly named variables:
• TotalAmount

50 Microsoft® Office Excel® 2007 - VBA


LESSON 2
• Revenue1999
• x
Examples of incorrectly named variables:
• 1999Revenue
• Mary Smith
• House.Mary
• ActiveSheet

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:

The Assignment Operator


The assignment operator (=) is a VBA language component used to manage the flow of data
into and out of variables. It evaluates the combination of data, variables, and symbols on its
right side to a single data value, which is then stored in the variable, object, or property on its
left.

Arithmetic Operators
Arithmetic operators are similar to the operators you use in calculating mathematical expres-
sions.

Lesson 2: Formatting Worksheets Using Macros 51


LESSON 2
Name Purpose
* (Multiplication) Multiplies two numbers together.
/ (Division) Divides the top number by the bottom number.
+ (Addition) Adds two numbers together.
- (Subtraction) Subtracts the second number from the first.
^ (Exponentiation) Raises the first number to the power of the second.

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.

52 Microsoft® Office Excel® 2007 - VBA


LESSON 2
The For Next Loop
Definition:
The For Next loop is a code group that repeats the execution of a series of VBA com-
mands. Consisting of the For command, which marks the beginning of the loop, the
Next command, which marks the end of the loop, and a criterion placed just after
For that evaluates an incrementing integer variable called a counter variable, the
For Next loop repeats the lines of VBA code placed within the loop until the size of
the counter variable is larger than an allowed value.

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:

Lesson 2: Formatting Worksheets Using Macros 53


LESSON 2
The Worksheets Collection Object
Definition:
The Worksheets collection object is an Excel VBA object that manages the collection
of worksheets in a workbook. Using it, you can create macros that can perform repeti-
tive tasks, such as entering and formatting report headers, without repetitively entering
code related to each worksheet.
When used, the Worksheets command, followed by a pair of parentheses holding a
numeric expression that evaluates to an integer, causes the Worksheets
collection object to refer to the worksheet whose position in the worksheet list is
the same as the numeric expression; the name of the worksheet can also be used.

Example:

The Count Property


Definition:
The Count property is a property of the Worksheets collection object. It con-
tains an integer whose size is the same as the number of worksheets in the currently
active workbook.
When used, the Count command is attached with a period to the end of the
Worksheets collection object reference.

54 Microsoft® Office Excel® 2007 - VBA


LESSON 2
Example:

The Offset Property


Definition:
The Offset property is a property of the ActiveCell object used to measure a dis-
tance from the currently active cell. When used, the Offset command, followed by a
pair of parentheses containing a comma-separated pair of integer values that determine
a distance, in cells, from the active cell, is attached with a period to the ActiveCell
object.

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.

Lesson 2: Formatting Worksheets Using Macros 55


LESSON 2
The Copy Method
Definition:
The Copy method is a method of the ActiveSheet object. Using it, you can copy
currently selected worksheet data to the Excel Clipboard. When used, the Copy com-
mand is attached with a period to the ActiveSheet object.

Example:

The Paste Method


Definition:
The Paste method is a method of the ActiveSheet object. Using it, you can paste
worksheet data placed on the Excel Clipboard by the Copy method. When used, the
Paste command is attached with a period to the ActiveSheet object.

Example:
A data range on the Clipboard is pasted to the active worksheet.

56 Microsoft® Office Excel® 2007 - VBA


LESSON 2

How to Duplicate Data


Procedure Reference: Declare a Variable
To declare a variable:
1. Type Option Explicit and then press Enter.
2. Type Dim followed by a space.
3. Type the name of the variable and then a space.
4. Type As and then a space.
5. Enter the variable’s data type.

Procedure Reference: Set Up a For Next Loop


To set up a For Next loop in a VBA-scripted macro:

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

' Space for repeating code here...

Next VariableName

Lesson 2: Formatting Worksheets Using Macros 57


LESSON 2
6. In the For statement, after the counter variable name, type the equals sign and
then a space.
7. Enter the starting value for the counter variable and then a space.
8. Type To and then a space.
9. Enter the ending value for the counter variable.

' Num1 and Num2 represent numeric values:

For x = Num1 To Num2

Procedure Reference: Duplicate Data


To code a macro to duplicate data from one worksheet to another:
1. If necessary, select a cell in the range to be copied.
2. Select the current region of the active cell.
3. Invoke the Selection object’s Copy method to copy the current region.
4. Select a worksheet where the range will be copied to.
5. If necessary, select a cell where the range is to be pasted.
6. Invoke the ActiveSheet object’s Paste method.

Range("CellAddr").Select
ActiveCell.CurrentRegion.Select
Selection.Copy
Worksheets(Name of the worksheet).Select
Range("CellAddr").Select
ActiveSheet.Paste

Procedure Reference: Select a Cell by Offsetting the Active Cell


To select a cell by offsetting the active cell:
1. Use the Range object and its Select method to select the active cell.
2. In the next line, use the ActiveCell object’s Offset property, and the
Select method to select the new active cell.
a. Type ActiveCell.Offset().Select.
b. Within the parentheses of the Offset property, enter a numeric value to
offset the row reference.
c. Type a comma.
d. Enter a numeric value to offset the column reference.

' Selecting the original cell:

Range("CellAddr").Select

' Selecting the new active cell via the Offset property:

ActiveCell.Offset(num1, num2).Select

58 Microsoft® Office Excel® 2007 - VBA


LESSON 2
ACTIVITY 2-5
Duplicating Data
Data Files:
• All Portfolios.xlsm

Before You Begin:


From the C:\084037Data\Formatting Worksheets folder, open the All Portfolios.xlsm file.

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.

What You Do How You Do It

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.

c. In Visual Basic Editor, in the code editing


window, above the Sub DuplData state-
ment, type Option Explicit and then
press Enter.

d. In the DuplData macro, type Dim x As


Integer to declare x as the variable,
with integer as the data type and then
press Enter.

See Code Sample 1.

Code Sample 1
Option Explicit
____________________

Sub DuplData()

Dim x As Integer

End Sub

Lesson 2: Formatting Worksheets Using Macros 59


LESSON 2
2. Enter the code that marks the begin- a. Type For
ning and end of a For Next loop
structure.
Ignore the debugging warning messages.

b. Press Enter three times to provide blank


lines where repeating code will be
entered.

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.

b. In the Next statement, add a space and


type x after the word Next.

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 To followed by a space.

d. Type Worksheets.Count - 1 as the


ending value for the x counter variable
and press Enter.

60 Microsoft® Office Excel® 2007 - VBA


LESSON 2
5. Enter the code, within the For Next a. Type Worksheets(x).Select to select
loop, to select, copy, and paste the a worksheet with the counter variable and
data from any of the stock price press Enter.
tables on the first three sheets to the
fourth All Portfolios sheet.
b. Type Range("A1").Select to select
cell A1 in each selected worksheet and
press Enter.

c. Type
ActiveCell.CurrentRegion.Select
to select the current region of the active
cell and press Enter.

d. Type Selection.Copy to copy the cur-


rent region and press Enter.

e. Type Worksheets("All
Portfolios").Select to select the All
Portfolios worksheet, where the range
will be pasted and press Enter.

f. In the next line, type


ActiveSheet.Paste to paste the data.

See Code Sample 2.

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

Lesson 2: Formatting Worksheets Using Macros 61


LESSON 2
6. Enter the code necessary to select a. In the blank line above the
cell A1 and then its offset. ActiveSheet.Paste statement, type
Range("A1").Select and then press
Enter.

b. Type ActiveCell.Offset().Select
and then press Enter.

c. Within the parentheses of the Offset


property, type x * 10 as the numeric
value to offset the row reference and
then type , (comma).

d. Press the Spacebar and then type 0 as the


numeric value to offset the column refer-
ence.

See Code Sample 3.

e. Close the Visual Basic Editor.

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.

62 Microsoft® Office Excel® 2007 - VBA


LESSON 2
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.

9. Save the file and then close it. a. Save the file as All Portfolios Final.xlsm

b. Close the file.

DISCOVERY ACTIVITY 2-6


Reviewing How to Duplicate Data
Scenario:
You are now ready to review your knowledge of duplicating data.

1. Which is a variable naming rule?


a) The first character of the variable name must be a number.
b) There is not a character size limit.
c) Any sign can be used in the name.
d) The name can’t be the same as VBA’s language components.

2. Which is an example of a command that a Do Loop consists of?


a) Does
b) While
c) Where
d) Done

Lesson 2: Formatting Worksheets Using Macros 63


LESSON 2
TOPIC E
Generate a Report
You have applied the components that go into creating formatted reports, it’s time to draw
them all together. In this topic, you will generate a formatted report.
By creating a report-generating macro, you can transform the raw data in a multi-sheet work-
book into a series of finished reports by entering a single command.

The Columns Object


Definition:
The Columns object is an Excel VBA object that represents one or more columns on a
worksheet. Using it, you can perform tasks such as resetting the column width or for-
matting columns to display numeric data as percentages or currency. When used, the
Columns command is followed by a pair of parentheses. Within the parentheses is a
column range enclosed in quotation marks.

Example:

The AutoFit Method


Definition:
The AutoFit method is a method of the Columns object. Using it, you can change the
width of the column range indicated by the Columns object to fit the data contained
in the columns’ cells. When used, the AutoFit command is attached with a period to
the Columns object reference.

64 Microsoft® Office Excel® 2007 - VBA


LESSON 2
Example:

The Address Property


Definition:
The Address property is a property of the ActiveCell object. It represents a string
value describing the location of the currently active cell. When used, the Address
command is attached with a period to the ActiveCell object reference.

Example:

Lesson 2: Formatting Worksheets Using Macros 65


LESSON 2
The Call Command
Definition:
The Call command is an Excel VBA language component used to run a macro from
another macro. Using it, you can organize your macro code into several separate code
groups, and then call the macros from a “master” macro in an intended order to
accomplish a large, multiphase task. In this method, you need to first enter the Call
command, followed by the name of the macro being called.

Example:
A master macro calls a series of macros to perform specialized tasks that together for-
mat a report.

The Font Property


Definition:
The Font property is an Excel VBA property you can use to set how text will appear
on a worksheet. The Font property itself contains several properties, such as bold,
italic, and underline, that define text-related issues such as the font face, size, and pre-
sentation of text. When used, the Font command, followed by one or more of its
properties, is attached with a period to the object being formatted; a value setting prop-
erty is then designated with the equals sign assignment operator.

66 Microsoft® Office Excel® 2007 - VBA


LESSON 2
Example:

Using With End With to Assign Font Properties


When multiple font properties must be set, the With End With syntax is often used
to reduce the number of keystrokes.
' Setting Font properties without With End With:

Selection.Font.Name = "Arial"
Selection.Font.Size = 14
Selection.Font.ld = True

' Setting Font properties with With End With:

With Selection.Font

.Name = "Arial"
.Size = 14
.Bold = True

End With

The End Property


Definition:
The End property is an Excel VBA property often used with the Selection object.
Using it, you can locate the beginning or end of data being generated on a worksheet,
so that additional information that will become part of the data set can be attached to
the previously generated data. When used, the End command, followed by a pair of
parentheses, is attached with a period to the object; within the parentheses is placed
one of four built-in Excel Direction commands indicating the direction in which to
search.

Example:
The End property locates the bottom of the body of a report.

Lesson 2: Formatting Worksheets Using Macros 67


LESSON 2

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

How to Generate a Report


Procedure Reference: Create a Report Generator
To create a report-generating macro:
1. Create a For Next loop structure that cycles through the set of worksheets.
2. Within the loop, under the line of code that selects the worksheets, enter the code
necessary to format each worksheet selected by the loop iterations.
3. Enter the code necessary to copy data for duplication from each worksheet.
a. With the Range object and the Select method, select a cell in the range to
be copied.
b. With the ActiveCell object and the CurrentRegion method, select the
current region of the active cell.
c. With the ActiveSheet object and the Copy method, copy the selected
range to the Clipboard.
4. Assign the destination of the copied data.
a. With the Worksheets collection object and the Select method, select the
destination worksheet.
b. With the Range object and the Select method, select a cell far below the
bottom of the existing data.
c. With the Selection object, the End method, and the Select method,
select a cell at the bottom of the existing data.
d. With the ActiveCell object and the Offset property, select an active
cell below the existing data.
e. If necessary, with the ActiveCell object and the Value property, insert
header text.

68 Microsoft® Office Excel® 2007 - VBA


LESSON 2
f. If necessary, with the ActiveCell object and the Offset property, select
an active cell below the header.
g. With the ActiveSheet object and the Paste method, paste the copied
range.

' Selecting the destination worksheet:

Worksheets(SheetRef).Select

' Selecting a cell below the destination:

Range("CellAddr").Select

' Moving up to the bottom of the data:

Selection.End(xlUp).Select

' Selecting the cell with the Offset property:

ActiveCell.Offset(num1,num2).Select

' Inserting header text:

ActiveCell.Value = "Header Text"

' Selecting an active cell below the header:

ActiveCell.Offset(num1,num2).Select

' Pasting in the data:

ActiveSheet.Paste
5. If necessary, format the generated report.
a. Call a macro to find and format the unformatted areas.

Lesson 2: Formatting Worksheets Using Macros 69


LESSON 2
b. Reset the column widths.

Sub MacName()

Dim CV As Integer

For x = 1 To Worksheets.Count - 1

Worksheets(CV).Select

'Formatting Individual Pages

Call Macro 1
Call Macro 2
Call Macro 3
Call Macro 4

'Selecting Range for Duplication

Range("CellAddr").Select
Selection.CurrentRegion.Select
Selection.Copy

'Positioning and copying data onto target worksheet:

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

'Formatting target worksheet columns

Columns("ColRange").Select
Selection.Columns.AutoFit

End Sub

Procedure Reference: Code a Do Loop in a Macro


To code a Do loop in a macro:
1. Enter the code necessary to build the Do loop criterion.
a. Declare variables.
b. Assign initial values to the variables.
2. Enter the Do loop structure.
a. Type Do to indicate the start of the Do loop structure.
b. Press Enter at least twice to create space for the code that will be repeated
in the loop.

70 Microsoft® Office Excel® 2007 - VBA


LESSON 2
c. Type Loop to indicate the end of the Do loop structure.
d. Enter the While criterion indicator either after the Do or the Loop state-
ment.
e. Enter the While criterion evaluated by the Do loop.

Procedure Reference: Generate Code for Finding and Formatting Text


To generate code for finding and formatting text:
1. Create a new blank workbook.
2. On the worksheet, type two instances of the text you wish to find.
3. Start the Macro Recorder.
4. On the Home tab, in the Editing group, from the Find & Select drop-down
menu, select Find to display the Find and Replace dialog box.
5. Type the desired text to be found.
6. Click Find Next to find the first instance.
7. Click Find Next to find the second instance.
8. In the Code group or on the status bar, click Stop Recording.
9. In Visual Basic Editor, copy the generated code to the Clipboard.
10. Close the workbook without saving.

Procedure Reference: Find and Format Text


To find and format text on a generated report:
1. Create a named macro to find and format text.
a. In Visual Basic Editor, in a macro containing a Do loop whose While crite-
rion compares a string variable against the Address property of the active
cell, above the Do statement, paste the code generated by a recorded macro
to Find and Find Next the desired text.
b. Move the generated Find Next code inside the Do loop.
c. In the macro, between the variable declaration statement and the generated
Find code, enter the code to select a cell at the location where the first
instance of the desired text will appear.
d. In between the Do statement and the Find Next statement, enter the code
necessary to format the found text to the desired specifications.
2. Enter the code necessary to call the function in a report-generating macro.
a. In a report-generating macro, in a blank line after the end of the main
For Next loop, enter the code to call the find and format text macro.
b. Press Enter.
3. Generate a report.
a. Run a report-generating macro.
b. Select each worksheet in the report to review the formatted content.

Lesson 2: Formatting Worksheets Using Macros 71


LESSON 2
ACTIVITY 2-7
Creating a Report Generator
Data Files:
• Report Generator.xlsm

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.

72 Microsoft® Office Excel® 2007 - VBA


LESSON 2
What You Do How You Do It

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.

c. In the next line, type For x = 1 To


Worksheets.Count - 1, press Enter
twice and then type Next x to set up a
For Next loop structure that cycles
through all except the All Portfolios
worksheet.

d. Within the loop, in the line below the For


statement, type Worksheets(x)
.Select to select each worksheet as the
loop iterates, and then press Enter.

See Code Sample 1.

Code Sample 1
Sub GenRep()

Dim x As Integer

For x = 1 To Worksheets.Count - 1

Worksheets(x).Select

Next x

End Sub

Lesson 2: Formatting Worksheets Using Macros 73


LESSON 2
2. Enter the code necessary to format a. Under the statement that selects each
each worksheet selected by the loop worksheet, type Call SortLastCol to
iterations, within the loop, after the call SortLastCol and press Enter.
statement that selects the
Worksheet object.
b. Under the line of code you just entered,
type a macro call to InsColRow and press
Enter.

c. Under the line of code you just entered,


type a macro call to InsertTxt and press
Enter.

d. Under the line of code you just entered,


type a macro call to FmtTxt and press
Enter.

See Code Sample 2.

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

3. Enter the code necessary to copy a. Type Range("B6").Select and then


data from each worksheet for dupli- press Enter.
cation.
All the formatted stock table data ranges start
at B6.

b. Type
Selection.CurrentRegion.Select
to select the entire data range, and then
press Enter.

c. Type Selection.Copy to copy the


range, and then press Enter.

74 Microsoft® Office Excel® 2007 - VBA


LESSON 2
4. Assign the destination of the copied a. Type Worksheets("All ⇒
data. Portfolios").Select to select the
destination worksheet, and then press
Enter.

b. Type Range("B2000").Select and


then press Enter.

c. Type Selection.End(xlUp).Select
and then press Enter.

The preceding two steps select the destination


active cell from which a text header can be
offset.

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.

f. Type ActiveCell.Offset(2, 0)⇒


.Select to select an active cell offset in
which to paste the copied range, and then
press Enter.

g. Type ActiveSheet.Paste to paste the


copied range into its destination, and then
press Enter.

See Code Sample 3.

Code Sample 3
Sub GenRep()

Dim x As Integer

For x = 1 To Worksheets.Count - 1

Worksheets(x).Select

'Formatting Individual Portfolio Pages

Call SortLastCol
Call InsColRow
Call InsertTxt
Call FmtTxt

'Selecting Range for Duplication

Lesson 2: Formatting Worksheets Using Macros 75


LESSON 2
Range("B6").Select
Selection.CurrentRegion.Select
Selection.Copy

'Positioning and pasting data onto All Portfolios


Worksheets("All Portfolios").Select
Range("B2000").Select
Selection.End(xlUp).Select
ActiveCell.Offset(2, 0).Select
ActiveCell.Value = Worksheets(x).Name & " Portfolio"
ActiveCell.Offset(2, 0).Select
ActiveSheet.Paste

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.

6. Generate reports. a. Close the Visual Basic Editor.

b. Run the GenRep macro.

c. Select the Conservative worksheet to


view the generated report.

d. Select the Balanced worksheet to view


the generated report.

e. Select the Aggressive worksheet to view


the generated report.

f. Select the All Portfolios worksheet to


view the generated report.

g. Save the file as My Report


Generator.xlsm and close it.

7. True or False? The report generator generated the reports without error.
True
False

76 Microsoft® Office Excel® 2007 - VBA


LESSON 2
ACTIVITY 2-8
Finding and Formatting Text
Data Files:
• New Report.xlsm

Before You Begin:


From the C:\084037Data\Formatting Worksheets folder, open the New Report.xlsm file.

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.

What You Do How You Do It

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.

c. Press Enter twice.

d. Type FoundCellAddress = ⇒
ActiveCell.Address and press Enter.

Lesson 2: Formatting Worksheets Using Macros 77


LESSON 2
2. Enter the Do loop structure. a. Type Do to indicate the start of the Do
loop structure.

b. Press Enter six times.

c. Type Loop to indicate the end of the


Do loop structure, and then press the
Spacebar.

d. Type While to enter the criterion indica-


tor, and then press the Spacebar.

e. Type FoundCellAddress <> ⇒


ActiveCell.Address and then press
Enter to enter the criterion evaluated by
the Do loop.

See Code Sample 1.

Code Sample 1
Sub FindFormatPortHeaders()

Dim FoundCellAddress As String

FoundCellAddress = ActiveCell.Address

Do

Loop While FoundCellAddress <> ActiveCell.Address


End Sub

78 Microsoft® Office Excel® 2007 - VBA


LESSON 2
3. Generate a macro code to find two a. Switch to the Excel view.
instances of the desired text.
b. Create a new blank workbook.

c. In cell A1, type portfolio and press Enter.

d. In cell A2, type portfolio and press Enter.

e. Start recording a macro named temp

f. On the Home tab, in the Editing group,


from the Find & Select drop-down menu,
choose Find to display the Find and
Replace dialog box, and then type portfo-
lio

g. Click Find Next twice to find both


instances of the word “portfolio”.

h. In the Find and Replace dialog box, click


Close.

i. On the status bar, click the Stop Record-


ing button.

j. In Visual Basic Editor, in the temp macro


code, copy the generated code to the
Clipboard.

k. Close the Visual Basic Editor.

l. In the application window, close the new


workbook without saving.

Lesson 2: Formatting Worksheets Using Macros 79


LESSON 2
4. Create a macro to find and format a. In Visual Basic Editor, in the
text. FindFormatPortHeaders macro, paste the
code from the Clipboard above the Do
statement.

b. Move the Cells.FindNext statement


inside the Do loop.

Cell B4 holds the word “portfolio.”

c. Just under the variable declaration state-


ment, type Range("B4").Select to
select cell B4.

d. In between the Do statement and the


Cells.FindNext statement, enter the
code necessary to format the currently
active cell in 14pt, Arial, Bold.

See Code Sample 2.

e. In the GenRep macro, in the blank line


after the Next x statement, type
Call ⇒
FindFormatPortHeaders and press
Enter.

Code Sample 2
Sub FindFormatPortHeaders()

Dim FoundCellAddress As String

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

Loop While FoundCellAddress <> ActiveCell.Address

End Sub

80 Microsoft® Office Excel® 2007 - VBA


LESSON 2
5. Generate a report. a. Close the Visual Basic Editor.

b. On the worksheet, run the GenRep macro.

c. View the report on the Conservative


worksheet.

d. View the report on the Balanced


worksheet.

e. View the report on the Aggressive


worksheet.

f. View the report on the All Portfolios


worksheet.

g. Save the file as My New Report.xlsm and


close it.

6. True or False? The report was successfully generated with fully formatted text.
True
False

DISCOVERY ACTIVITY 2-9


Reviewing How to Find and Format Text
Scenario:
You are now ready to review your knowledge of finding and formatting text.

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: Formatting Worksheets Using Macros 81


LESSON 2
2. Which direction command is used to get the effect of pressing End+Right Arrow?
a) xlDown
b) xlToRight
c) xlUp
d) xlShift

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?

2. Which aspect of creating the report generator is the most difficult?

82 Microsoft® Office Excel® 2007 - VBA


LESSON 3

LESSON 3 Lesson Time


35 minutes

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.

Lesson 3: Creating an Interactive Worksheet 83


LESSON 3
Introduction
While the macros created in the previous lesson do not require information or decisions from
the user, VBA does provide ways to modify a worksheet by capturing the user input. In this
lesson, you will use a dialog box to capture the user-entered information that will be applied to
modify a worksheet.
Creating an interactive worksheet enables you to query users for information that modifies a
worksheet, so that they don’t have to make changes manually.

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.

Figure 3-1: Responses in a message box.

84 Microsoft® Office Excel® 2007 - VBA


LESSON 3
Button Description
OK Enables the user to acknowledge the message.
OK and Cancel Enables the user to proceed with or stop an action
described in the message.
Abort, Retry, and Ignore Enables the user to stop an action described in the
message, try to complete the action, or continue
irrespective of the action’s completion.
Yes and No Enables the user to agree or disagree with an
action suggested in the message.
Yes, No, and Cancel Enables the user to agree, disagree, or halt an
action suggested in the message.
Retry and Cancel Enables the user to try to complete an action
described in the message or stop the action’s
execution.

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:

How to Determine the Dialog Box Type


Procedure Reference: Determine the Dialog Box Type
To determine the dialog box type:
1. Determine the kind of information required.
• Message acknowledgement.
• Message acknowledgement or cancel command.

Lesson 3: Creating an Interactive Worksheet 85


LESSON 3
• Yes/no answer.
• Yes/no answer or cancel command.
• Command to retry or cancel.
• Command to abort, retry, or ignore.
• Entry of unique text or numeric data.
2. Determine the type of the dialog box.
• Use an input box, if the user input gathered must include unique text or
numeric data.
• Otherwise, use a message box.

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.

What You Do How You Do It

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

86 Microsoft® Office Excel® 2007 - VBA


LESSON 3
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
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.

The InputBox Function


Definition:
The InputBox function is a built-in VBA function that governs how an input box is
displayed. It consists of the InputBox command, followed by a pair of parentheses
that contains a comma-separated list of variables or data items that control the dis-
played message, the text in the title bar, and the default text that appears in the text
box.

Lesson 3: Creating an Interactive Worksheet 87


LESSON 3
When entered in code, the InputBox function is placed on the right side of a vari-
able assignment statement; when run, the data entered by the user in the input box is
assigned as string data to the variable. The variable can then be used in subsequent
code to direct the macro toward a chosen data processing goal.

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:

88 Microsoft® Office Excel® 2007 - VBA


LESSON 3
The MsgBox Function
Definition:
The MsgBox function is a built-in VBA function that governs how a message box is
displayed. It consists of the MsgBox command, followed by a pair of parentheses that
contains a comma-separated list of variables, data items, or constants that control the
message and the types of buttons displayed.
When entered in code, the MsgBox function is placed on the right side of a variable
assignment statement; when run, the data entered by the user is assigned as integer
data to the variable. The variable can then be used in subsequent code to direct the
macro toward a chosen data processing goal.

Example:

The Code Continuation Character


The code continuation character (_) enables the presentation of an unusually long VBA com-
mand as wrapped text in the code editing window. The character, consisting of a single
underscore keystroke, is placed at the right end of the code to be wrapped; usually, a space
precedes it.
When the Excel application interprets VBA code in a macro, it considers the Enter keystroke
as the end of a single VBA command except when it is preceded by the code continuation
character.

Lesson 3: Creating an Interactive Worksheet 89


LESSON 3

Figure 3-2: Code Continuation.

The vbCrLf Character


The vbCrLf character indicates where the text in a long input box or message box should be
broken and placed on the next line—the equivalent of pressing the Enter key in a word pro-
cessing application. Typically, the character is concatenated into a series of string data items
that have been set up in the intended format; the resulting single string formed by the concat-
enated segments containing the vbCrLf characters is then stored in a variable.

Figure 3-3: Using vbCrLf to format message text.

90 Microsoft® Office Excel® 2007 - VBA


LESSON 3
Decision Structures
Definition:
Decision structures are code groups that enable macro developers to cause a macro to
perform different actions based on a varying input, such as a response from a user. The
input is compared to values anticipated by the developer; if the input matches the
value or returns a true comparison, specified lines of code are run. If the input matches
no values or returns a false comparison, other specified lines of code (or no code at
all) are run. The two types of decision structures are Select Case and If Then.

Example:

The Select Case Structure


The Select Case structure enables the code in a macro to be executed or ignored based on a
condition, such as an entered response from a user. The Select Case decision structure
consists of the following parts.
• The Select Case statement, which begins the structure.
• The End Select statement, which ends the structure.
• At least two Case statements, which exist inside the structure.
• An optional Case Else statement, which exists after the last Case statement.
• At least one line of code under each Case or Case Else statement.
• A criterion variable, placed in the Select Case statement.
• And a comparative data value for each Case statement.
When executed, the Select Case structure compares the value contained in the criterion
variable, identified in the Select Case statement, against the comparative data values in
each Case statement until a match is found. Then, the code under the matching Case state-
ment is run; the code under the other Case (and Case Else) statements is ignored. If no
Case statements match, either the code within the optional Case Else statement is executed
or the code within the structure is ignored.

Lesson 3: Creating an Interactive Worksheet 91


LESSON 3
The If Then Structure
The If Then structure enables the code in a macro to be executed or ignored depending on
the value of an expression. The If Then decision structure consists of the following parts.
• An If Then statement, which begins the structure.
• An End If statement, which ends the structure.
• A criterion expression or Boolean variable in the If Then statement.
• And at least one line of code under the If Then statement.
When executed, the If Then structure first evaluates the criterion expression within it. If the
result of the expression is true, the code within the If Then structure is run; if the expres-
sion is false, the code within the If Then structure is ignored.

Optional If Then Structure Clauses


Like Select Case, the If Then decision structure can contain optional clauses.
• ElseIf Then statements containing criterion expressions.
• An Else statement.
• At least one line of code under each ElseIf Then and Else.
An ElseIf Then clause is formed by a beginning ElseIf Then statement, fol-
lowed by at least one line of code after it. A subsequent ElseIf, Else, or End If
statement forms the clause’s end.
Like the If Then statement, ElseIf Then statements contain a criterion expres-
sion that evaluates to true or false. If the result of the expression is true, the code
within the ElseIf Then statement is run; if the expression is false, the code within
the ElseIf Then statement is ignored.
The criterion expression in an ElseIf statement is evaluated only when the criteria in
the If Then and any ElseIf statements above it are evaluated to false. The Else
statement, placed below any ElseIf statements, contains no criterion. The code under
it runs only when the criterion expressions in the If Then and ElseIf Then state-
ments are evaluated to false.

How to Capture User Input


Procedure Reference: Obtain User Input with an Input Box
To obtain user input with an input box:
1. Declare four variables as string variables: one for the main message, one for the
text that will appear in the title bar, one for the default text that will appear in the
input box’s text box, and one for the user’s response.

' Declaring four variables as strings:

Dim Message, TitlebarTxt, DefaultTxt, UserResponse As


String

92 Microsoft® Office Excel® 2007 - VBA


LESSON 3
2. In the next line, assign string data values to the first three variables.

' Assigning text into the main message variable:

Message = "Text for main message"


TitlebarTxt = "Text for title bar"
DefaultTxt = "Default text for text box"
3. In the line after next, assign the InputBox function, with its parameters, to the
fourth string variable.

' Assigning the InputBox function into a variable:

UserResponse = InputBox(Message,TitlebarTxt, DefaultTxt)

Procedure Reference: Execute Different Code Blocks with Select Case


To execute different code blocks by using the Select Case decision structure:
1. Enter the clauses for the Select Case structure.
a. Type Select Case.
b. In the first line below, type Case.
c. In the second line below, type Case again.
d. If necessary, in the lines below, type additional Case statements.
e. If necessary, in the next line, type Case Else.
f. In the line after next, type End Select.' The Select Case
clauses:

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:

Select Case VarName

Case Criterion1

Lesson 3: Creating an Interactive Worksheet 93


LESSON 3
Case Criterion2

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:

Select Case VarName

Case Criterion1

Code to run if Criterion1 met

Case Criterion2

Code to run if Criterion2 met

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:

Select Case VarName

Case Criterion1

Code to run if Criterion1 met

Case Criterion2

Code to run if Criterion2 met

Case Else
Code to run if no criteria met
End Select

94 Microsoft® Office Excel® 2007 - VBA


LESSON 3
Procedure Reference: Record User Input from a Message Box
To record user input from a message box:
1. Type the name of the variable used to store the user input from the message box.
2. Type the equals sign assignment operator.
3. Type MsgBox().
4. Within the parentheses, enter a string value to direct the user to enter input in the
message box.
5. After the string value, type a comma, and then a number or Visual Basic constant
defining the message box type.

Procedure Reference: Build an If Then...ElseIf...Else...End If Structure


To enter the code for an If Then...ElseIf...Else...End If structure:
1. Type If Then.
2. If necessary, in the next line, type ElseIf Then.
3. If necessary, in the lines below, type additional ElseIf Then clauses.
4. If necessary, in the next line, type Else.
5. In the next line, type End If to complete the main clauses of the If Then
structure.
6. In the If Then statement, between If and Then, enter an evaluative criterion.
7. If necessary, between ElseIf and Then, enter an evaluative criterion.
8. If necessary, enter evaluative criteria for the subsequent ElseIf Then state-
ments.

If comparison1 Then

code to perform if comparison1 is true

ElseIf comparison2 then

code to perform if comparison2 is true

Else

code to perform if other comparisons are false

End If

Lesson 3: Creating an Interactive Worksheet 95


LESSON 3
ACTIVITY 3-2
Sorting a Worksheet Based on User Input
Data Files:
• User Interactive.xlsm

Before You Begin:


From the C:\084037Data\Creating an Interactive Worksheet folder, open the User
Interactive.xlsm file.

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.

What You Do How You Do It

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.

c. In the next blank line, declare YNAnswer


as an integer.

See Code Sample 1.

Code Sample 1
Sub SortBy()
'
'
'
Dim Message, TitlebarTxt, DefaultTxt, SortVal As String
Dim YNAnswer As Integer

End Sub

96 Microsoft® Office Excel® 2007 - VBA


LESSON 3
2. Assign data values to the variables a. Assign message text to Message.
used as parameters in the InputBox
function. See Code Sample 2.

b. In the next line, assign “Sort Call Center


Log” as the text to appear in the title bar.

c. In the next line, assign “Enter 1 or 2” as


the default text for the input box’s text
box.

See Code Sample 3.

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"

TitlebarTxt = "Sort Call Center Log"


DefaultTxt = "Enter 1 or 2"

End Sub

Lesson 3: Creating an Interactive Worksheet 97


LESSON 3
3. Assign the InputBox function, with a. Type SortVal and press the Spacebar.
its parameters, to the SortVal vari-
able.
b. Assign the InputBox function to
SortVal.

c. In the parentheses, enter the parameter


values.

See Code Sample 4.

d. Click at the end of the statement and


press Enter.

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"

TitlebarTxt = "Sort Call Center Log"

DefaultTxt = "Enter 1 or 2"

SortVal = InputBox(Message, TitlebarTxt, DefaultTxt)

End Sub

98 Microsoft® Office Excel® 2007 - VBA


LESSON 3
4. Create a Select Case structure a. Type Select Case and press Enter two
having two Case clauses and a times.
Case Else clause.
b. Type Case and press Enter two times.

c. Type Case and press Enter two times.

d. Type Case Else and press Enter two


times.

e. Type End Select and press Enter two


times.

See Code Sample 5.

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"

Titlebar = "Sort Call Center Log"

DefaultTxt = "Enter 1 or 2"

SortVal = InputBox(Message, TitlebarTxt, DefaultTxt)

Select Case

Case

Case

Case Else

End Select

End Sub

Lesson 3: Creating an Interactive Worksheet 99


LESSON 3
5. Enter SortVal as the variable name a. Click in the Select Case statement,
to be evaluated by the Case struc- press the Spacebar, and type SortVal
tures, and 1 and 2 as the Cases'
criteria string values.
b. Click in the first Case statement, press
the Spacebar, and type "1" as the data
value criterion.

c. Click in the second Case statement, press


the Spacebar, and type "2" as the data
value criterion.

See Code Sample 6.

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.

b. Click in the blank line below Case “2” and


call the RepSort macro for the second
case.

See Code Sample 7.

Code Sample 7
Select Case SortVal

Case "1"

Call DateThenTime

Case "2"

Call RepSort

Case Else

End Select

100 Microsoft® Office Excel® 2007 - VBA


LESSON 3
7. Enter code to reset the macro if none a. Call the SortBy macro if none of the cases
of the criteria for the Case state- are met.
ments are met.
b. In between Case Else and the SortBy
macro call, type YNAnswer followed by a
space to enter the name of the variable
storing input from a message box.

c. Type the equals sign assignment operator


and press the Spacebar.

d. Type MsgBox() to enter the MsgBox


function.

e. Within the parentheses, type "You ⇒


didn't type a 1 or 2. Try ⇒
again?", vbYesNo as the message box
text.

f. Click at the end of the statement and


press Enter.

Lesson 3: Creating an Interactive Worksheet 101


LESSON 3
8. Enter an If Then code to call the a. In the next line, type If Then
SortBy macro again if the answer
entered by the user is yes.
b. Press Enter two times.

c. Type End If

d. Press Enter.

e. In between the If and Then, create a


comparison using YNAnswer to evaluate
whether a yes answer was returned from
the MsgBox function.

f. Move the call to the SortBy macro inside


the If Then structure.

See Code Sample 8.

Code Sample 8
' The completed SortBy macro code:

Sub SortBy()

'Code to display Input Box and retrieve data from user.

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"

TitlebarTxt = "Sort Call Center Log"

DefaultTxt = "Enter 1 or 2"

SortVal = InputBox(Message, Titlebar, DefaultTxt)

'Code to perform sort based on user input.

Select Case SortVal

Case "1"

Call DateThenTime

Case "2"

Call RepSort

Case Else

102 Microsoft® Office Excel® 2007 - VBA


LESSON 3
YNAnswer = MsgBox ("You didn't type a 1 or 2. Try again?",vbYesNo)
If YNAnswer = 6 Then
Call SortBy
End If
End Select

End Sub

9. Run the SortBy macro on the a. Switch to the worksheet.


worksheet.
b. On the worksheet, choose Macros to dis-
play the Macro dialog box.

c. From the list of macros, select the SortBy


macro, and click Run.

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.

c. In the Input text box, type 5

d. Click OK.

e. After reading the Yes/No message box,


click Yes.

f. In the reappearing Input text box, type 5


again.

g. Click OK.

h. After reading the Yes/No message box,


click No to end the macro.

i. Save the file as My UserInteractive.xlsm


and close it.

Lesson 3: Creating an Interactive Worksheet 103


LESSON 3
PRACTICE ACTIVITY 3-3
Including More Sorts
Data Files:
• User Interactive Practice.xlsm

Before You Begin:


Open the User Interactive Practice.xlsm file.

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.

4. Run and test the macro.

5. Save the file as My User Interactive Practice.xlsm and then close it.

104 Microsoft® Office Excel® 2007 - VBA


LESSON 3
Lesson 3 Follow-up
In this lesson, you coded macros to query users for responses that affected data processing
results, making the worksheet interactive.
1. How can the use of input boxes and message boxes change the way you use Excel?

2. How will you determine whether to use an input box versus a message box?

Lesson 3: Creating an Interactive Worksheet 105


NOTES

106 Microsoft® Office Excel® 2007 - VBA


LESSON 4

LESSON 4 Lesson Time


50 minutes

Working with Multiple


Worksheets
In this lesson, you will work with multiple worksheets.
You will:
• Insert, copy, and delete a worksheet.
• Rename worksheets.
• Modify the order of worksheets.
• Print worksheets.

Lesson 4: Working with Multiple Worksheets 107


LESSON 4
Introduction
You know how to manually add, copy, remove, rename, and reorder individual worksheets.
However, VBA can also be used to create and modify several worksheets at once. In this les-
son, you will create macros that facilitate the process of inserting, copying, deleting, renaming,
reordering, and printing worksheets.
There may be instances in your workplace where you need to automate tasks to be performed
not only in a single worksheet of a workbook, but also in several of them simultaneously.
Applying VBA allows you to automate the task of managing multiple worksheets in a single
Excel file.

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.

The Add Method


Definition:
The Add method is a method of the Worksheets collection object used to add
a new, blank worksheet in a worksheet list. The Add command, used to invoke this
method, is attached with a period at the end of the Worksheets object reference.
When executed in a macro, the method places the new worksheet at the end of the
worksheet list. If a new worksheet needs to be added elsewhere, either the Before or
After optional variant is used.

Example:

108 Microsoft® Office Excel® 2007 - VBA


LESSON 4
The Copy Method
Definition:
The Copy method is a method of the Worksheets collection object used to
make a duplicate of an existing worksheet in a worksheet list. The Copy command,
used to invoke this method, is attached with a period at the end of the Worksheets
collection object reference, thereby identifying the worksheet to be duplicated.
When executed in a macro, this method places the duplicate worksheet at the end of
the worksheet list.
If a duplicate worksheet needs to be added elsewhere, either the Before or After
optional variant is used.

Example:

The Delete Method


Definition:
The Delete method is a method of the Worksheets collection object used to
delete a worksheet from a worksheet list. The Delete command, used to invoke this
method, is attached with a period at the end of the Worksheets collection
object reference. When executed in a macro, this method deletes the worksheet refer-
enced by the Worksheets collection object.

Example:

How to Insert, Copy, and Delete Worksheets


Procedure Reference: Insert a Worksheet
To insert a worksheet using a macro:
1. In a macro, type Worksheets.Add.

Lesson 4: Working with Multiple Worksheets 109


LESSON 4
2. If necessary, use the Before optional variant to insert a worksheet before an
existing worksheet.
3. If necessary, use the After optional variant to insert a worksheet after an exist-
ing worksheet.
4. Run the macro.

' Adding a sheet before an existing sheet:

Worksheets.Add Before:=Worksheets(SheetRef)

' Adding a sheet after an existing sheet:

Worksheets.Add After:=Worksheets(SheetRef)

' NB: SheetRef refers either to


' a name or to a position number of an existing
sheet.

Procedure Reference: Delete a Worksheet


To delete a worksheet using a macro:
1. In a macro, type Worksheets.Delete.
2. Insert a pair of parentheses after the Worksheet object reference.
3. Within the parentheses, identify the worksheet to be deleted either by its name or
by its position in the worksheet list.
4. Run the macro.

' IDing by name:

Worksheets("Name").Delete

' IDing by position:

Worksheets(PositionNumber).Delete

Procedure Reference: Copy a Worksheet


To copy a worksheet using a macro:
1. In a macro, type Worksheets.Copy.
2. Insert a pair of parentheses after the Worksheet object reference.
3. Within the parentheses, identify the worksheet to be copied either by its name or
by its position in the worksheet list.
4. If necessary, use the Before optional variant to insert the copy before an exist-
ing worksheet.
5. If necessary, use the After optional variant to insert the copy after an existing
worksheet.

110 Microsoft® Office Excel® 2007 - VBA


LESSON 4
6. Run the macro.

' IDing the sheet to be copied by name:

Worksheets("Name").Copy

' IDing the sheet to be copied by position:

Worksheets(PostionNumber).Copy

' IDing the copy's location using Before:

Worksheets(SheetRef).Copy _
Before:=Worksheets(SheetRef)

' IDing the copy's location using After:

Worksheets(SheetRef).Copy _
After:=Worksheets(SheetRef)

' NB: SheetRef refers either to


' a name or to a position number.

ACTIVITY 4-1
Inserting Worksheets
Data Files:
• New Sheets.xlsm

Before You Begin:


1. From the C:\084037Data\Working with Multiple Worksheets folder, open the New
Sheets.xlsm file.
2. Display the AddSheets macro in the Visual Basic Editor.

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.

What You Do How You Do It

1. Declare the counter variable x as an a. Under the Sub AddSheets statement,


integer in the empty AddSheets under the commenting, type Dim x As
macro. Integer

b. Press Enter.

Lesson 4: Working with Multiple Worksheets 111


LESSON 4
2. Create a For Next loop that uses x a. Type For x = 1 To 12 and press Enter
to iterate the loop 12 times. three times.

b. Type Next x

See Code Sample 1.

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.

b. In the same line, type After:=


Worksheets(x) to insert the After
optional variant to indicate that each new
worksheet should be inserted after the
last worksheet in the worksheet list.

See Code Sample 2.

Code Sample 2
Sub AddSheets()

Dim x As Integer

For x = 1 To 12
Worksheets.Add After:=Worksheets(x)
Next x

End Sub

112 Microsoft® Office Excel® 2007 - VBA


LESSON 4
4. Run the macro to insert the 12 new a. Close the Visual Basic Editor.
worksheets.
b. Run the AddSheets macro.

c. Scroll across the worksheet list to view all


the sheets in the workbook.

d. Save the file as My New Sheets.xlsm and


close it.

5. Where is the Sheet1 worksheet in the list?


a) First
b) Second
c) Twelfth
d) Thirteenth

ACTIVITY 4-2
Deleting a Worksheet
Data Files:
• Project.xlsm

Before You Begin:


From the C:\084037Data\Project.xlsm folder, open the Project.xlsm file.

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.

Lesson 4: Working with Multiple Worksheets 113


LESSON 4
What You Do How You Do It

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

See Code Sample 1.

Code Sample 1
Next x

Worksheets.Delete

End Sub

2. Identify Sheet1 as the sheet to be a. In the deletion statement, insert a pair of


deleted from the worksheet list. parentheses after the Worksheets
object reference.

b. Within the parentheses, type 1 to identify


Sheet1 by its position in the worksheet.

See Code Sample 2.

Code Sample 2
Next x

Worksheets(1).Delete

End Sub

3. Run the macro. a. Close the Visual Basic Editor.

b. Display the Macro dialog box and click


Run to run the DeleteSheet macro.

c. In the warning box that appears, click


Delete to delete the first sheet.

d. Scroll through the worksheet list and


observe that Sheet1 has been deleted.

e. Save the file as My Project.xlsm and


close it.

114 Microsoft® Office Excel® 2007 - VBA


LESSON 4
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
Copying Worksheets
Data Files:
• OG Corp.xlsm

Before You Begin:


1. From the C:\084037Data\Working with Multiple Worksheets folder, open the OG
Corp.xlsm file.
2. Display the CopySheets macro code in the Visual Basic Editor.

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.

Lesson 4: Working with Multiple Worksheets 115


LESSON 4
What You Do How You Do It

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.

c. Within the parentheses, identify the first


sheet as the sheet to be copied by its
position in the worksheet list.

d. After the code Worksheets(1).Copy,


press the Spacebar and type After:=
Worksheets(x) to insert the new copy
after the last sheet in the worksheet list.

See Code Sample 1.

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

2. Run the macro. a. Close the Visual Basic Editor.

b. Display the Macro dialog box and click


Run.

c. In the warning box that appears, click


Delete to confirm the deletion of Sheet1.

d. Scroll through the worksheet list and


observe that Sheet1 has been deleted.

116 Microsoft® Office Excel® 2007 - VBA


LESSON 4
3. Inspect the second worksheet, and a. Select the Sheet1 (2) tab to view its con-
then the last worksheet. tents.

b. Select the Sheet1 (13) tab to view its


contents.

If necessary, use the sheet navigation controls


to display the last worksheet tab.

c. Save the file as My OG Corp.xlsm and


close it.

4. True or False? Sheet2 through Sheet13 contain the same information originally con-
tained in Sheet1.
True
False

DISCOVERY ACTIVITY 4-4


Reviewing How to Insert, Copy, and Delete Worksheets
Scenario:
You are now ready to review your knowledge of how to insert, copy, and delete worksheets.

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.

2. If you need to delete worksheet 2, which code would you use?


a) Delete(2).Worksheets
b) Worksheets(2).Delete
c) Worksheets.Delete(2)
d) Worksheets(2)Delete

Lesson 4: Working with Multiple Worksheets 117


LESSON 4
TOPIC B
Rename Worksheets
You know how to manually rename worksheets. You are now required to rename worksheets
on a frequent basis. In this topic, you will create a macro that renames worksheets.
As you gather worksheet information, you may find that several worksheets need to be repeat-
edly renamed to reflect their ever-changing contents. Rather than to suffer through the tedium
of manually renaming them, you can apply VBA to automate this task of renaming.

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:

The DateSerial Function


Definition:
The DateSerial function is a built-in VBA function that accepts integer data, processes
it, and returns a Date data type. The DateSerial command is followed by a pair of
parentheses containing a comma-separated list of integer values representing the year,
month, and day.

Example:

Valid Integer Values


The valid integer values for the DateSerial function are listed in the table below.

118 Microsoft® Office Excel® 2007 - VBA


LESSON 4
Required Value Valid Range
For the Year 1 to 9999
For the Month 1 to 12
For the Day 1 to 28, 1 to 29, 1 to 30, or 1 to 31, depending on the month and year
values.

The Format Function


Definition:
The Format function is a built-in VBA function that can convert Date data into String
data. When used, the function consists of the Format command, followed by a pair of
parentheses containing two items: an expression whose result is Date data; and a for-
mat expression, which directs the function to format the resulting String data in a
particular style.

Example:

How to Rename Worksheets


Procedure Reference: Rename a Worksheet
To rename a worksheet with a macro:
1. In the macro, type Worksheets().
2. Within the parentheses, identify the worksheet to be renamed either by its name
or by its position in the worksheet list.
3. After the closing parenthesis, add the Name property.
4. Type an equals sign to set the Name property equal to the new name.
5. Type an expression representing the new name of the worksheet.

' Renaming a worksheet

' NB: SheetRef refers to either the name of a


' worksheet or its position in the worksheets
' list; NewName refers to any valid worksheet
' name.

Worksheets(SheetRef).Name = Expression

Lesson 4: Working with Multiple Worksheets 119


LESSON 4
ACTIVITY 4-5
Renaming Inserted Worksheets
Data Files:
• OG Corp Monthly.xlsm

Before You Begin:


1. From the C:\084037Data\Working with Multiple Worksheets folder, open the OG Corp
Monthly.xlsm file.
2. Display the RenameSheet macro code in the Visual Basic Editor.

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.

120 Microsoft® Office Excel® 2007 - VBA


LESSON 4
What You Do How You Do It

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()

b. Within the parentheses, type x + 1 to


identify the worksheet to be renamed as
the last worksheet in the worksheet list.

Because the renaming command follows the


copy command, x + 1 represents the last
worksheet in the list.

c. At the end of the code Worksheets(x


+ 1), type .Name to add the Name
property and then press the Spacebar.

d. Type = to add the assignment operator


and then press the Spacebar.

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.

See Code Sample 1.

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

Lesson 4: Working with Multiple Worksheets 121


LESSON 4
2. Run the macro. a. Close the Visual Basic Editor.

b. Display the Macro dialog box, select the


RenameSheets macro and click Run.

c. In the warning box that appears, click


Delete.

d. Verify that the worksheet name tabs are


named with the months of the year.

e. Save the file as My OG Corp


Monthly.xlsm and close it.

DISCOVERY ACTIVITY 4-6


Exploring Worksheet Renaming
Scenario:
You are now ready to review your knowledge of renaming worksheets.

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.

122 Microsoft® Office Excel® 2007 - VBA


LESSON 4
TOPIC C
Modify the Order of Worksheets
You know how to manually reorder worksheets. You are now required to reorder worksheets
on a frequent basis. In this topic, you will create a macro that reorders worksheets.
As workbooks become large and unwieldy, frequently used information might be located at
opposite ends of the worksheet list. By reordering worksheets automatically, you can modify
the order of worksheet information in situations that demand quick access to otherwise “bur-
ied” data.

The Move Method


Definition:
The Move method is a method of the Worksheets collection object that moves
a worksheet from one position in the worksheet list to another. The Move command is
attached with a period to the Worksheets object reference; the Before or After
option is used to identify the destination of the worksheet being moved.

Example:

How to Modify the Order of Worksheets


Procedure Reference: Move a Worksheet
To move a worksheet with a macro:
1. In the macro, type Worksheets.Move.
2. Insert a pair of parentheses after the Worksheets object reference.
3. Within the parentheses, identify the sheet to be moved either by its name or by its
position in the worksheet list.

' By name:

Worksheets("SheetName").Move

' By position:

Worksheets(Number).Move

Lesson 4: Working with Multiple Worksheets 123


LESSON 4
4. If necessary, use the Before optional variant and the Worksheet
collection object to move the worksheet before another existing worksheet.
5. If necessary, use the After optional variant and the Worksheet
collection object to move the worksheet after another existing worksheet.

' Moving a sheet before an existing sheet:

Worksheets(SheetRef1).Move Before:=Worksheets(SheetRef2)

' Moving a sheet after an existing sheet:

Worksheets(SheetRef1).Move After:=Worksheets(SheetRef2)

' NB: SheetRef refers to either


' the name or position number of a sheet.
6. Run the macro.

ACTIVITY 4-7
Moving Worksheets Within a Workbook
Data Files:
• OGC Sales.xlsm

Before You Begin:


1. From the C:\084037Data\Working with Multiple Sheets folder, open the OGC Sales.xlsm
file.
2. In Visual Basic Editor, display the empty SEMove macro.

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.

What You Do How You Do It

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.

b. In the parentheses, type "SE Sales" to


identify SE Sales as the sheet to be
moved, and then click at the end of the
code and press the Spacebar.

124 Microsoft® Office Excel® 2007 - VBA


LESSON 4
2. Indicate that the sheet is to be a. Type Before:= to add the optional vari-
moved to the first position in the ant.
worksheet list.
b. Type Worksheets(1) to identify the
first sheet in the list as the sheet in front
of which the moved sheet is to be placed.

See Code Sample 1.

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.

c. Paste the same line of code onto the next


line.

d. Change the name of the worksheet being


moved to SE Clients.

e. Paste the same line of code onto the next


line and change the name of the
worksheet being moved to SE Team.

See Code Sample 2.

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)

Lesson 4: Working with Multiple Worksheets 125


LESSON 4
4. Run the SEMove macro to move the a. Close the Visual Basic Editor.
SE-related worksheets to the begin-
ning of the worksheet list.
b. Display the Macro dialog box, and run the
SEMove macro.

c. Click the second worksheet tab to display


the SE Clients worksheet.

d. Click the third worksheet tab to display


the SE Marketing worksheet.

e. Click the fourth worksheet tab to display


the SE Sales worksheet.

f. Click the first worksheet tab to display


the SE Team worksheet.

g. Save the file as My OGC Sales.xlsm and


close it.

DISCOVERY ACTIVITY 4-8


Understanding How to Modify the Order of Worksheets
Scenario:
You are now ready to review your knowledge of modifying the order of worksheets using
macros.

1. What are the parentheses used for when moving a worksheet?


a) They identify the sheet to be moved.
b) They identify the desired location to move the file.
c) They are optional variants used to position sheet before or after another sheet.
d) They are only used to insert a new worksheet while moving a worksheet.

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

126 Microsoft® Office Excel® 2007 - VBA


LESSON 4
TOPIC D
Print Worksheets
You know how to manually print worksheets. You are now required to print worksheets fre-
quently. In this topic, you will create a macro that prints worksheets.
The only thing that is more cumbersome than scrolling back and forth to view selected
worksheets in a large workbook is scrolling and then printing them. By automating the printing
of worksheets, you can extract data from large workbooks without having to hunt through a
long worksheets list.

The PrintPreview Method


Definition:
The PrintPreview method is a method of the Worksheets collection object
used to display worksheets in the Print Preview window. When used, the
PrintPreview command is attached with a period to the Worksheets
collection object reference.
If the Worksheets collection object contains no specific reference to a particu-
lar worksheet in the collection, all worksheets contained in the workbook are
displayed, when the method is executed. Otherwise, the worksheet referenced by the
Worksheets collection object is displayed.

Example:

The PrintOut Method


Definition:
The PrintOut method is a method of the Worksheets collection object used to
send worksheets to the printer. When used, the PrintOut command is attached with
a period to the Worksheets collection object reference.
If the Worksheets collection object contains no specific reference to a particu-
lar worksheet in the collection, all worksheets contained in the workbook are printed,
when the method is executed. Otherwise, the worksheet referenced by the
Worksheets collection object is printed.

Lesson 4: Working with Multiple Worksheets 127


LESSON 4
Example:

How to Print Worksheets


Procedure Reference: Preview Worksheet Printing with a Macro
To preview worksheet printing with a macro:
1. If necessary, in the macro, type Worksheets.PrintPreview to preview all
the sheets in the workbook.
2. If necessary, in the macro, type Worksheets(SheetRef).PrintPreview
to preview a selected sheet in the workbook, where SheetRef is a reference either
to a worksheet name or its position in the worksheet list.

' Previewing all worksheets:

Worksheets.PrintPreview

' Previewing a worksheet by name:

Worksheets("SomeName").PrintPreview

' Previewing a worksheet by its position:

Worksheets(Number).PrintPreview
3. Run the macro.
4. Preview the printout in the Print Preview window.

Procedure Reference: Preview Selected Adjacent Worksheets


To preview selected adjacent worksheets with a macro:
1. In the macro, construct a For Next loop, whose counter variable values refer to
the worksheet list index values of the worksheets you want to preview.
2. Within the For Next loop, type Worksheets().PrintPreview.

128 Microsoft® Office Excel® 2007 - VBA


LESSON 4
3. Within the parentheses, enter a reference to the counter variable.

For x = Num1 To Num2

Worksheets(x) Preview

Next x

' Num1 refers to the first sheet in the worksheet list


to be
' previewed
' Num2 refers to the last sheet in the worksheet list
to be
' previewed
4. Run the macro.

Procedure Reference: Preview Non-Adjacent Worksheets


To preview a series of non-adjacent worksheets with a macro:
1. In the macro, type Worksheets().PrintPreview.
2. Within the parentheses, type the name of the first worksheet to be previewed in
quotation marks.
3. Copy and paste the line of code you just entered to the next blank line.
4. Change the name in the new line of code to the name of the next worksheet you
want to preview.
5. If necessary, copy, paste, and edit additional lines of code until all the non-
adjacent worksheets you want to preview are referenced.
6. Run the macro.

' Print previewing non-adjacent worksheets:

Worksheets(SheetRef1).Preview

Worksheets(SheetRef2).Preview

Worksheets(SheetRef3).Preview

' NB: The names or position number of the referenced


sheets ' refer to
non-adjacent worksheets.

Lesson 4: Working with Multiple Worksheets 129


LESSON 4
ACTIVITY 4-9
Previewing an Entire Workbook
Data Files:
• Divisions.xlsm

Before You Begin:


1. From the C:\084037Data\Working with Multiple Sheets folder, open the Divisions.xlsm
file.
2. In Visual Basic Editor, display the empty PrintAllSheets macro.

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.

What You Do How You Do It

1. Enter the code necessary to preview a. In the PrintAllSheets macro, type


all the sheets in a workbook, in the Worksheets to enter the reference to
PrintAllSheets macro. the Worksheets collection object.

b. Add a period to add a method to the


object.

c. Type PrintPreview to add the method


that previews the printout of the work-
book sheets.

See Code Sample 1.

d. Close the Visual Basic Editor.

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.

130 Microsoft® Office Excel® 2007 - VBA


LESSON 4
3. Preview the printout in the Print a. After you read the contents of the first
Preview window that is displayed. displayed worksheet, click Next Page.

b. After you read the contents of the second


displayed worksheet, click Next Page.

c. In the lower-left corner of the Print Pre-


view window, verify the status, which
indicates that 24 worksheets can be pre-
viewed.

d. In the Preview group, click Close Print


Preview to close the Print Preview win-
dow.

e. Save the file as My Divisions.xlsm and


close it.

ACTIVITY 4-10
Previewing Selected Adjacent Worksheets
Data Files:
• New Divisions.xlsm

Before You Begin:


1. From the C:\084037Data\Working with Multiple Sheets folder, open the New
Divisions.xlsm file.
2. In Visual Basic Editor, display the empty PrintDivision macro.

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.

What You Do How You Do It

1. Declare the counter variable x as an a. In the PrintDivision macro, type Dim ⇒


integer, in the PrintDivision macro, x As Integer
and then code a For Next loop that
can be used to print the first four
worksheets in the worksheet list. b. In the next line below, type For x = ⇒
1 To 4 and press Enter twice.

c. Type Next x and press Enter.

Lesson 4: Working with Multiple Worksheets 131


LESSON 4
2. Enter the code to preview a selected a. Within the loop, type
worksheet, within the For Next Worksheets.PrintPreview
loop.
b. In the Worksheets collection object,
type (x) to insert a sheet reference that
uses the counter variable.

See Code Sample 1.

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.

c. Select the PrintDivision macro and click


Run.

4. Preview each sheet. a. View the preview for the first sheet, and
then click Close Print Preview.

b. View the preview for the second sheet,


and then click Close Print Preview.

c. View the preview for the third sheet, and


then click Close Print Preview.

d. View the preview for the fourth sheet,


and then click Close Print Preview.

e. Save the file as My New Divisions.xlsm


and close it.

132 Microsoft® Office Excel® 2007 - VBA


LESSON 4
PRACTICE ACTIVITY 4-11
More Adjacent Printing
• My New Divisions.xlsm

Before You Begin:


The file from the last activity remains open.

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

4. Save the file as My New Divisions.xlsm and then close it.

Lesson 4: Working with Multiple Worksheets 133


LESSON 4
ACTIVITY 4-12
Previewing Selected Non-Adjacent Worksheets
Data Files:
• Sales Details.xlsm

Before You Begin:


1. From the C:\084037Data\Working with Multiple Sheets folder, open the Sales Details.xlsm
file.
2. In Visual Basic Editor, display the empty PrintSales macro.

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.

What You Do How You Do It

1. Enter the code, in the PrintSales a. In the PrintSales macro, type


macro to preview the sales Worksheets.PrintPreview
worksheet for the NE Division.
b. In the Worksheets collection object,
type ("NE Sales") to insert a sheet ref-
erence that uses the name of the NE
Division’s Sales worksheet.

2. Copy and paste the code you just a. Select Worksheets("NE Sales")
entered onto the next blank line. .PrintPreview.

b. On the Standard toolbar, click the Copy


button.

c. Place the insertion point in the next blank


line.

d. On the Standard toolbar, click the Paste


button.

134 Microsoft® Office Excel® 2007 - VBA


LESSON 4
3. Modify the pasted code so that the SE a. Place the insertion point between N and E
Sales worksheet is referenced by the of NE.
Worksheets collection object.
b. Press Backspace.

c. Type S

See Code Sample 1.

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.

c. Select the PrintSales macro and click


Run.

5. Preview each sheet. a. View the preview for the first sheet, and
then click Close Print Preview.

b. View the preview for the second sheet,


and then click Close Print Preview.

c. Save the file as My Sales details.xlsm


and then close it.

Lesson 4: Working with Multiple Worksheets 135


LESSON 4
DISCOVERY ACTIVITY 4-13
Exploring How to Print Worksheets
Scenario:
You are now ready to review your knowledge of printing worksheets.

1. Which is an example of code that will print worksheet number 2?


a) Worksheets(2).PrintOut
b) Worksheets(2).Print
c) Worksheets.PrintOut(2)
d) Print(2).Worksheets

2. True or False? In PrintPreview, if no workbook is chosen, the default is to display all


worksheets in the workbook.
True
False

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?

136 Microsoft® Office Excel® 2007 - VBA


LESSON 5

LESSON 5 Lesson Time


35 minutes

Performing Calculations
In this lesson, you will perform calculations.
You will:
• Create a user-defined function.
• Automate a SUM function.

Lesson 5: Performing Calculations 137


LESSON 5
Introduction
You created macros that used VBA’s built-in functions. However, these built-in functions may
not always meet your needs. This is where the ability to create user-defined functions can
come to your aid. In this lesson, you will create a user-defined function to automate calculating
varying quantities of data in a worksheet.
Your company is likely to use specific calculations other than those available with Excel. VBA
allows you to create custom functions that perform duties beyond the built-in functions.

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.

138 Microsoft® Office Excel® 2007 - VBA


LESSON 5
Example:

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.

Lesson 5: Performing Calculations 139


LESSON 5
Example:

The Else Clause


Definition:
The Else clause is an optional clause in the If Then decision structure. It does not
contain any criterion, and it executes the code between it and the End If statement,
only when all criteria in the If Then structure are evaluated to a Boolean value of
false.

Example:

How to Create User-Defined Functions


Procedure Reference: Insert a New Function
To insert a new function into a project:
1. In Visual Basic Editor, in the Project Explorer, select the project into which you
want to insert the new function.
2. Choose Insert→Procedure to display the Add Procedure dialog box.
3. In the Name text box, enter a name for the new function.

140 Microsoft® Office Excel® 2007 - VBA


LESSON 5
4. In the Type section, select Function.
5. If necessary, declare whether the function will be a private or public function.
6. Click OK.

Procedure Reference: Create and Apply a User-Defined Function


To create and apply a user-defined function:
1. After the function name, between the empty parentheses, enter the name of the
first argument.
2. If necessary, add additional arguments.
a. Type a comma and a space after the first argument.
b. Type the name of the second argument.
c. If additional arguments will be entered, type their names in a comma-
separated list.
3. If necessary, return a value from the function.
a. In a blank line, type the function’s name.
b. Type an equals sign to assign a value to the function return.
c. Type an expression whose result is the value you want to return from the
function.
4. Apply the function on the worksheet.

ACTIVITY 5-1
Creating and Applying a User-Defined Function
Data Files:
• Price Level.xlsm

Before You Begin:


From the C:\084037Data\Performing Calculations folder, open the Price Level.xlsm file.

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.

Lesson 5: Performing Calculations 141


LESSON 5
What You Do How You Do It

1. Create a new function named a. Display the Visual Basic Editor.


PriceLevel.
b. In Visual Basic Editor, choose Insert→
Procedure to display the Add Procedure
dialog box.

c. In the Name text box, type PriceLevel

d. In the Type radio button group, select


Function.

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.

c. Press the Spacebar.

d. Type byr as the name of the second argu-


ment.

e. Type a comma.

f. Press the Spacebar.

g. Type eyr as the name of the third argu-


ment.

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.

c. In the next line below, type End If and


press Enter.

d. In the If Then clause, between If and


Then, create an expression that is true if
the eyr or byr arguments contain values
smaller than 1913 or larger than 2008.

142 Microsoft® Office Excel® 2007 - VBA


LESSON 5
4. Return zero as the value from the a. Click at the end of the statement and
PriceLevel function if the year press Enter. In between the If Then and
arguments are neither within 1913 to the Else statements, type the function’s
2008 nor equivalent to the inflation- name.
adjusted amount.
b. Press the Spacebar.

c. Type an equals sign to assign a value to


the function.

d. Press the Spacebar.

e. Set zero as the value of the function.

f. If necessary, scroll down.

g. Click after Else, press Enter, and then


type the code that calculates and returns
the inflation-adjusted amount.

See Code Sample 1.

h. Close the Visual Basic Editor.

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

PriceLevel = amount * CPI_idx(eyr) / CPI_idx(byr)


End If

Lesson 5: Performing Calculations 143


LESSON 5
5. Apply the function in the cell next to a. In cell B7, click and type the equals sign.
the “Is Equivalent To” item on the
Price Level worksheet.
b. Type PriceLevel as the function’s
name.

c. Type an open parenthesis.

d. Click cell B5 to insert the cell reference


for the amount argument.

e. Type a comma.

f. Click cell B6 to insert the cell reference


for the byr argument.

g. Type a comma.

h. Click cell B8 to insert the cell reference


for the eyr argument.

i. Type a closing parenthesis.

j. Press Enter to assign the function to the


cell.

k. Save the file as My Price Level.xlsm and


close it.

144 Microsoft® Office Excel® 2007 - VBA


LESSON 5
TOPIC B
Automate SUM Functions
You know how to use VBA’s default SUM function to calculate a selected set of data. How-
ever, it is easy to calculate without specifying a set of data. In this topic, you will use a user-
defined function to automate the calculation of data in a worksheet.
When working with large workbooks containing multiple pages of regularly updated data, it
might seem a daunting task for you to make sure that all those manually set ranges for calcu-
lating sums stay on target—all too often, an added column or row of information throws
everything off, making your results worthless. By creating a custom SUM function that can
anticipate and adapt to the changes made to worksheet data, you can sum altered data without
the need of manually verifying and resetting data ranges.

Declared Range Objects


Definition:
A Declared Range object is a VBA object that represents a named range. Like a vari-
able, it exists as a storage location during the execution of a macro as part of its
processing code. It differs from a variable, however, in that it stores a cell range, not a
single data value. When a Declared Range object is declared, the Range com-
mand is added after the object’s name at the end of the Dim As command.

Example:

Lesson 5: Performing Calculations 145


LESSON 5
The Set Statement
Definition:
The Set statement is a VBA language component used to assign a cell range to a
Declared Range object. In this method, you need to first enter the Set command,
followed by the name of the Declared Range object; you then need to complete
the command by entering the equals sign assignment operator and an expression that
both define a cell range.

Example:

Range Object Cell Addressing


Definition:
Range object cell addressing is a VBA cell-addressing convention that organizes a cell
range assigned to a Declared Range object. When a cell range on a spreadsheet is
assigned to a Declared Range object, the object superimposes its own cell address-
ing coordinate system onto the cells in the range. Subsequent code using the
Declared Range object to reference the cells must use the cell addressing coordi-
nate system of the object, not that of the spreadsheet, to manipulate the contents of the
range. However, generic VBA commands that make use of the worksheet’s addressing
coordinate system can still access and control the data range.

Example:

146 Microsoft® Office Excel® 2007 - VBA


LESSON 5
The Rows Property
Definition:
The Rows property is a property of a Declared Range object that represents the
rows in a range. When used, the Rows command, followed by a pair of parentheses, is
attached to the Declared Range object reference with a period. A data value or
expression yielding an integer value can be placed within the parentheses to indicate
the number of rows the property refers to in a given VBA command.

Example:

The Formula Property


Definition:
The Formula property is a property of a Declared Range object that is used to
insert formulas in the cells of an indicated range. When used, the Formula command
is attached with a period to the Declared Range object reference; the equals sign
assignment operator and an expression defining the text for a formula for entry in
worksheet cells complete the command.

Example:

Lesson 5: Performing Calculations 147


LESSON 5
The Columns Property
Definition:
The Columns property is a property of a Declared Range object that represents the
columns in the range. When used, the Columns command, along with a pair of paren-
theses and a period, is attached to the Declared Range object reference. Data or an
expression is placed within the parentheses, along with an integer value, that identifies
the column in the range being referenced.

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:

Address Property Cell Reference Settings


Address property cell reference settings are true/false settings you can employ while using the
Address property to concatenate text for formulas that require absolute or relative cell refer-
encing when inserted in a cell range. The comma-separated settings are entered within a pair
of parentheses attached without a period to the end of the Address property reference.
The first true/false setting determines whether the row’s reference is absolute or relative; the
second, the column’s. By default, cell reference settings for the Address property are set to
true, meaning that absolute referencing is applied for both row and column referencing.

148 Microsoft® Office Excel® 2007 - VBA


LESSON 5

Figure 5-1: Address property cell referencing.

How to Automate the SUM Functions


Procedure Reference: Set a Range into a Declared Range Object
To set a range into a Declared Range object:
1. Use the Range object and its Select method to select a cell in the range.
2. In the next line, type Set and the name of the Declared Range object.
3. Type the equals sign assignment operator.
4. Assign the current region of the active cell to the Declared Range object.

Procedure Reference: Position a Range Object Below Another Range of


Unknown Length
To position a Range object below another range:
1. Type Set.
2. Type the name of the Range object to be positioned.
3. Type the equals sign assignment operator.
4. Type the name of the original Range used to reference the Range object’s posi-
tion.
5. Add the Offset property.
6. Within the Offset property, use the Rows and Count properties of the original
Range object to count its rows.

Lesson 5: Performing Calculations 149


LESSON 5
7. To the Offset property, add the Rows property.
8. In the Rows property, enter a numeric value that offsets the Range object to the
desired number of rows below the bottom of the original Range object.

Procedure Reference: Insert a SUM Function in the Cells of a Declared Range


Object
To insert a SUM function in the cells of a Declared Range object:
1. Type the name of the Range object.
2. Add the Formula property.
3. Add the equals sign assignment operator.
4. Within quotation marks, type the beginning of the SUM function as if you are typ-
ing it into a cell.
5. To your existing code, concatenate an expression whose result is syntactically cor-
rect.
6. To your existing code, concatenate the closing text for the function.

Procedure Reference: Changing Cell Values in a Declared Range Object


To change cell values in a Declared Range object:
1. Type the name of the Range object.
2. Add the Range property.
3. Within the Range property’s parentheses, reference the cell or cells whose value
you want to change.
4. Add the Value property.
5. Add the equals sign assignment operator.
6. Enter an expression or data value you want to assign to the cell.

150 Microsoft® Office Excel® 2007 - VBA


LESSON 5
ACTIVITY 5-2
Summing the Data Ranges of Unknown Length
Data Files:
• Auto Sum.xlsm

Before You Begin:


From the C:\084037Data\Performing Calculations folder, open the Auto Sum.xlsm file.
Display the AddTotals macro in the Visual Basic Editor.

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.

What You Do How You Do It

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.

b. In the next blank line, declare myTotal


as a 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.

b. In the next line, type Set myData

c. Press the Spacebar.

d. Type the equals sign to add the assign-


ment operator.

e. Press the Spacebar.

f. Assign myData to the current region of


the active cell and press Enter.

Lesson 5: Performing Calculations 151


LESSON 5
3. Position myTotal, two rows below a. Under the “Position the totals range
myData, under the third comment. object below the data range” comment,
type Set

b. Press the Spacebar.

c. Add myTotal as the name of the Range


object to be positioned.

d. Press the Spacebar.

e. Add the assignment operator.

f. Press the Spacebar.

g. Add a reference to the myData Range


object.

h. Add the Offset property.

i. Within the Offset property’s parenthe-


ses, add an expression that counts the
number of rows in myData.

j. Add the Rows property.

k. Within the Rows property, enter a value


that will position myTotal two rows
below the bottom of myData.

152 Microsoft® Office Excel® 2007 - VBA


LESSON 5
4. Insert the SUM function inside the a. Under the “Insert the SUM function in the
cells of myTotal, under the fourth totals range object” comment, type
comment. myTotal

b. Add the Formula property.

c. Press the Spacebar.

d. Add the assignment operator.

e. Press the Spacebar.

f. Within quotation marks, type the begin-


ning of the SUM function as if you are
typing it into a cell.

g. Concatenate an expression that sets a


direct mapping between myData and
myTotal with relative addressing.

h. Concatenate the closing text for the SUM


function.

Lesson 5: Performing Calculations 153


LESSON 5
5. Change the first cell of myTotal so a. Under the “Modify the first three cells of
that it contains the text “Total:” and the totals range object” comment, type
then delete the contents of the sec- myTotal
ond and third cells, under the fifth
comment.
b. Add the Range property.

c. Within the Range property’s parentheses,


refer to the first cell in myTotal.

d. Click at the end of the statement and add


the Value property.

e. Press the Spacebar.

f. Add the assignment operator.

g. Press the Spacebar.

h. Add the text into the cell.

i. In the next line, reference the second and


third cells in myTotal.

j. Assign the empty string to the cells’


Value property.

See Code Sample 1.

k. Close the Visual Basic Editor.

Code Sample 1
Sub AddTotals()

Dim x As Integer

'Declare the range objects here:


Dim myData As Range
Dim myTotal As Range
For x = 1 To Worksheets.Count

Worksheets(x).Select

'Set the data range object:


Range("A7").Select
Set myData = ActiveCell.CurrentRegion
'Position totals range object below the data range:
Set myTotal = myData.Offset(myData.Rows.Count).Rows(2) 'Insert the
SUM function in the totals range object:
myTotal.Formula = "=Sum(" & myData.Columns(1).Address(False, False) & _
")"
'Modify the first three cells of the totals range object:
myTotal.Range("A1").Value = "Total:"

154 Microsoft® Office Excel® 2007 - VBA


LESSON 5
myTotal.Range("B1:C1").Value = ""
Next x

End Sub

6. Test the macro. a. On the Developer tab, click Macros to


display the Macro dialog box.

b. Verify that the AddTotals macro is


selected and click Run.

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.

b. Select the Northwest worksheet and


scroll down to view the inserted totals at
the bottom of the data columns.

c. Select the Southeast worksheet and scroll


down to view the inserted totals at the
bottom of the data columns.

d. Select the Southwest worksheet and


scroll down to view the inserted totals at
the bottom of the data columns.

e. Save the file as My Auto Sum.xlsm and


close it.

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. Why would you automate the insertion of functions?

Lesson 5: Performing Calculations 155


FOLLOW-UP Follow-up
In Microsoft® Offıce Excel® 2007 - VBA, you applied the Visual Basic for Applications (VBA)
programming language to automate many of the tasks you learned to perform in Microsoft®
Offıce Excel® 2007 - Level 1 and Microsoft® Offıce Excel® 2007 - Level 2. Applying VBA to
spreadsheets automated repetitive tasks, and deploying custom functions increased productivity
to easily manage large quantities of spreadsheets.
1. What trade-off must be estimated when deciding to create macros to complete a task?

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.

156 Microsoft® Office Excel® 2007 - VBA


LESSON
LABS

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

Before You Begin:


From the C:\084037Data\Developing Macros folder, open the LLL1.xlsx file.

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.

1. Open a new blank workbook.

2. In the Personal Macro Workbook, record three macros that change the worksheet’s
background color to:
• Red
• Blue
• Yellow

3. Assign the macros you created to the toolbar.

4. Test the macros to change the blank workbook’s background color.

Lesson Labs 157


LESSON
5. Close the blank workbook.
LABS
6. Open the LLL1.xlsx file.

7. Using the custom toolbar, change the background color of the LLL1.xlsx file.

8. Close the LLL1.xlsx file without saving.

LESSON 2 LAB 1
Creating Grade Sheet Reports
Data Files:
• LLL2.xlsx
• xLLL2.xlsm

Before You Begin:


The Excel application is running.

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.

3. Record a series of macros that:


• Sort the data by the last column (Course Grade).
• Insert one column and six rows from the upper-left corner of the worksheet for each
class section.
• Insert the report header text, including the section’s name, for each section
worksheet.
• Format the report header text for each section worksheet, including the autofitted
column widths.

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.

158 Microsoft® Office Excel® 2007 - VBA


LESSON
5. In the ReportGenerator macro, create a loop structure that calls each recorded
macro to format each section’s grade sheet by: LABS
a. Sorting the data on each sheet by the last column (Course Grade).
b. Inserting one column and six rows from the upper-left corner of the worksheet for
each section.
c. Inserting the report header text, including the section’s name, for each section
worksheet.
d. Formatting the report header text for each section worksheet.
e. Formatting the columns so that the report text is correctly spaced on each section
worksheet.

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.

6. To the loop structure, add code that:


a. Duplicates the data from the first three worksheets onto the last All Sections
worksheet.
b. Lists each section’s name as a header above each section’s data.
c. Formats the columns of the All Sections worksheet so that the text is appropriately
spaced.

7. Run the macro to test your code.

If necessary, check the code in xLLL2.xlsm for help.

8. Save your work as MyLLL2.xlsm and then close the file.

Lesson Labs 159


LESSON
LABS LESSON 3 LAB 1
Building an Interactive Grade Sheet
Data Files:
• LLL3.xlsx

Before You Begin:


From the C:\084037Data\Creating an Interactive Worksheet folder, open the LLL3.xlsx file.

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.

4. Test your work.

160 Microsoft® Office Excel® 2007 - VBA


LESSON
LESSON 4 LAB 1 LABS
Moving and Printing Worksheets
Data Files:
• LLL4.xlsx
• xLLL4.xlsm

Before You Begin:


From the C:\084037Data\Working with Multiple Sheets folder, open the LLL4.xlsm file.

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.

2. In the code defining the input box, enter code that:


• Forms the main message in the input box: A request to the user to enter a 1, 2, 3, or
4 to move the first, second, third, or fourth quarter’s worth of worksheets to the
beginning of the worksheet list.
• Lists “Worksheet Move” as the name of the input box.
• Lists “Enter 1, 2, 3, or 4 here” as the default text for the input box’s text box.

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.

Lesson Labs 161


LESSON
LABS LESSON 5 LAB 1
Creating a Function to Calculate Sales Commissions
Data Files:
• LLL5.xlsx

Before You Begin:


From the C:\084037Data\Performing Calculations folder, open the LLL5.xlsx file.

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.

Amount Invested Fee Charged


$1 million and over 1.25%
$500,000 up to $1 million 1.5%
$250,00 up to $500,000 1.75%
$100,000 up to $250,000 2.0%
$0 up to $100,000 2.25%

The function should take one argument—the amount invested—and return a value
equal to the sales commission.

You have to build an If Then...ElseIf...End If construct to select the correct percentage to


multiply against the amount.

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.

4. Cross-check your work by calculating a commission manually for at least one


transaction in each category.

View the code in xLLL5.xlsm for the solution.

162 Microsoft® Office Excel® 2007 - VBA


LESSON
5. Save your work as MyLLL5.xlsm and then close the file.
LABS

Lesson Labs 163


NOTES

164 Microsoft® Office Excel® 2007 - VBA


SOLUTIONS
SOLUTIONS
Activity 1-5

3. What must be done to an electronic file in order to create a digital signature?


a) Disable all macros without notification.
b) Add revision tracking.
c) Disable all macros with notification.
✓ d) Add a digital certificate.

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

1. Which is a property of the Workbook object?


✓ a) ActiveSheet
b) Name
c) Value
d) Selection

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

1. Which is a variable naming rule?


a) The first character of the variable name must be a number.
b) There is not a character size limit.
c) Any sign can be used in the name.
✓ d) The name can’t be the same as VBA’s language components.

2. Which is an example of a command that a Do Loop consists of?


a) Does
✓ b) While
c) Where
d) Done

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

166 Microsoft® Office Excel® 2007 - VBA


SOLUTIONS
2. Which direction command is used to get the effect of pressing End+Right Arrow?
a) xlDown
✓ b) xlToRight
c) xlUp
d) xlShift

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

5. Where is the Sheet1 worksheet in the list?


✓ a) First
b) Second
c) Twelfth
d) Thirteenth

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.

2. If you need to delete worksheet 2, which code would you use?


a) Delete(2).Worksheets
✓ b) Worksheets(2).Delete
c) Worksheets.Delete(2)

168 Microsoft® Office Excel® 2007 - VBA


SOLUTIONS
d) Worksheets(2)Delete

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

1. What are the parentheses used for when moving a worksheet?


✓ a) They identify the sheet to be moved.
b) They identify the desired location to move the file.
c) They are optional variants used to position sheet before or after another sheet.
d) They are only used to insert a new worksheet while moving a worksheet.

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

1. Which is an example of code that will print worksheet number 2?


✓ a) Worksheets(2).PrintOut
b) Worksheets(2).Print
c) Worksheets.PrintOut(2)
d) Print(2).Worksheets

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

170 Microsoft® Office Excel® 2007 - VBA


GLOSSARY

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.

Address property cell reference settings Columns property


Two true/false settings you can employ while A property of a Declared Range object that
using the Address property to concatenate text represents the columns in the range.
for formulas that require absolute or relative
cell referencing when inserted in a cell range. comparison operators
Operators used to evaluate as true or false to
Address property check whether a data value meets a criterion.
A property of the ActiveCell object repre-
senting a string value describing the location Concatenation
of the currently active cell. The act of connecting two or more pieces of
text information together with an ampersand
argument to form a single, longer piece of text.
A variable used to pass data from a worksheet
to a function for processing. constants
Variables whose values are predefined and
arithmetic operators unchangeable in VBA.
Operators used in calculating mathematical
expressions. Copy method of ActiveSheet object
A method of the ActiveSheet object used
assignment operators (=) to copy currently selected worksheet data to
A VBA language component used to manage the Excel Clipboard.
the flow of data into and out of variables.
Copy method of Worksheet collection
AutoFit method object
A method of the Columns object used to A method of the Worksheets
change the widths of the column range. collection object used to make a dupli-
cate of an existing worksheet in a worksheet
Call command list.
An Excel VBA language component used to
run a macro from another macro. Count property
A property of the Worksheets
collection object; which contains an inte-
ger value representing the number of
worksheets in the currently active workbook.

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.

data types expressions


Different kinds of data you use when creating Combinations of data, operators, functions,
macros to process information. and variables that, together, process informa-
tion to yield a single data value.
DateSerial function
A built-in VBA function that accepts integer Font property
data, processes it, and returns a Date data An Excel VBA property used to set how text
type. will appear on a worksheet.

debugging process For Next loop


The means by which you can identify, locate, A code group that repeats the execution of a
and fix errors in macro code. series of VBA commands by using a counter
variable.
debugging tools
VBE tools that you can use to locate, exam- Format function
ine, and fix mistakes in VBA code. A built-in VBA function that can convert date
data into string data.
Decision structures
Code groups that enable macro developers to Formula property
cause a macro to perform different actions A property of a Declared Range object
based on varying inputs. that is used to insert formulas in the cells of
an indicated range.
Declared Range object
A VBA object that represents a named range. function call
A coding context in which a function causes
Delete method another function to perform data calculations.
A method of the Worksheets
collection object used to delete a If Then
worksheet from a worksheet list. A VBA code structure that enables the code
to be executed or ignored depending on the
digital certificate value of an expression.
An electronic file that contains unique infor-
mation about a specific person. input box
A dialog box consisting of a message to the
digital signature macro user, a text box into which the user can
A content authentication tool that authenti- type requested data, and at least one button,
cates the sender and ensures the integrity of which the user can click.
the digital document.
InputBox function
Do loop A built-in VBA function that governs how an
A code group that repeats the execution of a input box is displayed.
series of VBA commands until an evaluative
criterion is met.

172 Microsoft® Office Excel® 2007 - VBA


GLOSSARY
logical operators object
Operators that compare two or more true/false A programming construct that, for the most
values. part, mimics the characteristics of the compo-
nents of an Excel workbook.
Macro dialog box
A dialog box that allows you to create, run, Offset property
edit, or delete the selected macro. A property of the ActiveCell object used
to measure a distance from the currently
Macro Recorder active cell.
An Excel tool you can use to create a macro
by recording actions you take in the work- operators
book. Symbols you use to do tasks such as perform-
ing arithmetic, comparing two numbers,
macro assigning data to a worksheet cell, or answer-
A task automation tool that executes a set of ing questions of logic.
commands to automate frequently repeated
steps. Paste method
A method of the ActiveSheet object used
message box to paste Clipboard contents into a selection on
Used by macro developers to capture user the worksheet.
input when a macro runs.
Personal Macro Workbook
method A storage location where you can create and
A set of short built-in programs whose actions save the macros you create in Excel.
change the referenced worksheet component.
PrintOut method
module A method of the Worksheets
A project entity, similar to a text file, that collection object used to send worksheets
stores macro code. to the printer.
Modules folder PrintPreview method
The location in a project where macro code is A method of the Worksheets
stored. collection object used to display
worksheets in the window.
Move method
A method of the Worksheets private function
collection object that moves a worksheet A function that can be used only by the
from one position in the worksheet list to project containing the module where the func-
another. tion code exists.
MsgBox function project
A built-in VBA function that governs how a The VBE representation of a set of relation-
message box is displayed. ships that exist among the parts of an open
Excel workbook.
Name property
An Excel VBA property that contains text property
data representing the name of the object using A set of built-in storage locations to keep
it. track of, work with, and affect the characteris-
tics of the worksheet component to which it
Object-Oriented Programming
refers.
A programming method that focuses on mod-
eling entities and their interactions. public function
A function that can be shared by multiple
projects.

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.

174 Microsoft® Office Excel® 2007 - VBA


INDEX

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

176 Microsoft® Office Excel® 2007 - VBA

You might also like