2007-vba - advanced technology support, inc® officeexcel® 2007-vba course ... advanced microsoft...

182
Microsoft ® Office Excel ® 2007 - VBA 3424IGEE DO NOT DUPLICATE Instructor Edition

Upload: doananh

Post on 09-May-2018

242 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Microsoft® Office Excel® 2007 - VBA

3424IGEE

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 2: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Microsoft® Office Excel® 2007VBA

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 3: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Microsoft® Office Excel® 2007 - VBA

Course Edition: 1.0

ACKNOWLEDGMENTS

Project TeamContent Developer: Mariya Mubarak and Theophilus Benjamin • Content Manager: Pradeep PM • Graphic Designer: GaneshKumar B • Project Manager: Yogesh Aravindhakshan • Media Instructional Designer: Bhoopathy R • Content Editor: VanithaKesavan • Materials Editor: Banupriya • Project Quality Support: Shobana T.S • Technical Reviewer: • Project TechnicalSupport: Mike Toscano

NOTICESDISCLAIMER: 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 warrantywhatsoever, 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. Anyresemblance 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 inthe 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 ofthe 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 isnot 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 MicrosoftCorporation. 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 notbe 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 writtenpermission 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 atwww.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 andconditions 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 withoutpermission, please call (800) 478-7788.

Microsoft® Office Excel® 2007 - VBAii

Part Number: 3424IGEE

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 4: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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

Contents iii

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 5: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

LESSON 2 - FORMATTING WORKSHEETS USING MACROS

A. Insert Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

The Selection Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

The ActiveSheet Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

The Name Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

The Value Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

B. Format Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

C. Sort Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

The Range Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

The Select Method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

The CurrentRegion Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

D. Duplicate Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

Variable Naming Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

The Assignment Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

Arithmetic Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

The For Next Loop. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

The Do Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

The Worksheets Collection Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

The Count Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54

The Offset Property. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

The Copy Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

The Paste Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

CONTENTS

Microsoft® Office Excel® 2007 - VBAiv

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 6: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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

Contents v

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 7: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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

GLOSSARY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169

CONTENTS

Microsoft® Office Excel® 2007 - VBAvi

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 8: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

ABOUT THIS COURSEIn the previous Excel courses, you used Excel to simplify business tasks, including the creationof spreadsheets, graphs, charts, and formulas that were difficult to create and nearly impossibleto 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 languageto simplify many of the tasks that you can perform using various tools and functions in Excel2007.

Creating similar spreadsheets with different data from scratch, each and every day, for everyreport 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 largequantities of spreadsheets.

Course DescriptionTarget StudentAdvanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks usingVisual Basic for Applications (VBA).

Course PrerequisitesKnowledge of Microsoft® Office Excel® 2007, including how to create, edit, format, and printworksheets 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®

® Offıce Excel® ® Offıce Excel®

Level 3.

INTRODUCTION

Introduction vii

2007 - Level 2, and Microsoft 2007 -2007 - Level 1, Microsoft DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 9: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

How to Use This Book

As a Learning GuideEach lesson covers one broad topic or a set of related topics. Lessons are arranged in the orderof increasing proficiency with Microsoft® Offıce Excel® 2007; skills you acquire in one lessonare used and developed in the subsequent lessons. For this reason, you should work throughthe 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 allowyou 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 typingtime 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 learnMicrosoft® Offıce Excel® 2007 quickly and easily.

As a Review ToolAny method of instruction is only as effective as the time and effort you are willing to investin it. In addition, some of the information that you learn in class may not be important to youimmediately, but it may become important later on. For this reason, we encourage you tospend 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 “HowYou Do It” column.

As a ReferenceThe organization and layout of the book makes it easy to use as a learning tool and as anafter-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 ObjectivesIn 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.

INTRODUCTION

Microsoft® Office Excel® 2007 - VBAviii

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 10: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Course Requirements

HardwareFor 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 useVista, you might notice some minor differences in the interface when keying the course.

• Microsoft® Office 2007 Professional Enterprise Edition

Class Setup

For Initial Class Setup1. 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 useraccounts exist on the computer.) Choose Start→Control Panel→User Accounts. ClickChange The Way Users Log On And Off. Uncheck Use Welcome Screen. Click ApplyOptions.

3. In Windows XP Professional, install Service Pack 2. Use the Service Pack installationdefaults.

4. For Windows XP Professional, choose Start→Settings→Printers to install a printerdriver (a physical print device is optional). Run the Add Printer wizard and follow theprompts.

INTRODUCTION

Introduction ix

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 11: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

5. Verify that file extensions are visible.

6. Run the Internet Connection wizard to set up the Internet connection as appropriate foryour 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. Thefiles will be extracted to the C:\084037Data folder.

Before Every Class1. 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 coursemanual.

List of Additional FilesPrinted 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 thecourse CD-ROM or data disk. Do not delete these files.

INTRODUCTION

Microsoft® Office Excel® 2007 - VBAx

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 12: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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 Time1 hour(s), 50 minutesLESSON 1

LESSON 1

Lesson 1: Developing Macros 1

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 13: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

IntroductionWhile 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 thingsyou might not have known were possible. Macros help save time and expand the capabilitiesof Excel.

TOPIC ACreate a Macro with the MacroRecorderYou 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 MacroRecorder. In this topic, you will automate procedure steps, so that the number of steps requiredto complete a task is dramatically reduced.

It is easy to see that the idea of automating repetitive tasks in Microsoft Office Excel is a goodone. Excel uses Visual Basic for Applications (VBA) programming to accomplish this. Butwhat 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 byrecording actions as you perform them.

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

Object-Oriented ProgrammingObject-Oriented Programming is a methodology where all entities are treated as objects. Theseobjects 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 depositsand withdrawals that control the bank account can be treated as behaviors. Object-OrientedProgramming works by assembling various objects, their features, and their interactions to cre-ate an application.

LESSON 1

Microsoft® Office Excel® 2007 - VBA2

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 14: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

MacrosDefinition:

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 canuse the macro recorder to record a sequence of actions, and then perform these tasksby using the macro name or a simple command assigned to the macro. The commandsin the recorded macro are converted into programming code that can be edited ifrequired.

Example:

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

Figure 1-1: The Macro dialog box.

Option DescriptionRun Executes the macro.

Step Into Allows you to start the VBA Editor.

Edit Allows you to make changes to the macro.

Macros

Macro Options

LESSON 1

Lesson 1: Developing Macros 3

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 15: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Option DescriptionCreate 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 RecorderThe Macro Recorder is an Excel tool that you can use to create a macro. It translates themanual actions you perform in a workbook into a series of VBA commands that are saved in amacro.

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

Macro Naming ConventionsThere 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 nameerror message.

Relative ReferencesIf you are using formulas frequently, these formulas are repeatable or extendable toother rows or columns, which can be done by AutoFill.

The Macro Recorder

LESSON 1

Microsoft® Office Excel® 2007 - VBA4

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 16: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Personal Macro WorkbookA Macro Personal Workbook is a storage location in the Excel application where you cancreate and save macros. Once created, the macros stored in the Personal Macro Workbook canbe 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 RecorderProcedure 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 Developertab 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 RecordMacro 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 whereyou 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.

Personal Macro Workbook

LESSON 1

Lesson 1: Developing Macros 5

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 17: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

2. In the Macro dialog box, select the macro you want to run.

3. Click Run to run the macro.

ACTIVITY 1-1Recording 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 Ribboncheck 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 allmacros (not recommended; potentially dangerous code can run) option, and close theTrust 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 otherdepartments. The look and feel of the reports are different. Some use the Times New Romanfont and some use the Courier font. You decide to create macros to implement font changes tothe worksheet.

What You Do How You Do It

1. Enter the identifying characteristicsfor a new macro namedfont2TimesNewRoman, using theRecord Macro dialog box.

a. On the Developer tab, in the Code group,click Record Macro, to dis-play the Record Macro dialog box.

b. In the Macro name text box, typefont2TimesNewRoman

c. From the Store macro in drop-down list,select Personal Macro Workbook.

d. In the Description text box, click andtype This macro changes the font forthe entire worksheet to Times NewRoman.

LESSON 1

Microsoft® Office Excel® 2007 - VBA6

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 18: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

2. Record a macro that changes the fontstyle for the entire worksheet toTimes New Roman.

a. Click OK to start the Macro Recorder.

b. On the worksheet, to the left of the Col-umn A heading, click the Select All buttonto select the entire worksheet.

c. On the Home tab, in the Font group, fromthe Font drop-down list, scroll down andselect 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 characteristicsfor a new macro named font2Courier,using the Record Macro dialog box.

a. In the Code group, click Record Macro todisplay the Record Macro dialog box.

b. In the Macro name text box, typefont2Courier

c. Verify that Personal Macro Workbook isselected in the Store macro in drop-downlist.

d. In the Description text box, click andtype This macro changes the font forthe entire worksheet to Courier.

4. Record a macro that changes the fontstyle for the entire worksheet toCourier.

a. Click OK to start the Macro Recorder.

b. On the worksheet, to the left of the Col-umn A heading, click the Select All buttonto select the entire worksheet.

c. On the Home tab, in the Font group, fromthe Font Selection drop-down list, scrollup 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

Lesson 1: Developing Macros 7

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 19: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

5. Run the font2TimesNewRoman macroto change the worksheet back toTimes New Roman.

a. In the Code group, click Macros to displaythe Macro dialog box.

b. In the Macro dialog box, in the Macro

name list box, selectPERSONAL.XLSB!font2TimesNewRoman.

c. Click Run to run the macro.

6. Run the font2Courier macro tochange the worksheet to Courier.

a. In the Code group, click Macros.

b. In the Macro dialog box, verify that thePERSONAL.XLSB!font2Courier macro isselected.

c. Click Run to run the macro.

7. Save the file as My RecordMacro.xlsm and then close the file.

a. Choose File→Save As.

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 typeMy Record Macro and click Save.

e. Close the file.

LESSON 1

Microsoft® Office Excel® 2007 - VBA8

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 20: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

TOPIC BEdit a MacroYou have recorded a basic macro that automates several steps that a user may perform in theExcel environment. Many times a recorded macro will suit your needs, but sometimes youmay 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, includingmodifying the font of a row to be red. Now imagine that you wanted to perform the samesteps, but format the same row to be blue. Instead of recording a new macro, you can modifythe existing macro. Editing a macro modifies an existing macro without the extra steps ofrecording a new one.

Visual Basic EditorVisual Basic Editor (VBE) is a part of the Excel application where you can create, edit, anddelete 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 DescriptionProject Explorer A tree-like navigation tool similar to Windows

Explorer that enables you to access stored macrocode.

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 theVBA language.

Although a useful tool for advanced VBA programmers, the Object Explorer is beyond the scope of this course.

Visual Basic Editor

LESSON 1

Lesson 1: Developing Macros 9

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 21: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

ProjectsA project is a VBE representation of a set of relationships that exist among the parts of anopen Excel workbook. Viewed in Project Explorer, projects are depicted in a hierarchic, treestructure similar to the file and folder structures viewed in Windows Explorer.

ModulesDefinition:

A module is a project entity that stores macro code. It is similar to a text file. Whenopened, 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 FolderThe Modules folder is the location in a project where macro code is stored. When opened, theModules folder displays at least one module.

ObjectsDefinition:

An object is a programming language component that, for the most part, mimics thecharacteristics and behaviors of the components in an Excel workbook. Objects areuniquely named and represent an element of an application such as a cell, a chart, aform, or a report.

Modules

Objects

LESSON 1

Microsoft® Office Excel® 2007 - VBA10

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 22: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Example:

PropertiesDefinition:

A property is a set of built-in storage locations that affects the characteristics of theworksheet component to which it refers. It keeps track of work and functions with theworksheet component. The components can be size, color, or screen location.

Example:

MethodsDefinition:

A method is a set of short programs whose action changes the referenced worksheetcomponent. Methods are built-in programs. Methods can be associated with a particu-lar object or class.

Properties

Methods

LESSON 1

Lesson 1: Developing Macros 11

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 23: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Example:

VBA CommentsDefinition:

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 onwhat 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 toignore the line because it contains no VBA code.

Example:

How to Edit a MacroProcedure Reference: Edit a Macro

To edit a macro:

1. On the Developer tab, click Visual Basic to open Visual Basic Editor.

VBA Comments

LESSON 1

Microsoft® Office Excel® 2007 - VBA12

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 24: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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, selectthe name of the macro you want to display.

5. If necessary, scan the code block until you find its end, denoted with the codeEnd 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-2Editing 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 nowgo out in the Verdana font. Rather than starting over, you decide to edit the macro, so thatinstead of Courier, it changes the worksheet font to Verdana.

LESSON 1

Lesson 1: Developing Macros 13

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 25: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

What You Do How You Do It

1. Modify the font2Courier macro’s codeand commenting so that it now for-mats the worksheet with the Verdanafont.

a. Select Macros, and from the Macro name

list box, select font2Courier, and clickEdit to locate the code block starting withthe code Sub font2Courier().

b. If necessary, maximize the code blockuntil you find its end, denoted with thecode End Sub.

c. In the Microsoft Visual Basic Editor,change the macro’s name to“font2Verdana”.

d. In the commenting lines, change the wordCourier to Verdana.

e. In the Sub font2Verdana macro, below theCells.Select statement, delete With.

f. In the Sub font2Verdana macro, below.Name = “Courier” delete the lines ofcode from Strikethrough to EndWith.

g. Move the font name assignment statementso that it becomes part of the previousline of code.

h. In the font name assignment statement,replace Courier with Verdana.

If necessary, see the completed code block atthe end of this activity.

LESSON 1

Microsoft® Office Excel® 2007 - VBA14

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 26: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

2. Test the edited macro. a. Choose File→Close and Return to

Microsoft Excel.

b. On the worksheet, run the font2Verdanamacro.

c. If the worksheet text does not change tothe Verdana font, open the MicrosoftVisual Basic Editor, modify your edits, andretest.

See Code Sample 1.

d. Save the file as My Edit Macro.xlsm andclose it.

Code Sample 1

' The completed edits to font2Verdana:

Sub Font2Verdana()'' Font2Verdana Macro' This macro changes the worksheet to Verdana font.''

Cells.SelectSelection.Font.Name = "Verdana"Range("A1").Select

End Sub.

LESSON 1

Lesson 1: Developing Macros 15

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 27: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

TOPIC CDebug a MacroYou have modified a macro in the VBA editor. Sometimes, you may encounter instances whereyour 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 thatyou 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 yourVBA code that is causing an unexpected result.

The Debugging ProcessThe debugging process is the means by which you can identify, locate, and fix errors in macrocode.

1. The application environment is set up so that both the macro code and the worksheet itacts 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 theerror.

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.

The Debugging Process

LESSON 1

Microsoft® Office Excel® 2007 - VBA16

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 28: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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

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

Code GroupsA 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 toaccomplish part of a complex task.

How to Debug a MacroProcedure 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 macrocode is stored.

2. Above the Code editing window, from the Macro name drop-down list, selectthe 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 VBAcode.

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.

Debugging Tools

LESSON 1

Lesson 1: Developing Macros 17

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 29: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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 backupcopy.

4. On the Debug toolbar, click Reset.

5. If necessary, above the Code editing window, from the Macro name drop-downlist, 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 acode block.

2. If necessary, review the results of the executed line of code.

ACTIVITY 1-3Debugging 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 thatcalls 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.

LESSON 1

Microsoft® Office Excel® 2007 - VBA18

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 30: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

What You Do How You Do It

1. Review the final product dataexample and then prepare an easy-access raw data backup.

a. Select the End Product worksheet.

b. Select the Original Data worksheet toview the raw data, after reviewing theEnd Product worksheet.

c. On the Home tab, from the Insert drop-down menu, choose Insert Sheet tocreate a third worksheet to hold a copy ofthe original data.

d. Right-click the new worksheet’s tab, andthen choose Rename to select theworksheet tab’s text.

e. Type Backup as the name of the newworksheet.

f. Select the Original Data worksheet.

g. Select all the cells in the worksheet.

h. Click Copy to copy the worksheet data tothe Clipboard.

i. Select the Backup worksheet.

j. Click Paste to paste the data from theOriginal Data worksheet.

k. Select cell A1 to deselect the worksheetcells.

LESSON 1

Lesson 1: Developing Macros 19

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 31: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

2. Modify the display of the worksheetand the VBE code editor to view howthe worksheet is affected as youdebug the code.

a. Resize the application window so that ittakes up the left half of the screen.

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 editingwindow takes up the entire viewing area.

d. Resize the Microsoft Visual Basic Editorwindow so that it takes up the right halfof the screen.

e. In the Microsoft Visual Basic Editor win-dow, choose View→Toolbars→Debug todisplay the Debug toolbar.

f. Position the Debug toolbar so that itfloats in the left window away from thedata in a blank area of the worksheet.

3. Run the CreateReport macro to get ageneral idea of where the problemsare.

a. Click the View Microsoft Excel button.

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 theCreateReport macro is selected and clickRun.

e. Click the Microsoft Visual Basic Editortitle 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 viewthe correctly formatted data.

i. Select the Original Data worksheet.

LESSON 1

Microsoft® Office Excel® 2007 - VBA20

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 32: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

4. Reset the data in the Original Dataworksheet.

a. Display the Backup 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 theOriginal Data worksheet.

g. Select cell A1 to deselect the worksheetcells.

5. Step through the CreateReport macrocode until you find the first error.

a. Click the Microsoft Visual Basic Editortitle bar.

b. In the Microsoft Visual Basic window,verify that the CreateReport macro codeis selected.

c. On the Debug toolbar, click Step Into,

five times to execute the first fivelines of code.

d. Observe the rows that are selected in theworksheet.

6. Edit the code so that it selects thefirst four rows of the worksheet.

a. In the line of code immediately above theyellow highlighted code, place the inser-tion point between 2 and the colon.

b. Press Backspace.

c. Type 1

LESSON 1

Lesson 1: Developing Macros 21

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 33: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

7. Test the result of the edit. a. Place the insertion point within the yellowhighlighted code.

b. On the Debug toolbar, click Toggle

Breakpoint, to set a breakpoint atthe 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 previouslystepped through code up to thebreakpoint.

e. Click Step Into to execute the line of codeat the breakpoint.

f. Place the insertion point within thebreakpoint code.

g. On the Debug toolbar, click Toggle

Breakpoint to remove the breakpoint.

8. Progress through the code until youfind the next error.

a. Click Step Out, to run the rest of thecode in the InsertRowsCols macro.

b. Click Step Into four times.

9. Debug the error. a. Scroll down, and in the InsertTxt macrocode, place the insertion point in thestatement Range("A2").Select.

b. Click Toggle Breakpoint to set abreakpoint.

c. In the range selection statement thatselects cell A10, modify the code so thatcell A1 is selected.

d. Click Reset to reset the InsertTxt macro.

e. Click Run Sub/UserForm to run the codeto the breakpoint.

LESSON 1

Microsoft® Office Excel® 2007 - VBA22

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 34: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

10. Run through the rest of the code forthe InsertTxt macro.

a. Verify that the insertion point is withinthe line of code containing thebreakpoint.

b. Click Toggle Breakpoint to remove thebreakpoint.

c. Click Step Out to execute the rest of thecode in the InsertTxt macro.

d. In the Microsoft Visual Basic Editor win-dow, click the View Microsoft Excel

button.

LESSON 1

Lesson 1: Developing Macros 23

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 35: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

11. Cross-check your work by running theInsertRowsCols and InsertTxt macrocodes.

a. Select the Backup worksheet.

b. Verify that all the cells on the worksheetare 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 Editortitle 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 toexecute all the codes.

m. Choose File→Close and Return to

Microsoft Excel.

n. In the Microsoft Visual Basic messagebox, click OK.

o. Save the file as My DebuggingExample.xlsm and close it.

LESSON 1

Microsoft® Office Excel® 2007 - VBA24

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 36: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

TOPIC DCustomize the Quick Access Toolbarand HotkeysYou have created a macro. Now, you want to create shortcuts to quickly run the macros. Inthis topic, you will create these shortcuts by customizing Excel’s Quick Access toolbar, andassign hotkeys to the macros you have created.

If you are used to working with GUI software applications, then you are undoubtedly familiarwith common conventions such as buttons, menus, and keyboard shortcuts. Excel gives youthe opportunity to incorporate these conventions into your macro development. Customizingthe Excel Quick Access toolbar, or assigning hotkeys to macros provides a number of simplechoices for running macros.

How to Customize the Quick Access Toolbar andHotkeysProcedure 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 Toolbardrop-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 macroon 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 QuickAccess 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 nameof 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

Lesson 1: Developing Macros 25

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 37: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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-4Customizing 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 theywould be easily visible and in a convenient location.

What You Do How You Do It

1. Customize the Quick Access toolbarusing the Excel Options dialog box.

a. Click the Microsoft Office button andthen click Excel Options.

b. In the Excel Options dialog box, click theCustomize category.

c. From the Choose commands from drop-down list, select Macros.

d. From the Macro name list box, selectfont2Arial and click Add.

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

2. Add the font group and the cellsgroup to the Quick Access toolbarusing the right-click option.

a. On the Home tab, right-click Font.

b. Click Add to Quick Access Toolbar.

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

d. Click Add to Quick Access Toolbar.

LESSON 1

Microsoft® Office Excel® 2007 - VBA26

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 38: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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

b. In the Macro name list box, verify thatthe font2Arial macro is selected and clickOptions.

c. In the Macro Options dialog box, in theShortcut key text box, type m and clickOK.

d. Close the Macro dialog box.

e. On the keyboard, hold down Ctrl andpress m.

f. Observe that the macro is executed.

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

TOPIC EWork with Macro SecurityYou have created macros in Excel. You now need to protect the macros. In this topic, you willwork with macro security.

You have developed a macro, which is to be used by other staff in your office. By protectingyour macro with appropriate security settings you can ensure the integrity of the macro.

Digital CertificatesDefinition:

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 issuingauthority, expiration date, a name, and a copy of the certificate holder’s public key sothat 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’scomputer service professional. A digital certificate is also known as a digital IDbecause it is used to digitally sign a document.

Digital Certificates

LESSON 1

Lesson 1: Developing Macros 27

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 39: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Example:

Digital SignaturesDefinition:

A Digital Signature is a content authentication tool that authenticates the originator ofa 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 contentsof 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 beendigitally signed. When you open a document with a digital signature, the details willbe visible in the Signatures pane of your workbook. Users cannot make modificationsto a digitally signed document until the signature is removed.

Example:

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

Digital Signatures

LESSON 1

Microsoft® Office Excel® 2007 - VBA28

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 40: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Option DescriptionDisable 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 youto choose which macros to run.

Disable All Macros Except Digitally SignedMacros

Disables all macros except those that are digitallysigned by a trusted publisher.

Enable all Macros (Not Recommended, Poten-tially Dangerous Code Can Run)

Enables all macros in the workbook to run. Thislowers the security of the computer, making it vul-nerable to malicious code. This option is notrecommended 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 VisualBasic objects, methods, and properties. This optionis for developers only, as it poses a security haz-ard.

How to Work with Macro SecurityProcedure Reference: Add a Digital Signature

To add a digital signature:

1. On the Insert tab, from the Signature Line drop-down menu, choose MicrosoftOffice 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 clickOK.

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

Lesson 1: Developing Macros 29

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 41: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

14. In the Signature Confirmation message box, click OK.

15. In the Signatures pane, view the digital signature and the certificate icons on theMicrosoft 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-5Setting 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 takeadequate security measures so that your workbook’s security is set as desired. Before you dothis, you would also add a digital signature to the document to authenticate it.

LESSON 1

Microsoft® Office Excel® 2007 - VBA30

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 42: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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 messagebox, click OK.

c. In the Signature Setup dialog box, in theSuggested 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 messagebox, click OK.

i. In the Get a Digital ID dialog box, selectCreate your own digital ID and click OK.

j. In the Create a Digital ID dialog box, inthe Name text box, double-click and typePat Smith

k. In the E-mail address text box, click andtype [email protected]

l. In the Organization text box, click andtype OGC

m. In the Location text box, click and typeNY

n. Click Create.

o. In the Sign dialog box, in the Signature

text box, type Pat Smith

p. Click Sign.

LESSON 1

Lesson 1: Developing Macros 31

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 43: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

q. In the Signature Confirmation messagebox, click OK.

r. Observe that the signature is displayed inthe 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 theDisable 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-upIn this lesson, you created, edited, and debugged a macro, customized the Quick Accesstoolbar and worked with macro security. These skills will help you automate repetitive tasks inExcel, saving time and expanding the capabilities of Excel.

1. Do you think that the Macro Recorder is a useful tool? Why or why not?

Answers will vary, but the Macro Recorder tool is highly useful, because it can generateVBA code faster than typing by hand.

2. How does the Personal Macro Workbook relate to the creation and use of customtoolbars, buttons, and menus?

Answers will vary, but you can save macro code into the Personal Macro Workbook so thatit can be used whenever you have cause to use the custom tools. Otherwise, the macrocode would be locked away in a closed Excel workbook, which might be deleted, causingthe custom tools to become useless.

LESSON 1

Microsoft® Office Excel® 2007 - VBA32

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 44: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Formatting WorksheetsUsing Macros

In this lesson, you will format worksheets using macros.

You will:

• Insert text.

• Format text.

• Sort data.

• Duplicate data.

• Generate reports.

Lesson Time1 hour(s), 35 minutesLESSON 2

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 33

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 45: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

IntroductionYou have recorded macros as a simple way to create VBA code in an Excel worksheet. Whilerecorded macros are certainly simple to create, additional flexibility can be gained by enteringthe 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 thesame kind of formatting to different documents. This becomes absolutely tedious at one pointand you realize that automating the formatting tasks will save you a lot of time. ApplyingVBA reduces the number of steps required to repetitively apply formatting to a worksheet.

TOPIC AInsert TextYou know how to manually enter text into a worksheet. There may be times when you wanttext to frequently appear in the worksheet. In this topic, you will store text in a macro andautomatically insert it into a worksheet.

If you have ever created worksheets that required you to type the exact same text into cellsseveral times in a worksheet, then you know how frustrating the repetition could be. ApplyingVBA allows you to create macros to insert frequently used text without requiring the user tomanually enter the text into the worksheet.

The Selection ObjectDefinition:

The Selection object is an Excel VBA object that represents a currently selected part ofthe worksheet, such as a cell, column, or range. It is often used one line below macrocode 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 byan attached property or method.

The Selection Object

LESSON 2

Microsoft® Office Excel® 2007 - VBA34

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 46: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Example:

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

The ActiveSheet ObjectDefinition:

The ActiveSheet is an Excel VBA object that represents the currently active worksheetin the workbook. Like the Selection object, the ActiveSheet object can be usedin different contexts, but it refers only to the currently selected worksheet. By thisarrangement, you need to first enter the ActiveSheet command, followed by anattached property or method.

Example:

The ActiveSheet Object

Technically, theActiveSheet object is aproperty of the Workbookobject.

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 35

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 47: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

The Name PropertyDefinition:

The Name property is an Excel VBA property that contains text data representing thename 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 whenthe Name command is attached with a period to an object name.

Example:

The Value PropertyDefinition:

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

Example:

The Name Property

The Value Property

LESSON 2

Microsoft® Office Excel® 2007 - VBA36

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 48: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

ConcatenationDefinition:

Concatenation refers to the act of connecting two or more pieces of text informationtogether 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 TextProcedure 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 theworksheet’s name is to be located, erase the string data.

2. In its place, type ActiveSheet.Name.

Concatenation

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 37

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 49: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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

'Inserting the worksheet name into a cell:

'Original code:

Range("CellAddr").SelectSelection.Value = Name of the worksheet

Modified code:

Range("CellAddr").SelectSelection.Value = ActiveSheet.Name & " Portfolio"

ACTIVITY 2-1Inserting 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 theboilerplate 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 amacro named InsTxt.

a. Select the Conservative worksheet.

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.

LESSON 2

Microsoft® Office Excel® 2007 - VBA38

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 50: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

2. Insert the report title and headers forthe stock price data on theworksheet.

a. In cell A1, type OGC Investment Advisors

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 pressEnter.

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

ing button.

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 39

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 51: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

3. Edit the InsTxt macro code so thatthe worksheet’s name is assigned toa cell.

a. In the Code group, click Macros.

b. In the Macro dialog box, select the InsTxt

macro and click Edit.

c. If necessary, maximize the Visual BasicEditor and position the Debug toolbar inthe blank area.

d. In the InsTxt macro code, scroll down, andunder the code line that selects cell B4, inthe ActiveCell.FormulaR1C1 state-ment, delete "Conservative".

e. Type ActiveSheet.Name and press theSpacebar.

f. Type & to enter the ampersand concat-enation character and then press theSpacebar.

g. Type " Portfolio"

See Code Sample 1.

h. Close the Visual Basic Editor.

Code Sample 1

'The altered code:

Range("B4").SelectActiveCell.FormulaR1C1 = ActiveSheet.Name & " Portfolio"

4. Run the InsTxt macro on theworksheets.

a. In the workbook, select the Balanced

worksheet.

b. In the Code group, click Macros.

c. Select InsTxt and click Run to run theInsTxt macro on the Balanced worksheet.

d. Run the InsTxt macro on the Conservativeworksheet.

e. Run the InsTxt macro on the Aggressiveworksheet.

LESSON 2

Microsoft® Office Excel® 2007 - VBA40

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 52: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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 andchoose 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 typeMy Balance Sheet and click Save.

DISCOVERY ACTIVITY 2-2Understanding 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 oftext information together with an ampersand to form a single, longer piece of text.

✓ True

False

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 41

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 53: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

TOPIC BFormat TextYou know how to format text manually. Using VBA, the text that you want to modify can beformatted 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 involvequite a few steps. Applying VBA reduces the number of steps required to repeatedly formattext.

How to Format TextProcedure 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-3Formatting 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 theheader text differently from the body text so that it is easy to distinguish between the two.

LESSON 2

Microsoft® Office Excel® 2007 - VBA42

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 54: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

What You Do How You Do It

1. Start the Macro Recorder to record amacro named FmtTxt.

a. Select the Conservative worksheet.

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 thencomplete the macro recording.

a. Click cell A1, and on the Home tab, in theFont group, from the Font Size drop-down list, select 18.

b. In the Font group, click the Bold buttonto boldface the title.

c. Format cell A2 with a font size of 14 andbold it.

d. Format cell B4 with a font size of 14 andbold it.

e. Format the range B6:E6 with a font size of12 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

Lesson 2: Formatting Worksheets Using Macros 43

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 55: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

3. Run the FmtTxt macro on the otherworksheets.

a. Select the Balanced worksheet.

b. On the Developer tab, click Macros, andin the Macro dialog box, click Run to runthe FmtTxt macro.

c. Run the FmtTxt macro on the Aggressiveworksheet.

d. Save the file and close it.

TOPIC CSort DataYou 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 willcreate 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 theirquarterly test averages contained in columns. You decide to change the order of the students sothat the student with the highest average in the fourth quarter is displayed at the top of theworksheet. Excel’s default sorting behavior would change the order of the grades only in thefourth quarter column without affecting the remaining rows. This breaks the relationshipbetween the data and causes the information to be inaccurate. Applying VBA allows multiplerelated rows and columns to be sorted together.

The Range ObjectDefinition:

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

The Range Object

LESSON 2

Microsoft® Office Excel® 2007 - VBA44

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 56: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Example:

The Select MethodDefinition:

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

Example:

The CurrentRegion PropertyDefinition:

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

The Select Method

The CurrentRegion Property

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 45

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 57: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Example:

How to Sort DataProcedure 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 codeblock generated by the Macro Recorder, enter the code necessary to select a cellwithin 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

LESSON 2

Microsoft® Office Excel® 2007 - VBA46

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 58: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

ACTIVITY 2-4Sorting 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 ofthree stock portfolios. The portfolio components vary over time, causing the sizes of the rangesholding the price information to vary. You start coding a report builder by sorting the originaldata.

What You Do How You Do It

1. Display the code for SortLastColmacro that performs a descendingsort on the last column of a selectedrange.

a. Display the Macro dialog box.

b. Select the SortLastCol macro and clickEdit to display the code in Visual BasicEditor.

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 47

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 59: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

2. Edit the macro so that it selects arange of unknown row length.

a. In Visual Basic Editor, in the SortLastColmacro, at the beginning of the codeblock, type Range("A1").Select toselect cell A1 within the range of cells tobe sorted.

b. Press Enter.

c. TypeActiveCell.CurrentRegion.Selectto select the entire range in which thecell 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").SelectActiveCell.CurrentRegion.SelectSelection.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 twoworksheets.

a. In the workbook, select the Balanced

worksheet.

b. Run the SortLastCol macro to sort thedata.

Verify that This Workbook is selected to displaythe macro.

c. Select the Aggressive worksheet.

d. Run the SortLastCol macro to sort thedata.

e. Run the SortLastCol macro on the Conser-vative worksheet.

LESSON 2

Microsoft® Office Excel® 2007 - VBA48

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 60: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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 DDuplicate DataYou know how to manually copy and paste data in a worksheet. Using VBA, the text that youwant to copy and paste can be duplicated automatically by applying a macro. In this topic, youwill 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 stepsto select, copy, and paste data. Applying VBA reduces the number of steps required to dupli-cate data in a worksheet.

Data TypesDefinition:

Data types refer to text, numeric, and true/false data you work with when creatingmacros to process information. The String data type refers to text; the Integer datatype, to positive and negative whole numbers; and the Boolean data type, to true/falseor yes/no logical values.

Example:

Data Types

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 49

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 61: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

VariablesDefinition:

Variables are named locations that you can create and use in a macro to temporarilystore data when the macro runs. Once stored in a variable, a data value continues toexist in the variable until a new data value “writes over” the old one in subsequentcode, or the macro that created the variable stops running. When using variables, amacro module must first be defined with the Option Explicit declaration at thebeginning of the list of macros; each macro in the list must then declare the variablesit uses with the Dim As command, which defines the data type allowed, before theycan be used.

Example:

Types of VariablesVariables come in two forms:

• Weakly typed variables can hold any data type and are created in the macro whenthe code that first uses them is run.

• Strongly typed variables can hold only one data type and must be created, ordeclared before they are used. Attempting to store the wrong data type in astrongly typed variable creates an error, which causes the macro to cease before itcan complete its work.

Variable Naming RulesVariable 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, orpound 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

Variables

LESSON 2

Microsoft® Office Excel® 2007 - VBA50

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 62: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

• Revenue1999

• x

Examples of incorrectly named variables:

• 1999Revenue

• Mary Smith

• House.Mary

• ActiveSheet

OperatorsDefinition:

Operators are symbols you use to carry out tasks between two operands. These taskscan include performing arithmetic, comparing two numbers, assigning data to aworksheet cell, or answering questions of logic.

Example:

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

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

Operators

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 51

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 63: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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 OperatorsComparison operators are used to evaluate data to true or false to check whether a datavalue 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 onits left; false, otherwise.

>= (Greater than or equalto)

Returns a true value if the number on its left is larger or the same as thenumber on its right; false, otherwise.

<= (Less than or equalto)

Returns a true value if the number on its right is larger or the same as thenumber 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 OperatorsLogical operators compare two or more true/false values.

Name PurposeAND 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.

LESSON 2

Microsoft® Office Excel® 2007 - VBA52

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 64: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

The For Next LoopDefinition:

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, theNext command, which marks the end of the loop, and a criterion placed just afterFor that evaluates an incrementing integer variable called a counter variable, theFor Next loop repeats the lines of VBA code placed within the loop until the size ofthe counter variable is larger than an allowed value.

Example:

The Do LoopDefinition:

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 Loopcommand, which marks the end of the loop, and the While command, containing anevaluative criterion placed just after Do or Loop, the Do loop repeats the lines ofVBA code placed within the loop until the While criterion is evaluated to a Booleanvalue of false.

Example:

The For Next Loop

The Do Loop

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 53

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 65: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

The Worksheets Collection ObjectDefinition:

The Worksheets collection object is an Excel VBA object that manages the collectionof 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 enteringcode related to each worksheet.

When used, the Worksheets command, followed by a pair of parentheses holding anumeric expression that evaluates to an integer, causes the Worksheetscollection object to refer to the worksheet whose position in the worksheet list isthe same as the numeric expression; the name of the worksheet can also be used.

Example:

The Count PropertyDefinition:

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 currentlyactive workbook.

When used, the Count command is attached with a period to the end of theWorksheets collection object reference.

The Worksheets CollectionObject

The Count Property

LESSON 2

Microsoft® Office Excel® 2007 - VBA54

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 66: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Example:

The Offset PropertyDefinition:

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 apair of parentheses containing a comma-separated pair of integer values that determinea distance, in cells, from the active cell, is attached with a period to the ActiveCellobject.

Example:

Measuring DistancesPositive coordinate values designated in the Offset property indicate that the offsetlocation is either below or to the right of the currently active cell; negative coordinatevalues indicate that the offset location is either above or to the left.

The Offset Property

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 55

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 67: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

The Copy MethodDefinition:

The Copy method is a method of the ActiveSheet object. Using it, you can copycurrently 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 MethodDefinition:

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

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

The Copy Method

The Paste Method

LESSON 2

Microsoft® Office Excel® 2007 - VBA56

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 68: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

How to Duplicate DataProcedure 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 incompletemight appear; ignore the message.

1. Type For.

2. Press Enter at least twice to provide blank lines where repeating code will beentered.

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

Lesson 2: Formatting Worksheets Using Macros 57

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 69: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

6. In the For statement, after the counter variable name, type the equals sign andthen 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").SelectActiveCell.CurrentRegion.SelectSelection.CopyWorksheets(Name of the worksheet).SelectRange("CellAddr").SelectActiveSheet.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 theSelect method to select the new active cell.

a. Type ActiveCell.Offset().Select.

b. Within the parentheses of the Offset property, enter a numeric value tooffset 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

LESSON 2

Microsoft® Office Excel® 2007 - VBA58

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 70: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

ACTIVITY 2-5Duplicating 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 managerexpresses her wish to view the work-in-progress. She wants you to include a fourth page in theworkbook that contains all the three portfolios. Hesitant to alter your existing work, you goback to the drawing board with the original data to explore how to duplicate data ranges fromone worksheet to another.

What You Do How You Do It

1. Enter the code necessary to declarethe variable x as an integer.

a. Display the Macro dialog box.

b. In the Macro dialog box, verify that theDuplData is selected and click Edit.

c. In Visual Basic Editor, in the code editingwindow, above the Sub DuplData state-ment, type Option Explicit and thenpress Enter.

d. In the DuplData macro, type Dim x AsInteger to declare x as the variable,with integer as the data type and thenpress Enter.

See Code Sample 1.

Code Sample 1

Option Explicit____________________

Sub DuplData()

Dim x As Integer

End Sub

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 59

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 71: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

2. Enter the code that marks the begin-ning and end of a For Next loopstructure.

a. Type For

Ignore the debugging warning messages.

b. Press Enter three times to provide blanklines where repeating code will beentered.

c. Type Next

3. Add x as the counter variable used tocount the number of times the loopshould run.

a. Click at the end of the For statement,add a space, and then type x after theword For.

b. In the Next statement, add a space andtype x after the word Next.

4. Indicate the number of times thecode in the loop should run should beone less than the total number ofworksheets in the workbook, usingthe Worksheet object and its Countproperty.

a. In the For statement, after the x countervariable name, type an equals sign fol-lowed by a space.

b. Type 1 as the starting value for the xcounter variable followed by a space.

c. Type To followed by a space.

d. Type Worksheets.Count - 1 as theending value for the x counter variableand press Enter.

LESSON 2

Microsoft® Office Excel® 2007 - VBA60

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 72: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

5. Enter the code, within the For Nextloop, to select, copy, and paste thedata from any of the stock pricetables on the first three sheets to thefourth All Portfolios sheet.

a. Type Worksheets(x).Select to selecta worksheet with the counter variable andpress Enter.

b. Type Range("A1").Select to selectcell A1 in each selected worksheet andpress Enter.

c. TypeActiveCell.CurrentRegion.Selectto select the current region of the activecell and press Enter.

d. Type Selection.Copy to copy the cur-rent region and press Enter.

e. Type Worksheets("AllPortfolios").Select to select the All

Portfolios worksheet, where the rangewill be pasted and press Enter.

f. In the next line, typeActiveSheet.Paste to paste the data.

See Code Sample 2.

Code Sample 2

Sub DuplData()'For x = 1 to Worksheets.Count - 1

Worksheets(x).SelectRange("A1").SelectActiveCell.CurrentRegion.SelectSelection.CopyWorksheets("All Portfolios").Select

ActiveSheet.Paste

Next x

End Sub

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 61

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 73: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

6. Enter the code necessary to selectcell A1 and then its offset.

a. In the blank line above theActiveSheet.Paste statement, typeRange("A1").Select and then pressEnter.

b. Type ActiveCell.Offset().Selectand then press Enter.

c. Within the parentheses of the Offsetproperty, type x * 10 as the numericvalue to offset the row reference andthen type , (comma).

d. Press the Spacebar and then type 0 as thenumeric 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).SelectRange("A1").SelectActiveCell.CurrentRegion.SelectSelection.CopySheets("All Portfolios").SelectRange("A1").SelectActiveCell.Offset(x * 10, 0).SelectActiveSheet.Paste

Next x

End Sub

7. Duplicate the data onto the All Port-folios worksheet.

a. In the workbook, run the DuplData macro.

b. Scroll up to observe the data that is addedto the All Portfolios worksheet.

LESSON 2

Microsoft® Office Excel® 2007 - VBA62

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 74: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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 eachtime the loop iterated.

c) Because of an error; the Offset values would have placed them on rows 10, 20, and30.

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-6Reviewing 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

Lesson 2: Formatting Worksheets Using Macros 63

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 75: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

TOPIC EGenerate a ReportYou have applied the components that go into creating formatted reports, it’s time to drawthem 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 ObjectDefinition:

The Columns object is an Excel VBA object that represents one or more columns on aworksheet. 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, theColumns command is followed by a pair of parentheses. Within the parentheses is acolumn range enclosed in quotation marks.

Example:

The AutoFit MethodDefinition:

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

The Columns Object

The AutoFit Method

LESSON 2

Microsoft® Office Excel® 2007 - VBA64

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 76: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Example:

The Address PropertyDefinition:

The Address property is a property of the ActiveCell object. It represents a stringvalue describing the location of the currently active cell. When used, the Addresscommand is attached with a period to the ActiveCell object reference.

Example:

The Address Property

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 65

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 77: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

The Call CommandDefinition:

The Call command is an Excel VBA language component used to run a macro fromanother macro. Using it, you can organize your macro code into several separate codegroups, and then call the macros from a “master” macro in an intended order toaccomplish a large, multiphase task. In this method, you need to first enter the Callcommand, 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 PropertyDefinition:

The Font property is an Excel VBA property you can use to set how text will appearon 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 itsproperties, is attached with a period to the object being formatted; a value setting prop-erty is then designated with the equals sign assignment operator.

The Call Command

The Font Property

LESSON 2

Microsoft® Office Excel® 2007 - VBA66

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 78: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Example:

Using With End With to Assign Font PropertiesWhen multiple font properties must be set, the With End With syntax is often usedto reduce the number of keystrokes.

' Setting Font properties without With End With:

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

' Setting Font properties with With End With:

With Selection.Font

.Name = "Arial"

.Size = 14

.Bold = True

End With

The End PropertyDefinition:

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 tothe previously generated data. When used, the End command, followed by a pair ofparentheses, is attached with a period to the object; within the parentheses is placedone of four built-in Excel Direction commands indicating the direction in which tosearch.

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

The End Property

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 67

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 79: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Direction CommandsThe following table describes the four built-in direction commands used with the Endproperty.

Command EffectxlUp 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 ReportProcedure 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 codenecessary 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 tobe copied.

b. With the ActiveCell object and the CurrentRegion method, select thecurrent region of the active cell.

c. With the ActiveSheet object and the Copy method, copy the selectedrange to the Clipboard.

4. Assign the destination of the copied data.

a. With the Worksheets collection object and the Select method, select thedestination worksheet.

b. With the Range object and the Select method, select a cell far below thebottom 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 activecell below the existing data.

e. If necessary, with the ActiveCell object and the Value property, insertheader text.

LESSON 2

Microsoft® Office Excel® 2007 - VBA68

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 80: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

f. If necessary, with the ActiveCell object and the Offset property, selectan active cell below the header.

g. With the ActiveSheet object and the Paste method, paste the copiedrange.

' 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

Lesson 2: Formatting Worksheets Using Macros 69

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 81: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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 1Call Macro 2Call Macro 3Call Macro 4

'Selecting Range for Duplication

Range("CellAddr").SelectSelection.CurrentRegion.SelectSelection.Copy

'Positioning and copying data onto target worksheet:

Worksheets(SheetRef).SelectRange("CellAddrBelow").SelectSelection.End(xlUp).SelectActiveCell.Offset(num1,num2).SelectActiveCell.Value = Worksheets(CV).Name & " AddlTxt"ActiveCell.Offset(num3,num4).SelectActiveSheet.Paste

Next CV

'Formatting target worksheet columns

Columns("ColRange").SelectSelection.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 repeatedin the loop.

LESSON 2

Microsoft® Office Excel® 2007 - VBA70

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 82: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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-downmenu, 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 activecell, above the Do statement, paste the code generated by a recorded macroto 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 generatedFind code, enter the code to select a cell at the location where the firstinstance of the desired text will appear.

d. In between the Do statement and the Find Next statement, enter the codenecessary 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 mainFor 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

Lesson 2: Formatting Worksheets Using Macros 71

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 83: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

ACTIVITY 2-7Creating 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 reportsfor each stock portfolio and the additional All Portfolios worksheet, and set about writing thecode 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.

LESSON 2

Microsoft® Office Excel® 2007 - VBA72

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 84: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

What You Do How You Do It

1. Create a loop structure, in theGenRep macro that cycles throughthe set of worksheets.

a. In Visual Basic Editor, display the GenRepmacro code.

b. In the GenRep macro, type Dim x AsInteger to declare a counter variablenamed x as an integer.

c. In the next line, type For x = 1 ToWorksheets.Count - 1, press Enter

twice and then type Next x to set up aFor Next loop structure that cyclesthrough all except the All Portfoliosworksheet.

d. Within the loop, in the line below the Forstatement, type Worksheets(x).Select to select each worksheet as theloop 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

Lesson 2: Formatting Worksheets Using Macros 73

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 85: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

2. Enter the code necessary to formateach worksheet selected by the loopiterations, within the loop, after thestatement that selects theWorksheet object.

a. Under the statement that selects eachworksheet, type Call SortLastCol tocall SortLastCol and press Enter.

b. Under the line of code you just entered,type a macro call to InsColRow and pressEnter.

c. Under the line of code you just entered,type a macro call to InsertTxt and pressEnter.

d. Under the line of code you just entered,type a macro call to FmtTxt and pressEnter.

See Code Sample 2.

Code Sample 2

Sub GenRep()

Dim x As Integer

For x = 1 To Worksheets.Count - 1

Worksheets(x).Select

Call SortLastColCall InsColRowCall InsertTxtCall FmtTxt

Next x

3. Enter the code necessary to copydata from each worksheet for dupli-cation.

a. Type Range("B6").Select and thenpress Enter.

All the formatted stock table data ranges startat B6.

b. TypeSelection.CurrentRegion.Selectto select the entire data range, and thenpress Enter.

c. Type Selection.Copy to copy therange, and then press Enter.

LESSON 2

Microsoft® Office Excel® 2007 - VBA74

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 86: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

4. Assign the destination of the copieddata.

a. Type Worksheets("All ⇒Portfolios").Select to select thedestination worksheet, and then pressEnter.

b. Type Range("B2000").Select andthen press Enter.

c. Type Selection.End(xlUp).Selectand then press Enter.

The preceding two steps select the destinationactive cell from which a text header can beoffset.

d. Type ActiveCell.Offset⇒(2, 0).Select to select a cell offset toenter the portfolios’ names, and thenpress Enter.

e. Type ActiveCell.Value = ⇒Worksheets(x).Name & ⇒" Portfolio" to insert portfolio headertext, and then press Enter.

f. Type ActiveCell.Offset(2, 0)⇒.Select to select an active cell offset inwhich to paste the copied range, and thenpress Enter.

g. Type ActiveSheet.Paste to paste thecopied range into its destination, and thenpress 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 SortLastColCall InsColRowCall InsertTxtCall FmtTxt

'Selecting Range for Duplication

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 75

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 87: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Range("B6").SelectSelection.CurrentRegion.SelectSelection.Copy

'Positioning and pasting data onto All PortfoliosWorksheets("All Portfolios").SelectRange("B2000").SelectSelection.End(xlUp).SelectActiveCell.Offset(2, 0).SelectActiveCell.Value = Worksheets(x).Name & " Portfolio"ActiveCell.Offset(2, 0).SelectActiveSheet.Paste

Next x

End Sub

5. Format the report generated on theAll Portfolios worksheet.

a. Scroll down, and in the blank line afterthe Next x statement, typeColumns("B:E").Select to select col-umns B to E, and then press Enter.

b. Type Selection.Columns.AutoFit toresize the columns on the All Portfoliosworksheet.

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

b. Run the GenRep macro.

c. Select the Conservative worksheet toview the generated report.

d. Select the Balanced worksheet to viewthe generated report.

e. Select the Aggressive worksheet to viewthe generated report.

f. Select the All Portfolios worksheet toview the generated report.

g. Save the file as My ReportGenerator.xlsm and close it.

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

True

✓ False

LESSON 2

Microsoft® Office Excel® 2007 - VBA76

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 88: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

ACTIVITY 2-8Finding 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 begincreating 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 declareand initialize a string variable namedFoundCellAddress with theaddress of the first found active cell,in the FindFormatPortHeaders macroto build the Do loop criterion.

a. Display the Visual Basic Editor with theFindFormatPortHeaders macro code.

b. Type Dim FoundCellAddress ⇒As String

c. Press Enter twice.

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

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 77

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 89: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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

b. Press Enter six times.

c. Type Loop to indicate the end of theDo loop structure, and then press theSpacebar.

d. Type While to enter the criterion indica-tor, and then press the Spacebar.

e. Type FoundCellAddress <> ⇒ActiveCell.Address and then pressEnter to enter the criterion evaluated bythe Do loop.

See Code Sample 1.

Code Sample 1

Sub FindFormatPortHeaders()

Dim FoundCellAddress As String

FoundCellAddress = ActiveCell.Address

Do

Loop While FoundCellAddress <> ActiveCell.AddressEnd Sub

LESSON 2

Microsoft® Office Excel® 2007 - VBA78

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 90: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

3. Generate a macro code to find twoinstances of the desired text.

a. Switch to the Excel view.

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 bothinstances of the word “portfolio”.

h. In the Find and Replace dialog box, clickClose.

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

ing button.

j. In Visual Basic Editor, in the temp macrocode, copy the generated code to theClipboard.

k. Close the Visual Basic Editor.

l. In the application window, close the newworkbook without saving.

LESSON 2

Lesson 2: Formatting Worksheets Using Macros 79

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 91: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

4. Create a macro to find and formattext.

a. In Visual Basic Editor, in theFindFormatPortHeaders macro, paste thecode from the Clipboard above the Dostatement.

b. Move the Cells.FindNext statementinside the Do loop.

Cell B4 holds the word “portfolio.”

c. Just under the variable declaration state-ment, type Range("B4").Select toselect cell B4.

d. In between the Do statement and theCells.FindNext statement, enter thecode necessary to format the currentlyactive cell in 14pt, Arial, Bold.

See Code Sample 2.

e. In the GenRep macro, in the blank lineafter the Next x statement, typeCall ⇒FindFormatPortHeaders and pressEnter.

Code Sample 2

Sub FindFormatPortHeaders()

Dim FoundCellAddress As String

Range("B4").SelectCells.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

LESSON 2

Microsoft® Office Excel® 2007 - VBA80

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 92: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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

b. On the worksheet, run the GenRep macro.

c. View the report on the Conservativeworksheet.

d. View the report on the Balancedworksheet.

e. View the report on the Aggressiveworksheet.

f. View the report on the All Portfoliosworksheet.

g. Save the file as My New Report.xlsm andclose it.

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

✓ True

False

DISCOVERY ACTIVITY 2-9Reviewing 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

Lesson 2: Formatting Worksheets Using Macros 81

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 93: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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-upIn 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?

Answers will vary, but in most scenarios generating reports is inevitable and doing thiswith the help of macros makes your job a lot easier.

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

Answers will vary, but looping the code may pose problems if not done accurately.

LESSON 2

Microsoft® Office Excel® 2007 - VBA82

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 94: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Creating an InteractiveWorksheet

In this lesson, you will create an interactive worksheet.

You will:

• Determine the appropriate dialog box for capturing user input.

• Capture user input.

Lesson Time35 minutesLESSON 3

LESSON 3

Lesson 3: Creating an Interactive Worksheet 83

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 95: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

IntroductionWhile the macros created in the previous lesson do not require information or decisions fromthe user, VBA does provide ways to modify a worksheet by capturing the user input. In thislesson, you will use a dialog box to capture the user-entered information that will be applied tomodify a worksheet.

Creating an interactive worksheet enables you to query users for information that modifies aworksheet, so that they don’t have to make changes manually.

TOPIC ADetermine the Dialog Box TypeYou 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, youwill 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 boxwhose interactive controls minimize the consequences of user error like ruined data or acrashed computer. By determining user input and then creating a dialog box to capture userinput while minimizing error, you will be able to create VBA-scripted macros that get the jobdone without unintended errors and crashes.

Message BoxesA 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 untilthe user’s input is received and evaluated. Subsequent code in the macro can then be executedor skipped, based on the user’s response.

Figure 3-1: Responses in a message box.

Message Boxes

LESSON 3

Microsoft® Office Excel® 2007 - VBA84

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 96: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Button DescriptionOK Enables the user to acknowledge the message.

OK and Cancel Enables the user to proceed with or stop an actiondescribed in the message.

Abort, Retry, and Ignore Enables the user to stop an action described in themessage, try to complete the action, or continueirrespective of the action’s completion.

Yes and No Enables the user to agree or disagree with anaction suggested in the message.

Yes, No, and Cancel Enables the user to agree, disagree, or halt anaction suggested in the message.

Retry and Cancel Enables the user to try to complete an actiondescribed in the message or stop the action’sexecution.

Input BoxesDefinition:

An input box is a type of dialog box used by macro developers to capture entered textdata from a user when a macro is run. It consists of a message, a text box into which auser can type data requested by the message, and the OK and Cancel buttons, whichthe user can click. When a running macro displays an input box, the code in the macroceases execution until the user’s input is received and evaluated. Subsequent code inthe macro can then be executed or skipped, based on the text entered in the text box.

Example:

How to Determine the Dialog Box TypeProcedure 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.

Input Boxes

LESSON 3

Lesson 3: Creating an Interactive Worksheet 85

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 97: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

• 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 ornumeric data.

• Otherwise, use a message box.

ACTIVITY 3-1Determining the Dialog Box Type

Scenario:A coworker, who is given charge of an in-house training session for new employees on VBAscripting, plans to talk about the dialog box usage. She has prepared some scenarios for theclass to determine whether the input or message boxes should be used, and wants you to testout 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 nameof 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 auser 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 workbookcauses a dialog box to appear, when the print job fails. The dialog box asks whetherthe user wants to try sending the file to the printer again, or cancel the print job. Tocreate such a dialog box, you would use an input box.

True

✓ False

LESSON 3

Microsoft® Office Excel® 2007 - VBA86

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 98: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

4. True or False? When run, a macro displays a dialog box that enables the user to enterinformation to sort a table of data on a spreadsheet in five different ways. To createthe 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 fora response. Suddenly, a dialog box appears with an animated icon and a ″SearchingRecords″ 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 dialogbox, 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 priorinput error and halt the program until the user acknowledges the message by clickingOK?

a) Query box

✓ b) Message box

c) Input box

d) Exclamation box

TOPIC BCapture User InputYou 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 worksheetbased on an interaction. In this topic, you will create a macro that depends on user interactionto modify a worksheet.

Imagine you need to create two different views of sales data in a worksheet depending onwhether the user is a manager or a salesperson. One way to determine the correct view to bedisplayed would be to create a macro that asks if the user is a manager. Using VBA to captureuser input modifies a worksheet or its content based on the input.

The InputBox FunctionDefinition:

The InputBox function is a built-in VBA function that governs how an input box isdisplayed. It consists of the InputBox command, followed by a pair of parenthesesthat 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 textbox.

The InputBox Function

LESSON 3

Lesson 3: Creating an Interactive Worksheet 87

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 99: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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 isassigned as string data to the variable. The variable can then be used in subsequentcode to direct the macro toward a chosen data processing goal.

Example:

ConstantsDefinition:

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, theirnames reflect their purpose. Constants typically begin with the letters vb followed by abrief description of their usage.

Example:

Constants

LESSON 3

Microsoft® Office Excel® 2007 - VBA88

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 100: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

The MsgBox FunctionDefinition:

The MsgBox function is a built-in VBA function that governs how a message box isdisplayed. It consists of the MsgBox command, followed by a pair of parentheses thatcontains a comma-separated list of variables, data items, or constants that control themessage and the types of buttons displayed.

When entered in code, the MsgBox function is placed on the right side of a variableassignment statement; when run, the data entered by the user is assigned as integerdata to the variable. The variable can then be used in subsequent code to direct themacro toward a chosen data processing goal.

Example:

The Code Continuation CharacterThe 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 singleunderscore keystroke, is placed at the right end of the code to be wrapped; usually, a spaceprecedes it.

When the Excel application interprets VBA code in a macro, it considers the Enter keystrokeas the end of a single VBA command except when it is preceded by the code continuationcharacter.

The MsgBox Function

The Code ContinuationCharacter

LESSON 3

Lesson 3: Creating an Interactive Worksheet 89

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 101: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Figure 3-2: Code Continuation.

The vbCrLf CharacterThe vbCrLf character indicates where the text in a long input box or message box should bebroken 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 itemsthat 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.

The vbCrLf Character

LESSON 3

Microsoft® Office Excel® 2007 - VBA90

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 102: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Decision StructuresDefinition:

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

Example:

The Select Case StructureThe Select Case structure enables the code in a macro to be executed or ignored based on acondition, such as an entered response from a user. The Select Case decision structureconsists 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 criterionvariable, identified in the Select Case statement, against the comparative data values ineach 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 noCase statements match, either the code within the optional Case Else statement is executedor the code within the structure is ignored.

Decision Structures

LESSON 3

Lesson 3: Creating an Interactive Worksheet 91

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 103: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

The If Then StructureThe If Then structure enables the code in a macro to be executed or ignored depending onthe 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 theresult 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 ClausesLike 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 Ifstatement 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 codewithin the ElseIf Then statement is run; if the expression is false, the code withinthe ElseIf Then statement is ignored.

The criterion expression in an ElseIf statement is evaluated only when the criteria inthe If Then and any ElseIf statements above it are evaluated to false. The Elsestatement, placed below any ElseIf statements, contains no criterion. The code underit runs only when the criterion expressions in the If Then and ElseIf Then state-ments are evaluated to false.

How to Capture User InputProcedure 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 thetext that will appear in the title bar, one for the default text that will appear in theinput box’s text box, and one for the user’s response.

' Declaring four variables as strings:

Dim Message, TitlebarTxt, DefaultTxt, UserResponse AsString

LESSON 3

Microsoft® Office Excel® 2007 - VBA92

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 104: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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 thefourth 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 Caseclauses:

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 thevariable 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 evaluativecriterion.

d. If necessary, in the subsequent Case statements, enter unique data values asthe statements’ evaluative criteria.' Adding criteria:

Select Case VarName

Case Criterion1

LESSON 3

Lesson 3: Creating an Interactive Worksheet 93

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 105: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Case Criterion2

Case Else

End Select

3. Enter the code to be run based on the criterion evaluated in each Casestatement.

a. For the first Case statement, in between the first and second Casestatements, enter the code to be run if the criterion for the first Casestatement is met.

b. For the second Case statement, in between the second Case statement andthe 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 Casestatement for which you want to enter the code and the next Case, CaseElse, or End Select clause, enter the code to be run if the criterion forthe 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 EndSelect clauses, enter the code to be run if the criteria for the Casestatements 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 ElseCode to run if no criteria metEnd Select

LESSON 3

Microsoft® Office Excel® 2007 - VBA94

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 106: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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 themessage box.

5. After the string value, type a comma, and then a number or Visual Basic constantdefining 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 Thenstructure.

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

Lesson 3: Creating an Interactive Worksheet 95

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 107: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

ACTIVITY 3-2Sorting 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 UserInteractive.xlsm file.

Scenario:Your manager reviews an extensive log generated by a call center, and has recorded severalmacros to sort the data differently. Instead of remembering the different macro names, hewants to run a single macro that asks him to sort data and perform action. He hands off theproject to you and asks you to come up with a prototype that sorts using the DateThenTimeand RepSort macros, or displays an error message followed by a macro reset, if bad input isentered by a user.

What You Do How You Do It

1. Declare the variables necessary tohold the information for the InputBoxfunction parameters and the user’sresponse.

a. In Visual Basic Editor, display the code forthe SortBy macro.

b. In the SortBy macro, in the first blank linebelow 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 StringDim YNAnswer As Integer

End Sub

LESSON 3

Microsoft® Office Excel® 2007 - VBA96

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 108: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

2. Assign data values to the variablesused as parameters in the InputBoxfunction.

a. Assign message text to Message.

See Code Sample 2.

b. In the next line, assign “Sort Call CenterLog” as the text to appear in the title bar.

c. In the next line, assign “Enter 1 or 2” asthe default text for the input box’s textbox.

See Code Sample 3.

d. Press Enter.

Code Sample 2

Sub SortBy()'''Dim Message, TitlebarTxt, DefaultTxt, SortVal As StringDim 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 StringDim 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

Lesson 3: Creating an Interactive Worksheet 97

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 109: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

3. Assign the InputBox function, withits parameters, to the SortVal vari-able.

a. Type SortVal and press the Spacebar.

b. Assign the InputBox function toSortVal.

c. In the parentheses, enter the parametervalues.

See Code Sample 4.

d. Click at the end of the statement andpress Enter.

Code Sample 4

Sub SortBy()'''Dim Message, TitlebarTxt, DefaultTxt, SortVal As StringDim 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

LESSON 3

Microsoft® Office Excel® 2007 - VBA98

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 110: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

4. Create a Select Case structurehaving two Case clauses and aCase Else clause.

a. Type Select Case and press Enter twotimes.

b. Type Case and press Enter two times.

c. Type Case and press Enter two times.

d. Type Case Else and press Enter twotimes.

e. Type End Select and press Enter twotimes.

See Code Sample 5.

Code Sample 5

Sub SortBy()'''Dim Message, TitlebarTxt, DefaultTxt, SortVal As StringDim 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

Lesson 3: Creating an Interactive Worksheet 99

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 111: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

5. Enter SortVal as the variable nameto be evaluated by the Case struc-tures, and 1 and 2 as the Cases'criteria string values.

a. Click in the Select Case statement,press the Spacebar, and type SortVal

b. Click in the first Case statement, pressthe Spacebar, and type "1" as the datavalue criterion.

c. Click in the second Case statement, pressthe Spacebar, and type "2" as the datavalue 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 basedon the criteria evaluated in eachCase statement.

a. Click in the blank line below Case “1” andcall the DateThenTime macro for the firstcase.

b. Click in the blank line below Case “2” andcall the RepSort macro for the secondcase.

See Code Sample 7.

Code Sample 7

Select Case SortVal

Case "1"

Call DateThenTime

Case "2"

Call RepSort

Case Else

End Select

LESSON 3

Microsoft® Office Excel® 2007 - VBA100

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 112: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

7. Enter code to reset the macro if noneof the criteria for the Case state-ments are met.

a. Call the SortBy macro if none of the casesare met.

b. In between Case Else and the SortBymacro call, type YNAnswer followed by aspace to enter the name of the variablestoring input from a message box.

c. Type the equals sign assignment operatorand 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 boxtext.

f. Click at the end of the statement andpress Enter.

LESSON 3

Lesson 3: Creating an Interactive Worksheet 101

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 113: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

8. Enter an If Then code to call theSortBy macro again if the answerentered by the user is yes.

a. In the next line, type If Then

b. Press Enter two times.

c. Type End If

d. Press Enter.

e. In between the If and Then, create acomparison using YNAnswer to evaluatewhether a yes answer was returned fromthe MsgBox function.

f. Move the call to the SortBy macro insidethe 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

LESSON 3

Microsoft® Office Excel® 2007 - VBA102

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 114: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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

Call SortByEnd If

End Select

End Sub

9. Run the SortBy macro on theworksheet.

a. Switch to the 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 themacro to sort the data by the Reps’names.

a. In the Input text box that appears, type 2

b. Click OK.

11. Test to see if the Yes/No messagebox works correctly if the user’sinput is incorrect.

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

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 5again.

g. Click OK.

h. After reading the Yes/No message box,click No to end the macro.

i. Save the file as My UserInteractive.xlsmand close it.

LESSON 3

Lesson 3: Creating an Interactive Worksheet 103

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 115: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

PRACTICE ACTIVITY 3-3Including 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 additionalCase 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 performthe 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 thechoices are presented in list format in the input box.

3. Alter the default text message and warning message box message to reflect thenew changes.

4. Run and test the macro.

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

LESSON 3

Microsoft® Office Excel® 2007 - VBA104

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 116: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Lesson 3 Follow-upIn this lesson, you coded macros to query users for responses that affected data processingresults, making the worksheet interactive.

1. How can the use of input boxes and message boxes change the way you use Excel?

Answers will vary, but using input boxes and message boxes will help you create an inter-active macro.

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

Answers will vary, but if the user input gathered must include unique text or numericdata use an input box, otherwise use a message box.

LESSON 3

Lesson 3: Creating an Interactive Worksheet 105

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 117: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Microsoft® Office Excel® 2007 - VBA106

NOTES

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 118: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Working with MultipleWorksheets

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 Time50 minutesLESSON 4

LESSON 4

Lesson 4: Working with Multiple Worksheets 107

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 119: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

IntroductionYou 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 performednot 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 singleExcel file.

TOPIC AInsert, Copy, and Delete WorksheetsYou 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 toinsert, copy, and delete worksheets.

Inserting, copying, and deleting worksheets are the most commonly performed tasks in anExcel workbook. Repeatedly performing these tasks could become taxing at times. Thus, VBAhelps you to automate multiple worksheets related tasks.

The Add MethodDefinition:

The Add method is a method of the Worksheets collection object used to adda new, blank worksheet in a worksheet list. The Add command, used to invoke thismethod, 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 theworksheet list. If a new worksheet needs to be added elsewhere, either the Before orAfter optional variant is used.

Example:

The Add Method

LESSON 4

Microsoft® Office Excel® 2007 - VBA108

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 120: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

The Copy MethodDefinition:

The Copy method is a method of the Worksheets collection object used tomake 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 Worksheetscollection object reference, thereby identifying the worksheet to be duplicated.When executed in a macro, this method places the duplicate worksheet at the end ofthe worksheet list.

If a duplicate worksheet needs to be added elsewhere, either the Before or Afteroptional variant is used.

Example:

The Delete MethodDefinition:

The Delete method is a method of the Worksheets collection object used todelete a worksheet from a worksheet list. The Delete command, used to invoke thismethod, is attached with a period at the end of the Worksheets collectionobject 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 WorksheetsProcedure Reference: Insert a Worksheet

To insert a worksheet using a macro:

1. In a macro, type Worksheets.Add.

The Copy Method

The Delete Method

LESSON 4

Lesson 4: Working with Multiple Worksheets 109

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 121: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

2. If necessary, use the Before optional variant to insert a worksheet before anexisting 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 existingsheet.

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 orby 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 orby 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 existingworksheet.

LESSON 4

Microsoft® Office Excel® 2007 - VBA110

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 122: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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-1Inserting 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 worksheetsnamed for the months of the year. Although the form hasn’t been finalized, he wants you toget 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 aninteger in the empty AddSheetsmacro.

a. Under the Sub AddSheets statement,under the commenting, type Dim x AsInteger

b. Press Enter.

LESSON 4

Lesson 4: Working with Multiple Worksheets 111

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 123: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

2. Create a For Next loop that uses xto iterate the loop 12 times.

a. Type For x = 1 To 12 and press Enter

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 xEnd Sub

3. Enter the code for inserting aworksheet.

a. In between the For and Next statements,type Worksheets.Add to insert aworksheet and press the Spacebar.

b. In the same line, type After:=Worksheets(x) to insert the Afteroptional variant to indicate that each newworksheet should be inserted after thelast worksheet in the worksheet list.

See Code Sample 2.

Code Sample 2

Sub AddSheets()

Dim x As Integer

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

Next x

End Sub

LESSON 4

Microsoft® Office Excel® 2007 - VBA112

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 124: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

4. Run the macro to insert the 12 newworksheets.

a. Close the Visual Basic Editor.

b. Run the AddSheets macro.

c. Scroll across the worksheet list to view allthe sheets in the workbook.

d. Save the file as My New Sheets.xlsm andclose it.

5. Where is the Sheet1 worksheet in the list?

✓ a) First

b) Second

c) Twelfth

d) Thirteenth

ACTIVITY 4-2Deleting 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 formis not needed once the monthly sheets are created, you decide to have the macro delete it afterthe new sheets are inserted.

LESSON 4

Lesson 4: Working with Multiple Worksheets 113

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 125: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

What You Do How You Do It

1. Add a line of code to the DeleteSheetmacro that deletes Sheet1 after the12 other sheets are inserted.

a. Display the Visual Basic Editor for theDeleteSheet macro.

b. In the code editing window, in theDeleteSheet macro, in between theNext x and End Sub statements, typeWorksheets.Delete

See Code Sample 1.

Code Sample 1

Next x

Worksheets.Delete

End Sub

2. Identify Sheet1 as the sheet to bedeleted from the worksheet list.

a. In the deletion statement, insert a pair ofparentheses after the Worksheetsobject reference.

b. Within the parentheses, type 1 to identifySheet1 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 clickRun to run the DeleteSheet macro.

c. In the warning box that appears, clickDelete to delete the first sheet.

d. Scroll through the worksheet list andobserve that Sheet1 has been deleted.

e. Save the file as My Project.xlsm andclose it.

LESSON 4

Microsoft® Office Excel® 2007 - VBA114

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 126: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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-3Copying 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 tomodify the code to copy the finalized form into the 12 monthly worksheets.

LESSON 4

Lesson 4: Working with Multiple Worksheets 115

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 127: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

What You Do How You Do It

1. Use the Worksheets collectionobject, the Copy method, and theAfter optional variant, in the ForNext loop to copy the firstworksheet to 12 new copies at theend of the worksheet list.

a. Within the For Next loop, typeWorksheets.Copy

b. Insert a pair of parentheses after theWorksheets object reference.

c. Within the parentheses, identify the firstsheet as the sheet to be copied by itsposition in the worksheet list.

d. After the code Worksheets(1).Copy,press the Spacebar and type After:=Worksheets(x) to insert the new copyafter 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 12Worksheets(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 clickRun.

c. In the warning box that appears, clickDelete to confirm the deletion of Sheet1.

d. Scroll through the worksheet list andobserve that Sheet1 has been deleted.

LESSON 4

Microsoft® Office Excel® 2007 - VBA116

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 128: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

3. Inspect the second worksheet, andthen the last worksheet.

a. Select the Sheet1 (2) tab to view its con-tents.

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

If necessary, use the sheet navigation controlsto display the last worksheet tab.

c. Save the file as My OG Corp.xlsm andclose it.

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

✓ True

False

DISCOVERY ACTIVITY 4-4Reviewing 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 newworksheet?

✓ 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

Lesson 4: Working with Multiple Worksheets 117

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 129: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

TOPIC BRename WorksheetsYou know how to manually rename worksheets. You are now required to rename worksheetson 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 tediumof manually renaming them, you can apply VBA to automate this task of renaming.

ExpressionsDefinition:

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 theirresults assigned to variables that are then used to represent them in subsequent code.

Example:

The DateSerial FunctionDefinition:

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

Example:

Valid Integer ValuesThe valid integer values for the DateSerial function are listed in the table below.

Expressions

The DateSerial Function

LESSON 4

Microsoft® Office Excel® 2007 - VBA118

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 130: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Required Value Valid RangeFor 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 yearvalues.

The Format FunctionDefinition:

The Format function is a built-in VBA function that can convert Date data into Stringdata. When used, the function consists of the Format command, followed by a pair ofparentheses 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 aparticular style.

Example:

How to Rename WorksheetsProcedure 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 nameor 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

The Format Function

LESSON 4

Lesson 4: Working with Multiple Worksheets 119

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 131: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

ACTIVITY 4-5Renaming 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 themonths of the year. You insert the code designed to rename the new sheets.

LESSON 4

Microsoft® Office Excel® 2007 - VBA120

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 132: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

What You Do How You Do It

1. Enter the code necessary to renamethe newly inserted worksheet withthe appropriate month of the year.

a. In the RenameSheets macro, in the ForNext loop, below the statement thatcopies in the new worksheet, typeWorksheets()

b. Within the parentheses, type x + 1 toidentify the worksheet to be renamed asthe last worksheet in the worksheet list.

Because the renaming command follows thecopy command, x + 1 represents the lastworksheet in the list.

c. At the end of the code Worksheets(x+ 1), type .Name to add the Nameproperty and then press the Spacebar.

d. Type = to add the assignment operatorand then press the Spacebar.

e. Type Format(DateSerial⇒(1,x,1), "mmmm") to enter the expres-sion that assigns the full name of theappropriate month to the newly insertedworksheet.

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

Lesson 4: Working with Multiple Worksheets 121

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 133: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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

b. Display the Macro dialog box, select theRenameSheets macro and click Run.

c. In the warning box that appears, clickDelete.

d. Verify that the worksheet name tabs arenamed with the months of the year.

e. Save the file as My OG CorpMonthly.xlsm and close it.

DISCOVERY ACTIVITY 4-6Exploring 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.

LESSON 4

Microsoft® Office Excel® 2007 - VBA122

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 134: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

TOPIC CModify the Order of WorksheetsYou know how to manually reorder worksheets. You are now required to reorder worksheetson 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 atopposite ends of the worksheet list. By reordering worksheets automatically, you can modifythe order of worksheet information in situations that demand quick access to otherwise “bur-ied” data.

The Move MethodDefinition:

The Move method is a method of the Worksheets collection object that movesa worksheet from one position in the worksheet list to another. The Move command isattached with a period to the Worksheets object reference; the Before or Afteroption is used to identify the destination of the worksheet being moved.

Example:

How to Modify the Order of WorksheetsProcedure 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 itsposition in the worksheet list.

' By name:

Worksheets("SheetName").Move

' By position:

Worksheets(Number).Move

The Move Method

LESSON 4

Lesson 4: Working with Multiple Worksheets 123

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 135: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

4. If necessary, use the Before optional variant and the Worksheetcollection object to move the worksheet before another existing worksheet.

5. If necessary, use the After optional variant and the Worksheetcollection 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-7Moving 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 manypages in a workbook. She asks you to build some navigation controls to rearrange theworksheets automatically so that she is not in need to scroll all the time. You start by writing amacro 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().Moveto enter the code necessary to move aworksheet.

b. In the parentheses, type "SE Sales" toidentify SE Sales as the sheet to bemoved, and then click at the end of thecode and press the Spacebar.

LESSON 4

Microsoft® Office Excel® 2007 - VBA124

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 136: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

2. Indicate that the sheet is to bemoved to the first position in theworksheet list.

a. Type Before:= to add the optional vari-ant.

b. Type Worksheets(1) to identify thefirst sheet in the list as the sheet in frontof 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 tomove the SE Team, Clients, and Mar-keting worksheets, under the codeyou just entered.

a. Copy and paste the line of code you justentered onto the next line.

b. In the newly pasted code, change thename of the worksheet being moved toSE Marketing.

c. Paste the same line of code onto the nextline.

d. Change the name of the worksheet beingmoved to SE Clients.

e. Paste the same line of code onto the nextline and change the name of theworksheet 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)

Mention that the names mustbe in reverse order in thecode.

LESSON 4

Lesson 4: Working with Multiple Worksheets 125

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 137: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

4. Run the SEMove macro to move theSE-related worksheets to the begin-ning of the worksheet list.

a. Close the Visual Basic Editor.

b. Display the Macro dialog box, and run theSEMove macro.

c. Click the second worksheet tab to displaythe SE Clients worksheet.

d. Click the third worksheet tab to displaythe SE Marketing worksheet.

e. Click the fourth worksheet tab to displaythe SE Sales worksheet.

f. Click the first worksheet tab to displaythe SE Team worksheet.

g. Save the file as My OGC Sales.xlsm andclose it.

DISCOVERY ACTIVITY 4-8Understanding How to Modify the Order of Worksheets

Scenario:You are now ready to review your knowledge of modifying the order of worksheets usingmacros.

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 identifythe sheet to be moved by its name only.

True

✓ False

LESSON 4

Microsoft® Office Excel® 2007 - VBA126

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 138: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

TOPIC DPrint WorksheetsYou 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 selectedworksheets in a large workbook is scrolling and then printing them. By automating the printingof worksheets, you can extract data from large workbooks without having to hunt through along worksheets list.

The PrintPreview MethodDefinition:

The PrintPreview method is a method of the Worksheets collection objectused to display worksheets in the Print Preview window. When used, thePrintPreview command is attached with a period to the Worksheetscollection 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 aredisplayed, when the method is executed. Otherwise, the worksheet referenced by theWorksheets collection object is displayed.

Example:

The PrintOut MethodDefinition:

The PrintOut method is a method of the Worksheets collection object used tosend worksheets to the printer. When used, the PrintOut command is attached witha 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 theWorksheets collection object is printed.

The PrintPreview Method

The PrintOut Method

LESSON 4

Lesson 4: Working with Multiple Worksheets 127

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 139: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Example:

How to Print WorksheetsProcedure 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 allthe sheets in the workbook.

2. If necessary, in the macro, type Worksheets(SheetRef).PrintPreviewto preview a selected sheet in the workbook, where SheetRef is a reference eitherto 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 tothe worksheet list index values of the worksheets you want to preview.

2. Within the For Next loop, type Worksheets().PrintPreview.

For instructional purposes, theexercises in this topic will

preview, not print, theworksheets. Be sure to tell

students to swap out thePrintPreview method

with the PrintOut methodfor actual printing, and if time

permits, demonstrate such aswap.

LESSON 4

Microsoft® Office Excel® 2007 - VBA128

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 140: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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 listto be' previewed' Num2 refers to the last sheet in the worksheet listto 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 inquotation 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 youwant 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 referencedsheets ' refer tonon-adjacent worksheets.

LESSON 4

Lesson 4: Working with Multiple Worksheets 129

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 141: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

ACTIVITY 4-9Previewing 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 printedat 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 previewall the sheets in a workbook, in thePrintAllSheets macro.

a. In the PrintAllSheets macro, typeWorksheets to enter the reference tothe Worksheets collection object.

b. Add a period to add a method to theobject.

c. Type PrintPreview to add the methodthat previews the printout of the work-book sheets.

See Code Sample 1.

d. Close the Visual Basic Editor.

Code Sample 1

Sub PrintAllSheets()Worksheets.PrintPreviewEnd Sub

2. Run the macro to preview the print-out.

a. Display the Macro dialog box.

b. Select the PrintAllSheets macro and clickRun.

LESSON 4

Microsoft® Office Excel® 2007 - VBA130

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 142: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

3. Preview the printout in the Print

Preview window that is displayed.a. After you read the contents of the first

displayed worksheet, click Next Page.

b. After you read the contents of the seconddisplayed worksheet, click Next Page.

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

view window, verify the status, whichindicates 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 andclose it.

ACTIVITY 4-10Previewing 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 theworkbook. That way, she can print the sheets for any division by positioning them as the firstfour sheets, and then print. Mindful of wasting paper, you build a test macro that previews theselected sheets.

What You Do How You Do It

1. Declare the counter variable x as aninteger, in the PrintDivision macro,and then code a For Next loop thatcan be used to print the first fourworksheets in the worksheet list.

a. In the PrintDivision macro, type Dim ⇒x As Integer

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

Lesson 4: Working with Multiple Worksheets 131

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 143: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

2. Enter the code to preview a selectedworksheet, within the For Nextloop.

a. Within the loop, typeWorksheets.PrintPreview

b. In the Worksheets collection object,type (x) to insert a sheet reference thatuses 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 xEnd Sub

3. Run the macro to preview the print-out.

a. Close the Visual Basic Editor.

b. Display the Macro dialog box.

c. Select the PrintDivision macro and clickRun.

4. Preview each sheet. a. View the preview for the first sheet, andthen 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, andthen 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.xlsmand close it.

LESSON 4

Microsoft® Office Excel® 2007 - VBA132

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 144: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

PRACTICE ACTIVITY 4-11More 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 seeif 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 thelist is reordered, different worksheets would be printed.

✓ True

False

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

LESSON 4

Lesson 4: Working with Multiple Worksheets 133

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 145: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

ACTIVITY 4-12Previewing 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 testmacro that previews the Sales worksheets for the NE and SE divisions.

What You Do How You Do It

1. Enter the code, in the PrintSalesmacro to preview the salesworksheet for the NE Division.

a. In the PrintSales macro, typeWorksheets.PrintPreview

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

2. Copy and paste the code you justentered onto the next blank line.

a. Select Worksheets("NE Sales").PrintPreview.

b. On the Standard toolbar, click the Copy

button.

c. Place the insertion point in the next blankline.

d. On the Standard toolbar, click the Paste

button.

LESSON 4

Microsoft® Office Excel® 2007 - VBA134

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 146: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

3. Modify the pasted code so that the SESales worksheet is referenced by theWorksheets collection object.

a. Place the insertion point between N and Eof NE.

b. Press Backspace.

c. Type S

See Code Sample 1.

Code Sample 1

Sub PrintSales()

Worksheets("NE Sales").PrintPreviewWorksheets("SE Sales").PrintPreview

End Sub

4. Run the macro to preview the print-out.

a. Close the Visual Basic Editor.

b. Display the Macro dialog box.

c. Select the PrintSales macro and clickRun.

5. Preview each sheet. a. View the preview for the first sheet, andthen 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.xlsmand then close it.

LESSON 4

Lesson 4: Working with Multiple Worksheets 135

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 147: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

DISCOVERY ACTIVITY 4-13Exploring 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 allworksheets in the workbook.

✓ True

False

Lesson 4 Follow-upIn 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 andenable you to perform other important tasks.

1. List the various activities you can perform on multiple worksheets.

Answers will vary, but may include adding, copying, deleting and so on.

2. How will working with multiple sheets simultaneously help in your job role?

Answers will vary but working with multiple sheets simultaneously increases the level ofefficiency and is also a time-saving method.

LESSON 4

Microsoft® Office Excel® 2007 - VBA136

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 148: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Performing Calculations

In this lesson, you will perform calculations.

You will:

• Create a user-defined function.

• Automate a SUM function.

Lesson Time35 minutesLESSON 5

LESSON 5

Lesson 5: Performing Calculations 137

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 149: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

IntroductionYou created macros that used VBA’s built-in functions. However, these built-in functions maynot always meet your needs. This is where the ability to create user-defined functions cancome to your aid. In this lesson, you will create a user-defined function to automate calculatingvarying quantities of data in a worksheet.

Your company is likely to use specific calculations other than those available with Excel. VBAallows you to create custom functions that perform duties beyond the built-in functions.

TOPIC ACreate User-Defined FunctionsYou 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 capabilitiesby creating a user-defined macro.

Believe it or not, Excel can’t do it all—there are times when you need to calculate or managedata on a worksheet that can’t be accomplished by the software’s copious supply of stockfunctions. By creating a user-defined custom function, you can perform tasks that would other-wise be unavailable to a casual Excel user.

User-Defined FunctionsDefinition:

A user-defined function is a custom function created with VBA code to return a datavalue 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.

User-Defined Functions

LESSON 5

Microsoft® Office Excel® 2007 - VBA138

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 150: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Example:

Function CallsA 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 canbe processed only by another function to complete the calling function’s data process-ing goal.

Types of FunctionsSimilar to the Personal Macro Workbook, which enables any workbook to use the macrosstored 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 thefunction code exists.

ArgumentsDefinition:

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 Functionstatement, 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, ornone at all.

Arguments

LESSON 5

Lesson 5: Performing Calculations 139

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 151: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Example:

The Else ClauseDefinition:

The Else clause is an optional clause in the If Then decision structure. It does notcontain 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 offalse.

Example:

How to Create User-Defined FunctionsProcedure 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 youwant 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.

The Else Clause

LESSON 5

Microsoft® Office Excel® 2007 - VBA140

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 152: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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 thefirst 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 thefunction.

4. Apply the function on the worksheet.

ACTIVITY 5-1Creating 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 aftertaking inflation into account.

LESSON 5

Lesson 5: Performing Calculations 141

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 153: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

What You Do How You Do It

1. Create a new function namedPriceLevel.

a. Display the Visual Basic Editor.

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, selectFunction.

e. Click OK.

2. Enter amount, byr, and eyr as thefunction’s arguments list.

a. After the function name, between theempty parentheses, click and typeamount

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 amountin a base year to an inflation-adjusted equivalent in an ending yearbetween 1913 and 2008, using theCPI_idx function.

a. Within the PriceLevel function, typeIf Then and press Enter.

b. In the line below, type Else and pressEnter.

c. In the next line below, type End If andpress Enter.

d. In the If Then clause, between If andThen, create an expression that is true ifthe eyr or byr arguments contain valuessmaller than 1913 or larger than 2008.

LESSON 5

Microsoft® Office Excel® 2007 - VBA142

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 154: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

4. Return zero as the value from thePriceLevel function if the yeararguments are neither within 1913 to2008 nor equivalent to the inflation-adjusted amount.

a. Click at the end of the statement andpress Enter. In between the If Then andthe Else statements, type the function’sname.

b. Press the Spacebar.

c. Type an equals sign to assign a value tothe 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 thentype the code that calculates and returnsthe 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

Lesson 5: Performing Calculations 143

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 155: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

5. Apply the function in the cell next tothe “Is Equivalent To” item on thePrice Level worksheet.

a. In cell B7, click and type the equals sign.

b. Type PriceLevel as the function’sname.

c. Type an open parenthesis.

d. Click cell B5 to insert the cell referencefor the amount argument.

e. Type a comma.

f. Click cell B6 to insert the cell referencefor the byr argument.

g. Type a comma.

h. Click cell B8 to insert the cell referencefor the eyr argument.

i. Type a closing parenthesis.

j. Press Enter to assign the function to thecell.

k. Save the file as My Price Level.xlsm andclose it.

LESSON 5

Microsoft® Office Excel® 2007 - VBA144

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 156: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

TOPIC BAutomate SUM FunctionsYou 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, itmight 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 throwseverything off, making your results worthless. By creating a custom SUM function that cananticipate and adapt to the changes made to worksheet data, you can sum altered data withoutthe need of manually verifying and resetting data ranges.

Declared Range ObjectsDefinition:

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 itsprocessing code. It differs from a variable, however, in that it stores a cell range, not asingle 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:

Declared Range Objects

LESSON 5

Lesson 5: Performing Calculations 145

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 157: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

The Set StatementDefinition:

The Set statement is a VBA language component used to assign a cell range to aDeclared 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 completethe command by entering the equals sign assignment operator and an expression thatboth define a cell range.

Example:

Range Object Cell AddressingDefinition:

Range object cell addressing is a VBA cell-addressing convention that organizes a cellrange assigned to a Declared Range object. When a cell range on a spreadsheet isassigned to a Declared Range object, the object superimposes its own cell address-ing coordinate system onto the cells in the range. Subsequent code using theDeclared 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 therange. However, generic VBA commands that make use of the worksheet’s addressingcoordinate system can still access and control the data range.

Example:

The Set Statement

Range Object Cell Addressing

LESSON 5

Microsoft® Office Excel® 2007 - VBA146

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 158: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

The Rows PropertyDefinition:

The Rows property is a property of a Declared Range object that represents therows in a range. When used, the Rows command, followed by a pair of parentheses, isattached to the Declared Range object reference with a period. A data value orexpression yielding an integer value can be placed within the parentheses to indicatethe number of rows the property refers to in a given VBA command.

Example:

The Formula PropertyDefinition:

The Formula property is a property of a Declared Range object that is used toinsert formulas in the cells of an indicated range. When used, the Formula commandis attached with a period to the Declared Range object reference; the equals signassignment operator and an expression defining the text for a formula for entry inworksheet cells complete the command.

Example:

The Rows Property

The Formula Property

LESSON 5

Lesson 5: Performing Calculations 147

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 159: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

The Columns PropertyDefinition:

The Columns property is a property of a Declared Range object that represents thecolumns 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 anexpression is placed within the parentheses, along with an integer value, that identifiesthe column in the range being referenced.

When used in code that refers to two Declared Range objects, the Columns property functionsakin to a column offset; it provides the key to mapping the parts of one range to another.

Example:

Address Property Cell Reference SettingsAddress property cell reference settings are true/false settings you can employ while using theAddress 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 pairof 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; thesecond, the column’s. By default, cell reference settings for the Address property are set totrue, meaning that absolute referencing is applied for both row and column referencing.

The Columns Property

Address Property CellReference Settings

LESSON 5

Microsoft® Office Excel® 2007 - VBA148

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 160: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Figure 5-1: Address property cell referencing.

How to Automate the SUM FunctionsProcedure 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 ofUnknown 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 originalRange object to count its rows.

LESSON 5

Lesson 5: Performing Calculations 149

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 161: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

7. To the Offset property, add the Rows property.

8. In the Rows property, enter a numeric value that offsets the Range object to thedesired number of rows below the bottom of the original Range object.

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

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 valueyou 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.

LESSON 5

Microsoft® Office Excel® 2007 - VBA150

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 162: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

ACTIVITY 5-2Summing 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 amacro to automatically sum the last two columns of data presented on each worksheet. Youhave already created a macro code for cycling through the pages with a For Next loop, andnow ready to build the rest.

What You Do How You Do It

1. Declare myData and myTotal asRange objects, in the AddTotalsmacro, under the first comment.

a. Under the “Declare the Range objectshere” comment, declare myData as aRange object.

b. In the next blank line, declare myTotalas a Range object.

c. Press Enter.

2. Set the myData Range object equalto the current region of cell A7,under the second comment.

a. In the line below the “Set the data rangeobject” comment, use the Range objectto 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 ofthe active cell and press Enter.

LESSON 5

Lesson 5: Performing Calculations 151

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 163: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

3. Position myTotal, two rows belowmyData, under the third comment.

a. Under the “Position the totals rangeobject below the data range” comment,type Set

b. Press the Spacebar.

c. Add myTotal as the name of the Rangeobject to be positioned.

d. Press the Spacebar.

e. Add the assignment operator.

f. Press the Spacebar.

g. Add a reference to the myData Rangeobject.

h. Add the Offset property.

i. Within the Offset property’s parenthe-ses, add an expression that counts thenumber of rows in myData.

j. Add the Rows property.

k. Within the Rows property, enter a valuethat will position myTotal two rowsbelow the bottom of myData.

LESSON 5

Microsoft® Office Excel® 2007 - VBA152

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 164: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

4. Insert the SUM function inside thecells of myTotal, under the fourthcomment.

a. Under the “Insert the SUM function in thetotals range object” comment, typemyTotal

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 aretyping it into a cell.

g. Concatenate an expression that sets adirect mapping between myData andmyTotal with relative addressing.

h. Concatenate the closing text for the SUMfunction.

LESSON 5

Lesson 5: Performing Calculations 153

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 165: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

5. Change the first cell of myTotal sothat it contains the text “Total:” andthen delete the contents of the sec-ond and third cells, under the fifthcomment.

a. Under the “Modify the first three cells ofthe totals range object” comment, typemyTotal

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 addthe 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 andthird 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 RangeDim myTotal As RangeFor x = 1 To Worksheets.Count

Worksheets(x).Select

'Set the data range object:Range("A7").SelectSet 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:"

LESSON 5

Microsoft® Office Excel® 2007 - VBA154

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 166: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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

End Sub

6. Test the macro. a. On the Developer tab, click Macros todisplay the Macro dialog box.

b. Verify that the AddTotals macro isselected and click Run.

7. Check the macro results to view theinserted totals.

a. Select the Northeast worksheet and scrolldown to view the inserted totals at thebottom of the data columns.

b. Select the Northwest worksheet andscroll down to view the inserted totals atthe bottom of the data columns.

c. Select the Southeast worksheet and scrolldown to view the inserted totals at thebottom of the data columns.

d. Select the Southwest worksheet andscroll down to view the inserted totals atthe bottom of the data columns.

e. Save the file as My Auto Sum.xlsm andclose it.

Lesson 5 Follow-upIn this lesson, you used custom functions to perform calculations on worksheet data beyondthe limits of Excel’s built-in functions. You also automated the insertion of the SUM function atthe bottom of an unknown amount of data.

1. What is the primary reason for creating custom user-defined functions?

Answers will vary, but a custom user-defined function returns a data value that cannot beachieved by using the set of built-in functions available in Excel.

2. Why would you automate the insertion of functions?

Answers will vary, but automating insertion of functions makes it easy to calculate with-out specifying a set of data.

LESSON 5

Lesson 5: Performing Calculations 155

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 167: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Follow-upIn Microsoft® Offıce Excel®

programming language to automate many of the tasks you learned to perform in Microsoft®

Offıce Excel® ® Offıce Excel®

spreadsheets automated repetitive tasks, and deploying custom functions increased productivityto easily manage large quantities of spreadsheets.

1. What trade-off must be estimated when deciding to create macros to complete a task?

Whether the time and effort involved in creating the macros will be outweighed by thetime saved by automating the task.

2. Which tools related to creating and applying macros are the most powerful in your day-to-day use of Excel?

Answers might include: the macro recorder or customizing toolbars, menus, and buttons.

3. Can you think of additional ways in which VBA-scripted macros can solve businessproblems besides the scenarios presented in this course?

Answers will vary.

What’s Next?This is the last course in the series.

FOLLOW-UP

Microsoft® Office Excel® 2007 - VBA156

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

2007 - VBA, you applied the Visual Basic for Applications (VBA)

2007 - Level 1 and Microsoft 2007 - Level 2. Applying VBA to

Page 168: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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 practicedimmediately following the lesson or whether they require separate setup from the main lessoncontent. Lesson-level lab setup information is listed in the front of this manual in the coursesetup section.

LESSON 1 LAB 1Recording 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 openspreadsheet, 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’sbackground 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

LESSON

LABS

Lesson Labs 157

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 169: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

5. Close the blank workbook.

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 1Creating 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 reportthat 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 individualworksheets, 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 thecollated 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 eachclass section.

• Insert the report header text, including the section’s name, for each sectionworksheet.

• Format the report header text for each section worksheet, including the autofittedcolumn widths.

4. In Visual Basic Editor, at the bottom of the list of macros, in a blank line belowthe last line of code, type Sub ReportGenerator() to create a new emptymacro.

LESSON

LABS

Microsoft® Office Excel® 2007 - VBA158

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 170: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

5. In the ReportGenerator macro, create a loop structure that calls each recordedmacro to format each section’s grade sheet by: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 foreach section.

c. Inserting the report header text, including the section’s name, for each sectionworksheet.

d. Formatting the report header text for each section worksheet.

e. Formatting the columns so that the report text is correctly spaced on each sectionworksheet.

You must be careful to test and debug your code during this phase of the lab. Otherwise, you might ruin yourdata, 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 appropriatelyspaced.

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

Lesson Labs 159

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 171: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

LESSON 3 LAB 1Building 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 firstsemester grades for Freshman English. Your colleagues want to be able to review the gradesunder 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. (Sincethe data will not be changing, you do not have to worry about entering additionalcode to resize the sort ranges).

2. In Visual Basic Editor, at the bottom of the list of macros, in a blank line belowthe last line of code, type Sub InteractiveGradeSheet() to create a newempty macro.

3. Using an input box, a Select Case structure, and a message box, enter the codenecessary 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 ofits 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.

LESSON

LABS

Microsoft® Office Excel® 2007 - VBA160

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 172: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

LESSON 4 LAB 1Moving 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 tofigure out a way to move a quarter’s worth (13 weeks) of the worksheets for each quarter tothe 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, andthen 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 thebeginning 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’sworksheets 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 belowthe 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 13worksheets in the workbook.

7. Test the PrintQuarter macro until you are satisfied with your results.

LESSON

LABS

Lesson Labs 161

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 173: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

LESSON 5 LAB 1Creating 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 wayto calculate the sales commissions based on the amount of money invested by a customer. Heprovides 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 thesales 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 valueequal to the sales commission.

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

2. On the worksheet, in cell F7, use the SalesFee function as a formula. Designatecell E7 as the argument for the function.

3. Copy the function you just entered into the other empty cells in the Commissioncolumn.

4. Cross-check your work by calculating a commission manually for at least onetransaction in each category.

View the code in xLLL5.xlsm for the solution.

LESSON

LABS

Microsoft® Office Excel® 2007 - VBA162

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 174: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

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

LABS

Lesson Labs 163

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 175: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Microsoft® Office Excel® 2007 - VBA164

NOTES

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 176: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

ActiveSheet objectAn Excel VBA object that represents the cur-rently active worksheet in the workbook.

Add methodA method of the Worksheetscollection object used to add a new,blank worksheet in a worksheet list.

Address property cell reference settingsTwo true/false settings you can employ whileusing the Address property to concatenate textfor formulas that require absolute or relativecell referencing when inserted in a cell range.

Address propertyA property of the ActiveCell object repre-senting a string value describing the locationof the currently active cell.

argumentA variable used to pass data from a worksheetto a function for processing.

arithmetic operatorsOperators used in calculating mathematicalexpressions.

assignment operators (=)A VBA language component used to managethe flow of data into and out of variables.

AutoFit methodA method of the Columns object used tochange the widths of the column range.

Call commandAn Excel VBA language component used torun a macro from another macro.

code continuation characterA VBA language component that enables thepresentation of an unusually long VBA com-mand as wrapped text on several lines.

Columns objectAn Excel VBA object that represents one ormore columns on a worksheet.

Columns propertyA property of a Declared Range object thatrepresents the columns in the range.

comparison operatorsOperators used to evaluate as true or false tocheck whether a data value meets a criterion.

ConcatenationThe act of connecting two or more pieces oftext information together with an ampersandto form a single, longer piece of text.

constantsVariables whose values are predefined andunchangeable in VBA.

Copy method of ActiveSheet objectA method of the ActiveSheet object usedto copy currently selected worksheet data tothe Excel Clipboard.

Copy method of Worksheet collectionobjectA method of the Worksheetscollection object used to make a dupli-cate of an existing worksheet in a worksheetlist.

Count propertyA property of the Worksheetscollection object; which contains an inte-ger value representing the number ofworksheets in the currently active workbook.

GLOSSARY

GLOSSARY

Glossary 165

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 177: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

counter variableA variable used in a For Next loop tocount the number of times the loop repeatsthe code inside it.

CurrentRegion propertyA property of the ActiveCell object thatdescribes the largest possible range of cellsholding data in which the currently active cellis contained.

data typesDifferent kinds of data you use when creatingmacros to process information.

DateSerial functionA built-in VBA function that accepts integerdata, processes it, and returns a Date datatype.

debugging processThe means by which you can identify, locate,and fix errors in macro code.

debugging toolsVBE tools that you can use to locate, exam-ine, and fix mistakes in VBA code.

Decision structuresCode groups that enable macro developers tocause a macro to perform different actionsbased on varying inputs.

Declared Range objectA VBA object that represents a named range.

Delete methodA method of the Worksheetscollection object used to delete aworksheet from a worksheet list.

digital certificateAn electronic file that contains unique infor-mation about a specific person.

digital signatureA content authentication tool that authenti-cates the sender and ensures the integrity ofthe digital document.

Do loopA code group that repeats the execution of aseries of VBA commands until an evaluativecriterion is met.

Else clauseAn optional clause in the If Then decisionstructure invoked when the criterion expres-sion in the If Then statement is evaluated to aBoolean value of false.

End propertyAn Excel VBA property often used with theSelection object to locate the beginning orend of data being generated on a worksheet.

expressionsCombinations of data, operators, functions,and variables that, together, process informa-tion to yield a single data value.

Font propertyAn Excel VBA property used to set how textwill appear on a worksheet.

For Next loopA code group that repeats the execution of aseries of VBA commands by using a countervariable.

Format functionA built-in VBA function that can convert datedata into string data.

Formula propertyA property of a Declared Range objectthat is used to insert formulas in the cells ofan indicated range.

function callA coding context in which a function causesanother function to perform data calculations.

If ThenA VBA code structure that enables the codeto be executed or ignored depending on thevalue of an expression.

input boxA dialog box consisting of a message to themacro user, a text box into which the user cantype requested data, and at least one button,which the user can click.

InputBox functionA built-in VBA function that governs how aninput box is displayed.

GLOSSARY

Microsoft® Office Excel® 2007 - VBA166

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 178: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

logical operatorsOperators that compare two or more true/falsevalues.

Macro dialog boxA dialog box that allows you to create, run,edit, or delete the selected macro.

Macro RecorderAn Excel tool you can use to create a macroby recording actions you take in the work-book.

macroA task automation tool that executes a set ofcommands to automate frequently repeatedsteps.

message boxUsed by macro developers to capture userinput when a macro runs.

methodA set of short built-in programs whose actionschange the referenced worksheet component.

moduleA project entity, similar to a text file, thatstores macro code.

Modules folderThe location in a project where macro code isstored.

Move methodA method of the Worksheetscollection object that moves a worksheetfrom one position in the worksheet list toanother.

MsgBox functionA built-in VBA function that governs how amessage box is displayed.

Name propertyAn Excel VBA property that contains textdata representing the name of the object usingit.

Object-Oriented ProgrammingA programming method that focuses on mod-eling entities and their interactions.

objectA programming construct that, for the mostpart, mimics the characteristics of the compo-nents of an Excel workbook.

Offset propertyA property of the ActiveCell object usedto measure a distance from the currentlyactive cell.

operatorsSymbols you use to do tasks such as perform-ing arithmetic, comparing two numbers,assigning data to a worksheet cell, or answer-ing questions of logic.

Paste methodA method of the ActiveSheet object usedto paste Clipboard contents into a selection onthe worksheet.

Personal Macro WorkbookA storage location where you can create andsave the macros you create in Excel.

PrintOut methodA method of the Worksheetscollection object used to send worksheetsto the printer.

PrintPreview methodA method of the Worksheetscollection object used to displayworksheets in the window.

private functionA function that can be used only by theproject containing the module where the func-tion code exists.

projectThe VBE representation of a set of relation-ships that exist among the parts of an openExcel workbook.

propertyA set of built-in storage locations to keeptrack of, work with, and affect the characteris-tics of the worksheet component to which itrefers.

public functionA function that can be shared by multipleprojects.

GLOSSARY

Glossary 167

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 179: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Range object cell addressingA VBA cell-addressing convention that orga-nizes a cell range assigned to a DeclaredRange object.

Range objectAn Excel VBA object that represents a rangeof cells on a worksheet.

Rows propertyA property of a Declared Range objectthat represents the rows in a range.

Select CaseA VBA code structure that enables the codein a macro to be executed or ignored basedon a condition, such as an entered responsefrom a user.

Select methodAn Excel VBA method used to select part ofa worksheet.

Selection objectAn Excel VBA object that represents the cur-rent selection on the worksheet: a selectedcell, a selected range, a selected column, andso on.

Set statementA VBA language component used to assign acell range to a Declared Range object.

User-defined functionA function created with VBA code to return adata value that cannot be achieved by usingthe set of functions available in Excel.

Value propertyA VBA property that represents the datastored in an object, such as a worksheet cell.

variable naming rulesRules that prescribe the kinds of names youcan give to variables.

variablesNamed locations you can create and use in amacro to store data for processing.

VBA commentA line of explanatory text that you can enterin a macro to help identify and document themacro, and to provide the programmer withreminders on what the macro is supposed todo.

VBA(Visual Basic for Applications) A program-ming language used to create macros inMicrosoft Office applications. When yourecord a macro, Excel automatically translatesthe keystrokes and commands into VBA codelanguage, and creates and stores the macro.

vbCrLf characterA VBA language component used to indicatewhere the text in a long input box or messagebox should be broken and placed on the nextline.

VBE(Visual Basic Editor) A part of the Excelapplication where you can create, edit, anddelete macro code.

Worksheets collection objectAn Excel VBA object that manages the col-lection of worksheets in the workbook.

GLOSSARY

Microsoft® Office Excel® 2007 - VBA168

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 180: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

Aargument, 139

Ccharacter

code continuation, 89

vbCrLf, 90

command

Call, 66

commands

direction, 68

concatenation, 37

constants, 88

counter variable, 53

Ddata types, 49

dialog boxes

Macro, 3

Trust Center, 28

digital certificate, 27

digital signature, 28

EElse clause, 140

expressions, 118

Ffolders

Modules, 10

function call, 139

functions

DateSerial, 118

Format, 119

InputBox, 87

MsgBox, 89

private, 139

public, 139

User-defined, 138

Ggroups

code, 17

Iinput box, 85

Lloops

Do, 53

For Next, 53

MMacro Recorder, 4

macros, 3

message box, 84

methods, 11

Add, 108

AutoFit, 64

Copy, 56, 109

Delete, 109

Move, 123

Paste, 56

PrintOut, 127

PrintPreview, 127

Select, 45

modules, 10

OObject-Oriented Programming, 2

objects, 10

ActiveSheet, 35

Columns, 64

Declared Range, 145

Range, 44

Selection, 34

Worksheets collection, 54

operators, 51

arithmetic, 51

INDEX

INDEX

Index 169

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 181: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

assignment, 51

comparison, 52

logical, 52

PPersonal 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

RRange object cell addressing, 146

SSet statement, 146

settings

macro security, 28

structures

Decision, 91

If Then, 92

Select Case, 91

Ttools

debugging, 17

Vvariable 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

INDEX

Microsoft® Office Excel® 2007 - VBA170

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n

Page 182: 2007-VBA - Advanced Technology Support, Inc® OfficeExcel® 2007-VBA Course ... Advanced Microsoft Excel professionals who need to automate Excel spreadsheet tasks using Visual Basic

DO N

OT

DUPL

ICAT

E

Inst

ruct

or E

ditio

n