Vous êtes sur la page 1sur 1515

Microsoft® Excel® 2013
Programming by Example

LICENSE, DISCLAIMER OF LIABILITY, AND LIMITED WARRANTY
By purchasing or using this book (the “Work”), you agree that this license grants
permission to use the contents contained herein, but does not give you the right of
ownership to any of the textual content in the book or ownership to any of the
information or products contained in it. This license does not permit uploading of the
Work onto the Internet or on a network (of any kind) without the written consent of the
Publisher. Duplication or dissemination of any text, code, simulations, images, etc.
contained herein is limited to and subject to licensing terms for the respective
products, and permission must be obtained from the Publisher or the owner of the
content, etc., in order to reproduce or network any portion of the textual material (in
any media) that is contained in the Work.
Mercury Learning And Information LLC (“MLI” or “the Publisher”) and anyone
involved in the creation, writing, or production of the companion disc, accompanying
algorithms, code, or computer programs (“the software”), and any accompanying Web
site or software of the Work, cannot and do not warrant the performance or results that
might be obtained by using the contents of the Work. The author, developers, and the
Publisher have used their best efforts to insure the accuracy and functionality of the
textual material and/or programs contained in this package; we, however, make no
warranty of any kind, express or implied, regarding the performance of these contents
or programs. The Work is sold “as is” without warranty (except for defective
materials used in manufacturing the book or due to faulty workmanship).
The author, developers, and the publisher of any accompanying content, and
anyone involved in the composition, production, and manufacturing of this work will
not be liable for damages of any kind arising out of the use of (or the inability to use)
the algorithms, source code, computer programs, or textual material contained in this
publication. This includes, but is not limited to, loss of revenue or profit, or other
incidental, physical, or consequential damages arising out of the use of this Work.
The sole remedy in the event of a claim of any kind is expressly limited to
replacement of the book, and only at the discretion of the Publisher. The use of
“implied warranty” and certain “exclusions” vary from state to state, and might not
apply to the purchaser of this product.

Microsoft® Excel® 2013
Programming by Example
with VBA, XML, and ASP
Julitta Korol

Copyright ©2014 by Mercury Learning and Information LLC. All rights reserved.

This publication, portions of it, or any accompanying software may not be
reproduced in any way, stored in a retrieval system of any type, or transmitted by
any means, media, electronic display or mechanical display, including, but not
limited to, photocopy, recording, Internet postings, or scanning, without prior
permission in writing from the publisher.
Publisher: David Pallai
Mercury Learning and Information
22841 Quicksilver Drive
Dulles, VA 20166
info@merclearning.com
www.merclearning.com
1-800-758-3756
This book is printed on acid-free paper.
Julitta Korol. Microsoft Excel 2013 Programming by Example with VBA, XML,
and ASP.
ISBN: 978-1-938549-91-5
The publisher recognizes and respects all marks used by companies,
manufacturers, and developers as a means to distinguish their products. All brand
names and product names mentioned in this book are trademarks or service marks of
their respective companies. Any omission or misuse (of any kind) of service marks or
trademarks, etc. is not an attempt to infringe on the property of others.
Library of Congress Control Number: 2013958097
141516321
Our titles are available for adoption, license, or bulk purchase by institutions,

corporations, etc. For additional information, please contact the Customer Service
Dept. at 1-800-758-3756 (toll free).
The sole obligation of Mercury Learning and Information to the purchaser is to
replace the book and/or disc, based on defective materials or faulty workmanship, but
not based on the operation or functionality of the product.

To Tana-Lee Rebhan, without whom none of this
would have been possible in the required time frame.

Contents
Acknowledgments
Introduction
PART I—INTRODUCTION TO EXCEL 2013 VBA PROGRAMMING
Chapter 1 Automating Worksheet Tasks with Macros
What Are Macros?
Common Uses for Macros
VBA in 32-bit and 64-bit Versions of Office 2013
Excel 2013 File Formats
Macro Security Settings
Planning a Macro
Recording a Macro
Using Relative or Absolute References in Macros
Executing Macros
Editing Macros

Macro Comments
Analyzing the Macro Code
Cleaning Up the Macro Code
Testing the Modified Macro
Two Levels of Macro Execution
Improving Your Macro
Renaming the Macro
Other Methods of Running Macros
Running the Macro Using a Keyboard Shortcut
Running the Macro from the Quick Access Toolbar
Running the Macro from a Worksheet Button
Saving Macros
Printing Macros
Storing Macros in the Personal Macro Workbook
Chapter Summary

Chapter 2 Exploring the Visual Basic Editor (VBE)
Understanding the Project Explorer Window
Understanding the Properties Window
Understanding the Code Window
Other Windows in the Visual Basic Editor Window
Assigning a Name to the VBA Project
Renaming the Module
Understanding Digital Signatures
Creating a Digital Certificate
Signing a VBA Project
Chapter Summary
Chapter 3 Excel VBA Fundamentals
Understanding Instructions, Modules, and Procedures
Calling a Procedure from Another Project

Understanding Objects, Properties, and Methods
Microsoft Excel Object Model
Writing VBA Statements
Syntax versus Grammar
Breaking Up Long VBA Statements
Understanding VBA Errors
In Search of Help
On-the-Fly Syntax and Programming Assistance
List Properties/Methods
List Constants
Parameter Info
Quick Info
Complete Word
Indent/Outdent
Comment Block/Uncomment Block

Using the Object Browser
Using the VBA Object Library
Locating Procedures with the Object Browser
Using the Immediate Window
Obtaining Information in the Immediate Window
Learning about Objects
Working with Worksheet Cells
Using the Range Property
Using the Cells Property
Using the Offset Property
Other Methods of Selecting Cells
Selecting Rows and Columns
Obtaining Information about the Worksheet
Entering Data in a Worksheet

Returning Information Entered in a Worksheet
Finding Out about Cell Formatting
Moving, Copying, and Deleting Cells
Working with Workbooks and Worksheets
Working with Windows
Managing the Excel Application
Chapter Summary
Chapter 4 Using Variables, Data Types, and Constants
Saving Results of VBA Statements
Data Types
What Are Variables?
How to Create Variables
How to Declare Variables
Specifying the Data Type of a Variable
Assigning Values to Variables

Converting Between Data Types
Forcing Declaration of Variables
Understanding the Scope of Variables
Procedure-Level (Local) Variables
Module-Level Variables
Project-Level Variables
Lifetime of Variables
Understanding and Using Static Variables
Declaring and Using Object Variables
Using Specific Object Variables
Finding a Variable Definition
Determining a Data Type of a Variable
Using Constants in VBA Procedures
Built-in Constants

Chapter Summary
Chapter 5 VBA Procedures: Subroutines and Functions
About Function Procedures
Creating a Function Procedure
Executing a Function Procedure
Running a Function Procedure from a Worksheet
Running a Function Procedure from Another VBA Procedure
Ensuring Availability of Your Custom Functions
Passing Arguments
Specifying Argument Types
Passing Arguments by Reference and Value
Using Optional Arguments
Locating Built-in Functions
Using the MsgBox Function
Returning Values from the MsgBox Function

Using the InputBox Function
Determining and Converting Data Types
Using the InputBox Method
Using Master Procedures and Subprocedures
Chapter Summary
PART II—CONTROLLING PROGRAM EXECUTION
Chapter 6 Decision Making with VBA
Relational and Logical Operators
If…Then Statement
Decisions Based on More Than One Condition
If Block Instructions and Indenting
If…Then…Else Statement
If…Then…ElseIf Statement
Nested If…Then Statements
Select Case Statement

Using Is with the Case Clause
Specifying a Range of Values in a Case Clause
Specifying Multiple Expressions in a Case Clause
Chapter Summary
Chapter 7 Repeating Actions in VBA
Do Loops: Do…While and Do…Until
Watching a Procedure Execute
While…Wend Loop
For…Next Loop
For Each…Next Loop
Exiting Loops Early
Nested Loops
Chapter Summary
PART III—KEEPING TRACK OF MULTIPLE VALUES
Chapter 8 Working with Arrays

What Is an Array?
Declaring Arrays
Array Upper and Lower Bounds
Initializing an Array
Filling an Array Using Individual Assignment Statements
Filling an Array Using the Array Function
Filling an Array Using For…Next Loop
Using Arrays in VBA Procedures
Arrays and Looping Statements
Using a Two-Dimensional Array
Static and Dynamic Arrays
Array Functions
The Array Function
The Is Array Function

The Erase Function
The LBound and UBound Functions
Errors in Arrays
Parameter Arrays
Sorting an Array
Passing Arrays to Function Procedures
Chapter Summary
Chapter 9 Working with Collections and Class Modules
Working with Collections
Declaring a Custom Collection
Adding Objects to a Custom Collection
Removing Objects from a Custom Collection
Creating Custom Objects
Creating a Class
Variable Declarations

Defining the Properties for the Class
Creating the Property Get Procedures
Creating the Property Let Procedures
Creating the Class Methods
Creating an Instance of a Class
Event Procedures in the Class Module
Creating a Form for Data Collection
Creating a Worksheet for Data Output
Writing Code behind the User Form
Working with the Custom CEmployee Class
Watching the Execution of Your VBA Procedures
Chapter Summary
PART IV—ERROR HANDLING AND DEBUGGING
Chapter 10 VBE Tools for Testing and Debugging
Testing VBA Procedures

Stopping a Procedure
Using Breakpoints
When to Use a Breakpoint
Using the Immediate Window in Break Mode
Using the Stop Statement
Using the Assert Statement
Using the Watch Window
Removing Watch Expressions
Using Quick Watch
Using the Locals Window and the Call Stack Dialog Box
Stepping through VBA Procedures
Stepping Over a Procedure and Running to Cursor
Setting the Next Statement
Showing the Next Statement

Stopping and Resetting VBA Procedures
Chapter Summary
Chapter 11 Conditional Compilation and Error Trapping
Understanding and Using Conditional Compilation
Navigating with Bookmarks
Trapping Errors
Using the Err Object
Procedure Testing
Setting Error Trapping Options in your Visual Basic Project
Chapter Summary
PART V—MANIPULATING FILES AND FOLDERS WITH VBA
Chapter 12 File and Folder Manipulation with VBA
Manipulating Files and Folders
Finding Out the Name of the Active Folder
Changing the Name of a File or Folder

Checking the Existence of a File or Folder
Finding out the Date and Time the File Was Modified
Finding out the Size of a File (the FileLen Function)
Returning and Setting File Attributes (the GetAttr and SetAttr Functions)
Changing the Default Folder or Drive (the ChDir and ChDrive Statements)
Creating and Deleting Folders (the MkDir and RmDir Statements)
Copying Files (the FileCopy Statement)
Deleting Files (the Kill Statement)
Chapter Summary
Chapter 13 File and Folder Manipulation with Windows Script Host
(WSH)
Finding Information about Files with WSH
Methods and Properties of FileSystemObject
Properties of the File Object
Properties of the Folder Object

Properties of the Drive Object
Creating a Text File Using WSH
Performing Other Operations with WSH
Running Other Applications
Obtaining Information about Windows
Retrieving Information about the User, Domain, or Computer
Creating Shortcuts
Listing Shortcut Files
Chapter Summary
Chapter 14 Using Low-Level File Access
File Access Types
Working with Sequential Files
Reading Data Stored in Sequential Files
Reading a File Line by Line
Reading Characters from Sequential Files

Reading Delimited Text Files
Writing Data to Sequential Files
Using Write # and Print # Statements
Working with Random Access Files
Working with Binary Files
Chapter Summary
PART VI—CONTROLLING OTHER APPLICATIONS WITH VBA
Chapter 15 Using Excel VBA to Interact with Other Applications
Launching Applications
Moving between Applications
Controlling Another Application
Other Methods of Controlling Applications
Understanding Automation
Understanding Linking and Embedding
Linking and Embedding with VBA

COM and Automation
Understanding Binding
Late Binding
Early Binding
Establishing a Reference to a Type Library
Creating Automation Objects
Using the CreateObject Function
Creating a New Word Document Using Automation
Using the GetObject Function
Opening an Existing Word Document
Using the New Keyword
Using Automation to Access Microsoft Outlook
Chapter Summary
Chapter 16 Using Excel with Microsoft Access

Object Libraries
Setting Up References to Object Libraries
Connecting to Access
Opening an Access Database
Using Automation to Connect to an Access Database
Using DAO to Connect to an Access Database
Using ADO to Connect to an Access Database
Performing Access Tasks from Excel
Creating a New Access Database with DAO
Opening an Access Form
Opening an Access Report
Creating a New Access Database with ADO
Running a Select Query
Running a Parameter Query
Calling an Access Function

Retrieving Access Data into an Excel Worksheet
Retrieving Data with the GetRows Method
Retrieving Data with the CopyFromRecordset Method
Retrieving Data with the TransferSpreadsheet Method
Using the OpenDatabase Method
Creating a Text File from Access Data
Creating a Query Table from Access Data
Creating an Embedded Chart from Access Data
Transferring the Excel Worksheet to an Access Database 501
Linking an Excel Worksheet to an Access Database
Importing an Excel Worksheet to an Access Database
Placing Excel Data in an Access Table
Chapter Summary
PART VII—ENHANCING THE USER EXPERIENCE
Chapter 17 Event-Driven Programming

Introduction to Event Procedures
Writing Your First Event Procedure
Enabling and Disabling Events
Event Sequences
Worksheet Events
Worksheet_Activate()
Worksheet_Deactivate()
Worksheet_SelectionChange()
Worksheet_Change()
Worksheet_Calculate()
Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
Workbook Events
Workbook_Activate()

ByVal Arg2 . Cancel As Boolean) Workbook_BeforePrint(Cancel As Boolean) Workbook_BeforeClose(Cancel As Boolean) Workbook_NewSheet(ByVal Sh As Object) Workbook_WindowActivate(ByVal Wn As Window) Workbook_WindowDeactivate(ByVal Wn As Window) Workbook_WindowResize(ByVal Wn As Window) PivotTable Events Chart Events Writing Event Procedures for a Chart Located on a Chart Sheet Chart_Activate() Chart_Deactivate() Chart_Select(ByVal ElementID As Long. ByVal Arg1 As Long.Workbook_Deactivate() Workbook_Open() Workbook_BeforeSave(ByVal SaveAsUI As Boolean.

ByVal x As Long. ByVal Shift As Long.As Long) Chart_Calculate() Chart_BeforeRightClick() Chart_MouseDown(ByVal Button As Long. ByVal y As Long) Writing Event Procedures for Embedded Charts Events Recognized by the Application Object Query Table Events Other Excel Events OnTime Method OnKey Method Chapter Summary Chapter 18 Using Dialog Boxes Excel Dialog Boxes File Open and File Save As Dialog Boxes .

Filtering Files Selecting Files GetOpenFilename and GetSaveAsFilename Methods Using the GetOpenFilename Method Using the GetSaveAsFilename Method Chapter Summary Chapter 19 Creating Custom Forms Creating Forms Tools for Creating User Forms Placing Controls on a Form Setting Grid Options Sample Application 1: Info Survey Setting Up the Custom Form Inserting a New Form and Setting Up the Initial Properties Changing the Size of the Form .

Checkboxes.Adding Buttons. and Other Controls to a Form Changing Control Names and Properties Setting the Tab Order Preparing a Worksheet to Store Custom Form Data Displaying a Custom Form Understanding Form and Control Events Writing VBA Procedures to Respond to Form and Control Events Writing a Procedure to Initialize the Form Writing a Procedure to Populate the Listbox Control Writing a Procedure to Control Option Buttons Writing Procedures to Synchronize the Text Box with the Spin Button Writing a Procedure that Closes the User Form Transferring Form Data to the Worksheet Using the Info Survey Application .

Sample Application 2: Students and Exams Using MultiPage and TabStrip Controls Setting Up the Worksheet for the Students and Exams Application Writing VBA Procedures for the Students and Exams Custom Form Using the Students and Exams Custom Form Chapter Summary Chapter 20 Formatting Worksheets with VBA Performing Basic Formatting Tasks with VBA Formatting Numbers Formatting Text Formatting Dates Formatting Columns and Rows Formatting Headers and Footers Formatting Cell Appearance Removing Formatting from Cells and Ranges .

Performing Advanced Formatting Tasks with VBA Conditional Formatting Using VBA Conditional Formatting Rule Precedence Deleting Rules with VBA Using Data Bars Using Color Scales Using Icon Sets Formatting with Themes Formatting with Shapes Formatting with Sparklines Understanding Sparkline Groups Programming Sparklines with VBA Formatting with Styles Chapter Summary .

Chapter 21 Context Menu Programming and Ribbon Customizations Working with Context Menus Modifying a Built-in Context Menu Removing a Custom Item from a Context Menu Disabling and Hiding Items on a Context Menu Adding a Context Menu to a Command Button Finding a FaceID Value of an Image A Quick Overview of the Ribbon Interface Ribbon Programming with XML and VBA Creating the Ribbon Customization XML Markup Loading Ribbon Customizations Errors on Loading Ribbon Customizations Using Images in Ribbon Customizations Using Various Controls in Ribbon Customizations Creating Toggle Buttons .

and Submenus Creating Checkboxes Creating Edit Boxes Creating Combo Boxes and Drop-Downs Creating a Gallery Control Creating a Dialog Box Launcher Disabling a Control Repurposing a Built-in Control Refreshing the Ribbon The CommandBar Objects and the Ribbon Tab Activation and Group Auto-Scaling Customizing the Backstage View Customizing the Microsoft Office Button Menu in Excel 2013 Customizing the Quick Access Toolbar (QAT) .Creating Split Buttons. Menus.

Modifying Context Menus Using Ribbon Customizations Chapter Summary PART VIII—PROGRAMMING EXCEL SPECIAL FEATURES Chapter 22 Printing and Sending Email from Excel Controlling the Page Setup Controlling the Settings on the Page Layout Tab Controlling the Settings on the Margins Tab Controlling the Settings on the Header/Footer Tab Controlling the Settings on the Sheet Tab Retrieving Current Values from the Page Setup Dialog Box Previewing a Worksheet Changing the Active Printer Printing a Worksheet with VBA Disabling Printing and Print Previewing Using Printing Events .

Grouping. and Sorting a PivotTable Report Hiding Items in a PivotTable Adding Calculated Fields and Items to a PivotTable Creating a PivotChart Report Using VBA .Sending Email from Excel Sending Email Using the SendMail Method Sending Email Using the MsoEnvelope Object Sending Bulk Email from Excel via Outlook Chapter Summary Chapter 23 Programming PivotTables and PivotCharts Creating a PivotTable Report Removing PivotTable Detail Worksheets with VBA Creating a PivotTable Report Programmatically Creating a PivotTable Report from an Access Database Using the CreatePivotTable Method of the PivotCache Object Formatting.

Understanding and Using Slicers Creating Slicers Manually Working with Slicers Using VBA Data Model Functionality and PivotTables Programmatic Access to the Data Model Chapter Summary Chapter 24 Using and Programming Excel Tables Understanding Excel Tables Creating a Table Using Built-in Commands Creating a Table Using VBA Understanding Column Headings in the Table Multiple Tables in a Worksheet Working with the Excel ListObject Filtering Data in Excel Tables Using AutoFilter .

Filtering Data in Excel Tables Using Slicers Deleting Worksheet Tables Chapter Summary Chapter 25 Programming Special Features Tab Object Speech Object SpellingOptions Object CellFormat Object Characters Object AutoCorrect Object FormatCondition Object Graphic Object CustomProperty Object Sort Object Excel8CompabilityMode Property .

Chapter Summary Chapter 26 Programming the Visual Basic Editor (VBE) The Visual Basic Editor Object Model Understanding the VBE Objects Accessing the VBA Project Finding Information about a VBA Project VBA Project Protection Working with Modules Listing All Modules in a Workbook Adding a Module to a Workbook Removing a Module Deleting All Code from a Module Deleting Empty Modules Copying (Exporting/Importing) a Module .

Copying (Exporting/Importing) All Modules Working with Procedures Listing All Procedures in All Modules Adding a Procedure Deleting a Procedure Creating an Event Procedure Working with UserForms Creating and Manipulating UserForms Copying UserForms Programmatically Working with References Creating a List of References Adding a Reference Removing a Reference Checking for Broken References Working with Windows .

Working with VBE Menus and Toolbars Generating a Listing of VBE CommandBars and Controls Adding a CommandBar Button to the VBE Removing a CommandBar Button from the VBE Chapter Summary PART IX—EXCEL AND WEB TECHNOLOGIES Chapter 27 HTML Programming and Web Queries Creating Hyperlinks Using VBA Creating and Publishing HTML Files Using VBA Web Queries Creating and Running Web Queries with VBA Web Queries with Parameters Static and Dynamic Parameters Dynamic Web Queries Refreshing Data .

Chapter Summary Chapter 28 Excel and Active Server Pages Introduction to Active Server Pages The ASP Object Model HTML and VBScript Creating an ASP Page Installing Internet Information Services (IIS) Creating a Virtual Directory Setting ASP Configuration Properties Turning Off Friendly HTTP Error Messages Running Your First ASP Script Sending Data from an HTML Form to an Excel Workbook Sending Excel Data to the Internet Browser Chapter Summary .

Chapter 29 Using XML in Excel 2013 What Is XML? Well-Formed XML Documents Validating XML Documents Editing and Viewing an XML Document Opening an XML Document in Excel Working with XML Maps Working with XML Tables Exporting an XML Table XML Export Precautions Validating XML Data Programming XML Maps Adding an XML Map to a Workbook Deleting Existing XML Maps Exporting and Importing Data via an XML Map .

Binding an XML Map to an XML Data Source Refreshing XML Tables from an XML Data Source Viewing the XML Schema Creating XML Schema Files Using XML Events The XML Document Object Model Working with XML Document Nodes Retrieving Information from Element Nodes XML via ADO Saving an ADO Recordset to Disk as XML Loading an ADO Recordset Saving an ADO Recordset into the DOMDocument Object Understanding Namespaces Understanding Open XML Files .

Manipulating Open XML Files with VBA Chapter Summary PART X GOING BEYOND THE LIMITS OF VBA Chapter 30 Calling Windows API Functions from VBA Understanding the Windows API Library Files How to Declare a Windows API Function Passing Arguments to API Functions Understanding the API Data Types and Constants Using Constants with Windows API Functions 64-bit Office and Windows API Accessing Windows API Documentation Using Windows API Functions in Excel Chapter Summary Index .

To the compositor. for the thorough review of my writing. I’d like to acknowledge readers like you who cared enough to post reviews of the previous edition of this book online. This book is dedicated to you. for his patience during this long project and having to put up with frequent take out dinners. Special thanks to my husband. my dearest colleague.Acknowledgments First I’d like to express my gratitude to everyone at Mercury Learning and Information. Your invaluable feedback has helped me raise the quality of this work by including the material that matters to you most. for her production expertise and keeping track of all the edits and file processing issues. . In particular. Tana-Lee. checking the programming code and running it in Microsoft Excel to ensure it worked properly. Tana-Lee Rebhan. David Pallai. Thanks. Tracey McCrea. for all the typesetting efforts that gave this book the right look and feel. A sincere thank-you to my publisher. Paul. A whole bunch of thanks go to the editorial team for working so hard to bring this book to print. I would like to thank the copyeditor. Please continue to inspire me with your ideas and suggestions. To Jennifer Blaney. Swaminathan at SwaRadha Typesetting. Finally. for offering me the opportunity to update this book to the new 2013 version and tirelessly keeping things on track during this long project. my technical proofreader did an excellent job formatting and editing the text. L.

The book’s approach is to learn by doing. VBA procedures. This book shows you what’s doable with Microsoft® Excel® 2013 beyond the standard user interface. If you have not yet discovered them. As this was a very time-consuming and repetitive task. By executing special commands and statements and using a number of Excel’s built-in programming tools. I became immensely interested in automating the whole process. And while the computer was busy performing the same tasks over and over again. and Excel is still working like magic for me and a great number of other people who took time to familiarize themselves with its programming interface. I was working in a sales department and it was my job to calculate sales commissions and send the monthly and quarterly statements to our sales representatives spread all over the United States. all I had was the built-in documentation that was hard to read. fully automated form to gather data and store the results in a worksheet. I succeeded. and XML documents. XML. One is ASP (short for Active Server Pages) and the other is XML (or Extensible Markup Language). ASP pages. Microsoft Excel 2013 Programming By Example with VBA. and ASP will lead you through the process of creating your first macros. you’ve picked up the right book. VBScripts. It automatically calculated our salespeople’s commissions and printed out nicely formatted statements. Along the way. If you’d like to join these people and have Excel do magical things for you as well. you can work smarter than you ever thought possible. practical “how-to” examples and plenty of illustrations. There weren’t as many books written on the subject. Simply turn on the computer. I will show you how. launch Microsoft Excel. But before you get started. all the tools you need are built into Excel. there are detailed. Besides this book. from start to finish. open this book. In those days it wasn’t easy to get started in programming on your own.Introduction If you ever wanted to open a new worksheet without using built-in commands or create a custom. and do all the guided Hands-On exercises. I was free to deal with other more interesting projects. this book provides an easy step-by-step introduction to VBA and other hot technologies that work nicely with Microsoft Excel. VBA (Visual Basic for Applications). my first macro worked like magic. When I first started programming in Excel (circa 1990). allow me to give you a short overview of the things you’ll be learning . there is no extra cost to you. This book’s purpose is to teach you how to delegate many time-consuming and repetitive tasks to Excel by using its built-in language. Nevertheless. Many years have passed since that day. There’s no better way than step by step.

You also learn how to provide additional information to your procedures before they are run and are introduced to some useful built-in functions and methods that allow you to interact with your VBA procedure users.as you progress through this book. you’ll find out how the knowledge of decisions and looping enables you to control program flow and create useful VBA procedures and functions. and methods. you begin writing and executing VBA procedures. . the use of variables. execution. While the Excel macro recorder can get you started with VBA. Visual Basic for Applications is the programming language for Microsoft Excel. You also learn about macro design. Data Types. Some of the programming tools that are not covered here are discussed and put to use in Chapter 10. you acquire the fundamentals of VBA by recording macros and examining the VBA code behind the macro using the Visual Basic Editor. Once these topics are covered. In this part of the book. Chapter 5: VBA Procedures: Subroutines and Functions —In this chapter you learn how to write two types of VBA procedures: subroutines and functions. Here you’ll also learn about different VBA components. Microsoft Excel 2013 Programming By Example with VBA. Chapter 3: Excel VBA Fundamentals—In this chapter you are introduced to basic VBA concepts such as the Microsoft Excel object model and its objects. XML. and ASP is divided into 10 parts (30 chapters) that progressively introduces you to programming Microsoft Excel 2013 as well as controlling other applications with Excel. You also learn about many tools that will assist you in writing VBA statements quicker and with fewer errors. commonly referred to as VBE. Part I introduces you to Excel 2013 VBA programming. it does not allow you to incorporate complex logic into your program. and Constants —In this chapter you are introduced to basic VBA concepts that allow you to store various pieces of information for later use. and security. Chapter 4: Using Variables. In Part II of this book. and VBA syntax. Chapter 2: Exploring the Visual Basic Editor (VBE)—In this chapter you learn almost everything you need to know about working with the Visual Basic Editor window. properties. PART I INCLUDES THE FOLLOWING FIVE CHAPTERS: Chapter 1: Automating Worksheet Tasks with Macros —In this chapter you learn how you can introduce automation into your Excel worksheets by simply using the built-in macro recorder.

While you may have planned to write a perfect VBA procedure. and how you can test the ways your program responds to run-time errors by causing them on purpose. there is always a chance that incorrectly constructed or typed code. Chapter 11: Conditional Compilation and Error Trapping —In this chapter you learn how to run the same procedure in different languages. many advanced VBA procedures will require that you implement more efficient methods of keeping track of multiple values. In Part V of the book you discover various methods of working with files and folders. Chapter 9: Working with Collections and Class Modules —In this chapter you learn how to create and use your own VBA objects and collections of objects. and learn how to .THERE ARE TWO CHAPTERS IN PART II: Chapter 6: Decision Making with VBA—In this chapter you learn how to control your program flow with a number of different decision-making statements. will cause your program to fail or produce unexpected results. Chapter 7: Repeating Actions in VBA—In this chapter you learn how you can repeat the same actions by using looping structures. In Part IV of this book you’ll learn about various methods of handling errors. you can open and manipulate files directly via the low-level file I/O (input/output) functions. or perhaps logic errors. AGAIN. In Part III of this book you’ll learn about working with groups of variables (arrays) and storing data in collections. AGAIN. You also learn about built-in array functions. Additionally. Although you can use individual variables to store data while your VBA code is executing. While VBA offers a number of built-in functions and statements for working with the file system. THERE ARE TWO CHAPTERS IN PART IV: Chapter 10: VBE Tools for Testing and Debugging —In this chapter you begin using built-in debugging tools to test your programming code and trap errors. which you can use for holding various values. you can also perform file and folder manipulation tasks via objects and methods included in the Windows Script Host installed by default on computers running the Windows operating system. and testing and debugging VBA procedures. THERE ARE TWO CHAPTERS IN PART III: Chapter 8: Working with Arrays —In this chapter you learn the concept of static and dynamic arrays.

and ASP (Mercury Learning. XML. Chapter 16: Using Excel with Microsoft Access—In this chapter you learn about accessing Microsoft Access data and running Access queries and functions from VBA procedures. . The VBA skills you acquire in Excel can be used to program any application that supports this language. PART VI CONSISTS OF THE FOLLOWING TWO CHAPTERS: Chapter 15: Using Excel VBA to Interact with Other Applications—In this chapter you learn how you can launch and control other applications from within VBA procedures written in Excel. You will also learn how to format worksheets with VBA and control Excel with event-driven programming. and Access. PART V CONSISTS OF THE FOLLOWING THREE CHAPTERS: Chapter 12: File and Folder Manipulation with VBA—In this chapter you learn about numerous VBA statements used in working with Windows files and folders. I recommend my book Microsoft Access 2013 Programming By Example with VBA. You also learn how to establish a reference to a type library and use and create Automation objects. In recent years extensive changes have been made to the Excel user interface (UI). and write three types of files. Chapter 14: Using Low-Level File Access—In this chapter you learn how to get in direct contact with your data by using the process known as low-level file I/O. Power Point. Chapter 13: File and Folder Manipulation with Windows Script Host (WSH)— In this chapter you learn how the Windows Script Host works together with VBA and allows you to get information about files and folders. It is also supported by a number of non Microsoft products. VBA is used by other Office applications such as Word. Outlook. You also learn about various types of file access. In Part VII of the book you learn how to create desired interface elements for your users via Ribbon customizations and the creation of dialog boxes and custom forms. The VBA programming language goes beyond Excel. In Part VI of the book you learn how other applications expose their objects to VBA.programmatically open. read. 2013). If you are interested in learning more about Access programming with VBA using a step-by-step approach.

In Part VIII of the book you start by writing code that automates printing and emailing. color scales.IN PART VII THERE ARE FIVE CHAPTERS: Chapter 17: Event-Driven Programming—In this chapter you learn about the types of events that can occur when you are running VBA procedures in Excel. You will learn how to use VBA to manipulate these two objects to quickly produce reports that allow you or your users to easily examine large amounts of data pulled from an Excel worksheet range or from an external data source such as an Access database. Chapter 20: Formatting Worksheets with VBA—In this chapter you learn how to perform worksheet formatting tasks with VBA by applying visual features such as data bars. and Excel tables. Next. Chapter 21: Context Menu Programming and Ribbon Customizations—In this chapter you learn how to add custom options to Excel built-in context (shortcut) menus and how to work programmatically with the Ribbon interface and Backstage View. and icon sets. Chapter 23: Programming PivotTables and PivotCharts —In this chapter you learn how to work with two powerful Microsoft Excel objects that are used for data analysis: PivotTable and PivotChart. Chapter 19: Creating Custom Forms—In this chapter you learn how to use various controls for designing user-friendly forms. Some Excel 2013 features are used more frequently than others. This chapter has two complete hands-on applications you build from scratch. PivotCharts. You gain a working knowledge of writing event procedures and handling various types of events. You are also introduced to a number of useful Excel 2013 objects. . some are only used by Excel power users and developers. and learn how to program the Visual Basic Editor itself. you gain experience in programming advanced Excel features such as PivotTables. Chapter 18: Using Dialog Boxes—In this chapter you learn about working with Excel built-in dialog boxes programmatically. PART VIII HAS THE FOLLOWING FIVE CHAPTERS: Chapter 22: Printing and Sending Email from Excel—In this chapter you learn how to control printing and emailing your workbooks via VBA code. You also learn how to produce consistent-looking worksheets by using new document themes and styles.

convert it into a table. some of the processes and operations that you may need to augment are the integral parts of the Windows operating system and can only be controlled by calling upon the Windows Application Programming Interface (API). PART IX CONSISTS OF THE FOLLOWING THREE CHAPTERS: Chapter 27: HTML Programming and Web Queries —In this chapter you learn how to create hyperlinks and publish HTML files using VBA. You also learn how to create and run various types of Web queries (dynamic. You also learn how to retrieve and send information to Excel via Active Server Pages. Chapter 26: Programming the Visual Basic Editor (VBE) —In this chapter you learn how to use numerous objects. You will learn how to retrieve information from an Access database. and methods from the Microsoft Visual Basic for Applications Extensibility Object Library to control the Visual Basic Editor to gain full control over Excel. In Part IX of the book you are introduced to using Excel with Web technologies. You will also learn how tables are exposed through Excel’s object model and manipulated via VBA. . and parameterized). You learn about enhanced XML support in Excel 2013 and many objects and technologies that are used to process XML documents. your Excel data can be easily accessed and shared with others 24/7. static. Excel 2013 is capable of both capturing data from the Web and publishing data to the Web. Programming XML is also thoroughly discussed and practiced. You learn how to retrieve live data into worksheets with Web queries and use Excel VBA to create and publish HTML files. Thanks to the Internet and intranet. Chapter 29: Using XML in Excel 2013—In this chapter you learn how to use Extensible Markup Language with Excel.Chapter 24: Using and Programming Excel Tables —In this chapter you learn how to work with Excel tables. Chapter 25: Programming Special Features —In this chapter you learn about a number of useful objects in the Excel 2013 object library and get a feel for what can be accomplished by calling upon them. and enjoy database-like functionality in the spreadsheet. Chapter 28: Excel and Active Server Pages—In this chapter you learn how to use the Microsoft-developed Active Server Pages technology to send Excel data into the Internet browser and how to get data entered in an HTML form into Excel. properties. While VBA provides a very comprehensive object model that allows you to automate most worksheet tasks.

Let your worksheets perform magical things for you and let the fun begin. WHO THIS BOOK IS FOR This book is designed for Excel users who want to expand their knowledge of Excel and learn what can be accomplished with Excel beyond the provided user interface. THE COMPANION FILES The example files for all the hands-on activities in this book are available on the CD-ROM included with this book. With the basics already mastered. Microsoft Excel 2013 Programming By Example with VBA. Some courses have prerequisites and this is no exception.In Part X of the book you learn how functions found within the Windows API can help you extend your VBA procedures in areas where VBA does not provide a method to code the desired functionality. PART X INCLUDES THE FOLLOWING CHAPTER: Chapter 30: Calling Windows API Functions from VBA—In this chapter you are introduced to the Windows API library. this book will take you to the next learning level where your custom requirements and logic are rendered into the language that Excel can understand. XML. The book assumes that you can easily locate in Excel the options that are required to perform any of the tasks already preprogrammed by the Microsoft team. Consider this book as a sort of private course that you can attend in the comfort of your office or home. . which provides a multitude of functions that will come to your rescue when you need to overcome the limitations of the native VBA library. After learning basic Windows API concepts. you are shown how to declare and utilize API functions from VBA. and ASP does not explain how to select options from the Ribbon or use shortcut keys.

Here you’ll also learn about different VBA components. including Microsoft Excel®. . the use of variables. you will begin writing and executing VBA procedures. Once these topics are covered.Part 1 Introduction to Excel 2013 VBA Programming Chapter 1 Automating Worksheet Tasks with Macros Chapter 2 Exploring the Visual Basic Editor (VBE) Chapter 3 Excel VBA Fundamentals Chapter 4 Using Variables. Data Types. and VBA syntax. you acquire the fundamentals of VBA by recording macros and examining the VBA code behind the macro using the Visual Basic Editor. and Constants Chapter 5 VBA Procedures: Subroutines and Functions Visual Basic for Applications (VBA) is the programming language built-into all Microsoft® Office® applications. In this part of the book.

Creating them requires nothing more than what you already have—a basic knowledge of Microsoft Office Excel 2013 commands and spreadsheet concepts. Getting started with macros is easy. This first chapter walks you through the process of speeding up worksheet tasks with macros. using macros can significantly decrease the time you spend creating. Consider creating a macro when you find yourself performing the . make sure there is not already a built-in feature that you can use to perform that task. You can create macros by using Microsoft Excel’s built-in recording tool (Macro Recorder). timesaving features that allow you to work faster and smarter. and how to write and modify them. formatting. and printing your worksheets. WHAT ARE MACROS? Macros are programs that store a series of commands. or you can write them from scratch using Visual Basic Editor.Chapter 1 Automating Worksheet Tasks With Macros Are you ready to build intelligence into your Microsoft Excel 2013 spreadsheets? By automating routine tasks. Before you decide to automate a worksheet task with a macro. When you create a macro. you can make your spreadsheets run quicker and more efficiently. commonly known as VBA. Ready? Take a seat at your computer and launch Microsoft Office Excel 2013. modifying. COMMON USES FOR MACROS Microsoft Office Excel 2013 comes with dozens of built-in. you simply combine a sequence of keystrokes into a single command that you can later “play back. You learn what macros are. Microsoft Office Excel 2013 macros are created with the powerful programming language Visual Basic for Applications.” Because macros can reduce the number of steps required to complete tasks. how and when to use them.

the 32-bit version is installed.” In VBA 7 you will also need to update the calls to the existing Windows Application Programming Interface (API) functions to work . Slider. By default. TabStrip. and shading. margins.“64-bit Office and Windows API.5. as well as combine different formats. To find out which version of Office 2013 is running on your computer. you must explicitly select the Office 64-bit version installation option. Macros also enable you to check for duplicate entries in a selected area of your worksheet. For example. With a macro. borders. You will find examples of using these conditional compilation constants in Chapter 30. MonthView. and TreeView) and the controls of MSComCt2. ProgressBar. many common ActiveX controls and dynamic link libraries (DLLs) that have been written for 32-bit Office will not work in 64-bit systems. such as fonts. Excel 2010/2013 use VBA7). colors. headers. FlatScrollBar. macros are the way to go if you wish to automate the process of creating and formatting charts.same series of actions over and over again or when Excel does not provide a built-in tool to do the job. choose File | Account | About Excel. StatusBar. Excel’s 64-bit version enables you to work with bigger and more complex workbooks. DateTimePicker. and footers. and UpDown). The 64-bit version of Office enables you to open larger documents and get better application performance by using more physical memory. and selecting special options for printouts. The VBA7 constant will allow you to check whether your VBA code is using VBA7 or the previous version of VBA (Excel 2007 and 2003 use VBA 6. VBA IN 32-BIT AND 64-BIT VERSIONS OF OFFICE 2013 The 2013 Office system supports both 32-bit and 64-bit versions of the Windows operating system. Existing VBA solutions that utilize these controls or libraries need to be revised for the solution to be successfully migrated to 64-bit Office 2013. However. even in the 64-bit system. the Win64 constant can be used to test whether the code is running as 32-bit or 64-bit. you can automate data entry by creating a macro that enters headings in a worksheet or replaces column titles with new labels. ImageComboBox.ocx dynamic library installed in the Windows\System32 folder (ImageList. Macros enable you to automate just about any part of your worksheet. Even though Excel has an excellent chart facility. These include the common controls of the MSComCtl. To install a 64-bit version. Toolbar. you can quickly apply formatting to several worksheets. ListViews. For example. The Visual Basic for Applications provides two conditional compilation constants (VBA7 and Win64) that you can use to ensure the backward compatibility of your code.ocx (Animation. Macros will save you keystrokes when it comes to setting print areas.

1. Excel will warn you with a message as shown in Figure 1. check out my previous programming books available from: Mercury Learning and Information: Microsoft Excel 2010 Programming by Example with VBA. This file format does not allow the storing of VBA macro code or Microsoft Excel 4.0 macro sheets (.xlsb) Excel Macro-Enabled Template (. the workbook should be saved in one of the following macro-enabled file formats: Excel Macro-Enabled Workbook (.in the 64-bit version. If you own or have access to Excel 2010.xltm) If you attempt to save the workbook in a file format that is incompatible with the type of content it includes. and ASP Jones & Bartlett Learning: Excel 2007 VBA Programming with XML and ASP Excel 2003 VBA Programming with XML and ASP Learn Microsoft Excel 2002 VBA Programming with XML and ASP Like Excel 2010/2007. This advanced topic is discussed in Chapter 30. “Calling Windows API Functions from VBA. When your workbook contains programming code. . the default Office Excel 2013 file format (.xlm). 2003.xlsm) Excel Binary Workbook (. and only this version of Excel should be used when working with this book’s Hands-On exercises. EXCEL 2013 FILE FORMATS This book focuses on programming in Excel 2013.” No changes to the existing code are required if the VBA applications are written to run on a 32-bit Microsoft Office system.xlsx) is XMLbased. or 2002 and would like to learn Excel programming. 2007. XML.

It is also critical that you run up-to-date antivirus software on your computer. Antivirus software installed on your computer will scan the workbook file you are attempting to open if the file contains macros. MACRO SECURITY SETTINGS Because macros can contain malicious code designed to put a virus on a user’s computer.FIGURE 1. it is important to understand different security settings that are available in Excel 2013. When a workbook contains programming code. Microsoft Excel displays this message if you attempt to save it in an incompatible file format.1. The default Excel 2013 macro security setting is to disable all macros with notification. as shown in Figure 1. .2.

To open Trust Center’s Macro Settings.FIGURE 1. The Macro Settings options in the Trust Center allow you to control how Excel should deal with macros whenever they are present in an open workbook. you will receive a security warning message just under the Ribbon. choose File | Options | Trust Center | Trust Center Settings and click the Macro Settings link.2. .3. If macros are present in a workbook you are trying to open. as shown in Figure 1.

5. If you need more information before enabling content. The next time you open this workbook you will not be alerted to macros. Excel brings up a security warning message. as shown in Figure 1. . To use the disabled components. you can click the message text displayed in the security message bar to activate the Backstage View where you will find an explanation of the active content that has been disabled. Clicking on the Enable Content button in the Backstage View will reveal two options: Enable All Content This option provides the same functionality as the Enable Content button in the security message bar. Upon opening a workbook with macros. Advanced Options This option brings up the Microsoft Office Security Options dialog shown in Figure 1. This will add the workbook to the Trusted Documents list in your registry.3. This will enable all the content and make it a trusted document. This dialog provides options for enabling content for the current session only.4. you should click the Enable Content button on the message bar.FIGURE 1.

4.FIGURE 1. The Backstage View in Excel 2013. .

Because people do not want to be bothered with security notifications every time they open a file or want to put that file in a trusted folder. you’ll get the warning message again . What Are Trusted Documents? After studying how people work with files that contain macros and other active content. the Trusted Documents feature now records the trust decision on a per file basis. When you click the Enable Content button in the security warning message.FIGURE 1.5. The Microsoft Office Security Options dialog lets you allow active content such as macros for the current session. Microsoft added a Trusted Documents feature that allows you to enable content with one click. Because trust records are saved on a local computer. the trust record that contains the file’s full path and other data about the document is added to the Current User section of the local registry.

6 and click OK. Let’s take a few minutes now to set up your Excel application so you can run macros on your computer without security prompts. For the purpose of this book. Please note files for the “Hands-On” project may be found on the companion CD-ROM.4. 6. In the Main Tabs listing on the right-hand side. The Trusted Locations dialog already shows several predefined trusted locations that were created when you installed Excel 2013. Notice the Trust Center Settings hyperlink in the Backstage View shown in Figure 1. Create a folder on your hard drive named C:\Excel2013_ByExample. as shown in Figure 1. 5. 3. Hands-On 1. launch Excel 2013. The Trust Center dialog opens up. This hyperlink will open the Trust Center dialog where you can set up a trusted folder. In the Code group of the Developer tab on the Ribbon.1. The Developer tab should now be visible in the Ribbon. Choose File | Options. we will add a custom location to this list.7. as depicted earlier in Figure 1. In the Excel Options dialog. In the left pane of the Trust Center dialog.when you open the file from another computer. . To make it easy to work with macro-enabled workbooks while working with this book’s exercises. 2. click the Macro Security button. click Trusted Locations. 4. Setting up Excel 2013 for Macro Development 1.2. you will permanently trust your workbooks containing recorded macros or VBA code by placing them in a folder on your local or network drive that you mark as trusted. If you haven’t yet done so. You can also activate the Trust Center by selecting File | Options. select Developer as illustrated in Figure 1. click Customize Ribbon.

Click the Add new location button. .7.

8. FIGURE 1. To enable the Developer tab on the Ribbon. use the Excel Options (Customize Ribbon) dialog.6. Use the Macro Security button in the Code group on the Developer tab to customize the macro security settings.7. type the name of the folder you created in Step 1 of this Hands-On as shown in Figure 1.FIGURE 1. In the Path text box. 8. .

Your Excel application is now set up for easy macro development as well as opening files containing macros.2 earlier: Disable all macros without notification will cause the workbook to load with all macros and other add-in programs disabled. You will not be notified about the existence of macros in the workbook. You can still view and edit disabled macros. 9. Click OK to close the Microsoft Office Trusted Location dialog.8. . 10. Now let’s get back to the Macro Settings category in the Trust Center as shown in Figure 1.FIGURE 1. Files placed in a trusted location can be opened without being checked by the Trust Center security feature. You should save all the files created in the book’s Hands-On exercises into your trusted C:\Excel2013_ByExample folder. The Trusted Locations list in the Trust Center now includes the C:\Excel2013_ByExample folder as a trusted location. Designating a Trusted Location folder for this book’s programming examples. Click OK to close the Trust Center dialog box. but you cannot run them.

Excel checks whether you have already trusted the signer. You can prevent this message from appearing the next time you open the file by letting Excel know that you trust the document.3. A digital signature on a macro is similar to a handwritten signature on a printed letter. To do this. To digitally sign macros you must install a digital certificate. When you open a workbook containing executable code and that workbook has been digitally signed. you need to click the Enable Content button in the security message bar. This is covered in Chapter 2. Each time you open a workbook that contains macros or other executable code. This signature confirms that the macro has been signed by the creator and the macro code has not been altered since then.” A signed macro provides information about its signer and the status of the signature. Trusted Publishers are developers who have signed their code project with a valid and current digital signature issued by a reputable certification authority. If the signer can be found in the Trusted Publishers list (see Figure 1. . the workbook will be opened with macros enabled. You will add a certificate to this list in Chapter 2. you will be presented with a security dialog box that allows you to either enable or disable macros in the signed workbook.9. this default setting will cause Excel to display a security message bar as you’ve seen i n Figure 1. If the Trusted Publishers list does not have the name of the signer. A macro that is digitally signed is referred to as a signed macro. “Exploring the Visual Basic Editor (VBE).9). FIGURE 1. Disable all macros except digitally signed macros depends on whether a macro is digitally signed.Disable all macros with notification was discussed earlier in this chapter.

Because a macro is a collection of a fairly large number of keystrokes. Although it’s easier to edit a macro than it is to erase unwanted passages from a voice recording. take a few minutes to consider what you want to do. or its signature cannot be validated because it was made after the certificate expired or was revoked. potentially dangerous code can run) enables all macros and other executable code in all workbooks. As you enter the keystrokes. If you do not plan your macro prior to recording. write them down on a piece of paper exactly as they occur. This option is the least secure. an incompatible encryption method. numbers. you may end up with unnecessary actions that will slow it down.3. Trust access to the VBA project object model in the Developer Macro Settings category. you are presented with a security warning message as discussed earlier and shown in Figure 1. The easiest way to plan your macro is to manually perform all the actions that the macro needs to do. . is for developers who need to programmatically access and manipulate the VBA object model and the Visual Basic Editor environment.10 shows a simple worksheet formatted with distinct font colors and styles to help identify the contents of the underlying cells. Suppose you want to see at a glance which areas of a worksheet are text. Don’t leave anything out. An unsigned macro is a macro that does not bear a digital signature. Right now this check box should be left unchecked to prevent unauthorized programs from accessing the VBA project of any workbook or add-in. “Programming the Visual Basic Editor (VBE). Like a voice recorder. or a missing key. Excel’s macro recorder records every action you perform. Signed macros with invalid signatures are automatically disabled. and users attempting to open workbooks containing these macros are warned that the signature validation was not possible. it is important to plan your actions in advance. it does not display any notifications. Figure 1. performing only the actions you want recorded will save you editing time and trouble later. We will come back to this setting in Chapter 26. and formulas. Such macros could potentially contain malicious code.” More about Signed/Unsigned Macros Sometimes a signed macro may have an invalid signature because of a virus.Enable all macros (not recommended. Upon opening a workbook containing unsigned macros. PLANNING A MACRO Before you create a macro.

FIGURE 1. and formulas shown in Figure 1. Finding out “what’s what” in a worksheet is easy with formatting applied by an Excel macro.xlsm. enter the text. 2. Recall that workbooks saved in this format use the . Open a new workbook and save it in your trusted Excel2013_ByExample folder as Practice_Excel01. Be sure you save the file as Excel Macro-Enabled Workbook by selecting this file type from the Save as type drop-down list in the Save As dialog box. Starting in cell A1. Hands-On 1.2. Creating a Worksheet for Data Entry 1.xlsm file extension instead of the default . . numbers.11.xlsx.10.

This sample worksheet will be automatically formatted with a macro. Only the Text check box should be checked. 2.xlsm file. and Errors. In the Go To Special dialog box. To produce the formatting results shown in Figure 1. let’s perform Hands-On 1. Notice that the cells containing text are now selected. Hands-On 1. Select any cell in the Practice_Excel01. 3. Make sure that only one cell is selected.10. Logicals. click the Constants option button and then remove the check marks next to Numbers. Applying Custom Formatting to the Worksheet This Hands-On relies on the worksheet that was prepared in Hands-On 1.2.3. Select Home | Editing | Find & Select | Go To Special. Save the changes in the Practice_Excel01. Be careful not to change your selection until you apply the necessary formatting in the next step. . 1. Click OK to return to the worksheet.11. 4.xlsm workbook file.3.FIGURE 1. 3.

Be careful not to change your selection until you apply the necessary formatting in the following step. Only the Numbers check box should be checked. perform the following actions: 11. Click OK to return to the worksheet. Notice that the cells containing numbers are now selected. In Steps 11 to 15. In the Go To Special dialog box. Select cells A1:A4. perform the following actions: 6. With the formula cells still selected. 7. 9. click the Formulas option button. click the Constants option button and remove the check marks next to Text. To select and format cells containing formulas. Select a single cell. you located and formatted cells containing formulas. 10. Notice that the cells containing numbers that are the results of formulas are now selected. you will now add the color legend. To select and format cells containing numbers. Steps 1 to 5 allowed you to locate all the cells that contain text. . Be careful not to change your selection until you apply the necessary formatting in the next step. 8. and Errors. 16. Select a single cell in the worksheet. choose Home | Styles | Cell Styles and click on the Neutral style. To make it easy to understand all the formatting applied to the worksheet’s cells.5. Logicals. you located and formatted cells with numbers. Click OK to return to the worksheet. 15. 12. Notice that the cells containing text now appear in a different color. In the Go To Special dialog box. 13. Select Home | Editing | Find & Select | Go To Special. choose Home | Styles | Cell Styles and click on the Accent4 style under Heading 4. Select Home | Editing | Find & Select | Go To Special. choose Home | Styles | Cell Styles and click on the Calculation style in the Data and Model section. 14. Notice that the cells containing numbers now appear shaded. In Steps 6 to 10. With the number cells still selected. With the text cells still selected.

Select cell A2. 24. After completing Steps 16 to 28. Bold Italic font style. Creating a macro that is capable of playing back your keystrokes can be a real time-saver. and click on the Accent4 style under Heading 4. let’s remove the formatting from the example worksheet. 23. and 10 font size. Choose Home | Styles | Cell Styles. As you can see. as was shown in Figure 1.17. Select cell B3 and type Formulas. Choose Home | Styles | Cell Styles. Before you go on to the next section.4. cells A1:B3 will display a simple color legend. Select cell A1. click the Font tab. Hands-On 1. no matter how simple your worksheet task appears at first.10 earlier. Select cells B1:B3 and right-click within the selection. especially when you have to repeat the same process for a number of worksheets. 28. Choose Home | Styles | Cell Styles. 21. Select cell B1 and type Text. 27. Select cell A3. 20. many steps may be required to get exactly what you want. 18. Choose Format Cells from the shortcut menu. and click on the Neutral style. Select cell B2 and type Numbers. where you will record your first macro. 19. Removing All Formatting from the Worksheet . Choose Home | Cells | Insert | Insert Sheet Rows. 22. In the Format Cells dialog box. Select Arial Narrow font. and click on the Calculation style in the Data and Model section. 26. 25. and click OK to close the dialog box.

RECORDING A MACRO Now that you know what actions you need to perform. Select cells A1:A4 and in the Home tab’s Cells group. If the location of the active cell does not matter. Recording a Macro that Applies Formatting to a Worksheet Before you record a macro. 1. as shown in Figure 1. Choose View | Macros | Record Macro. click the Delete button’s drop-down arrow. 3. enter the name WhatsInACell for the sample macro.5. Select any single cell in your Practice_Excel01. 4. 3. Hands-On 1. 2. 2. If you want the macro to always start in a specific location on the worksheet. Do not dismiss this dialog box until you are instructed to do so.1. and then select Delete Sheet Rows. In the Record Macro dialog box. click the Clear button’s drop-down arrow. Click anywhere in the worksheet and press Ctrl-A to select the entire worksheet.12. and then select Clear Formats. Select cell A1. turn on the macro recorder first and then select the cell you want to start in. you should decide whether or not you want to record the positioning of the active cell. . select a single cell first and then turn on the macro recorder. In the Home tab’s Editing group.xlsm workbook. it’s time to turn on the macro recorder and create your first macro.

numbers. you must name it. Report1 is a correct macro name. When you record a new macro. Spaces are not allowed. Macro names can contain letters. enter Whats_In_A_Cell. For example. Excel assigns a default name such as Macro1. the storage location. If you want a space between the words.FIGURE 1. and the underscore character. Macro2. and a description for your macro. instead of WhatsInACell. Select This Workbook in the Store macro in list box.12. Macro Names If you forget to enter a name for the macro. 4. use the underscore. In the Record Macro dialog box. and so on. while 1Report is not. For example. but the first character must be a letter. you can also supply a shortcut key. Storing Macros .

click the Stop Recording button in the status bar as shown in Figure 1. Choose OK to close the Record Macro dialog box and begin recording. New Workbook—Excel will place the macro in a new workbook.13 or choose View | Macros | Stop Recording. enter the following text: Indicates the contents of the underlying cells: text. When this button appears in the status bar. Excel creates it the first time you select this option. Only the actions finalized by pressing Enter or clicking OK are recorded.13 appears in the status bar. When you have performed all the actions.14 below). Do not click on this button until you are instructed to do so. 7. the status bar displays a button that allows you to record another macro (see Figure 1.3. In the Description box. 5. This Workbook—The macro will be stored in the workbook you are currently using. FIGURE 1. Steps 1–28. . the workbook is in the recording mode. When you stop the macro recorder. If this workbook doesn’t already exist. and formulas. numbers. Personal Macro Workbook is located in the XLStart folder.13.Excel allows you to store macros in three locations: Personal Macro Workbook—Macros stored in this location will be available each time you work with Excel. If you press the Esc key or click Cancel before completing the entry. The Stop Recording button shown in Figure 1. The Stop Recording button in the status bar indicates that the macro recording mode is active. the macro recorder does not record that action. 6. Perform the actions you performed manually in Hands-On 1. The Stop Recording button remains in the status bar while you record your macro. 8.

etc. Excel status bar with the macro recording button turned off. By default. For example. C9. Bear in mind. etc. you may use both methods of cell addressing. the Excel macro recorder uses absolute references. perform an action. however. be sure to select the Use Relative References option before you choose the Record Macro option. Relative references automatically adjust when you copy them. $A$4). C5.g. use absolute cell addressing. Before you begin to record a new macro. that Excel will continue recording using relative cell references until you exit Microsoft Excel or click the Use Relative References option again. If you want your macro to perform the action in any cell. USING RELATIVE OR ABSOLUTE REFERENCES IN MACROS If you want your macro to execute the recorded action in a specific cell.14.g.15. you may select a specific cell (e.. During the process of recording your macro. which is located five rows down and two columns to the right of the currently active cell $A$4).. .FIGURE 1. Relative cell references have the following form: A1. make sure the Use Relative References option is not selected when you click the Macros button as shown in Figure 1. and absolute references don’t. $C$5. Absolute cell references have the following form: $A$1. then choose another cell relative to the selected cell (e. no matter what cell is selected during the execution of the macro.

let’s record another macro that will remove the formatting that you’ve applied to the worksheet.10. .6. Choose View | Macros | Record Macro (or you may click the Begin recording button located in the status bar). Hands-On 1. 2. Recording a Macro that Removes Formatting from a Worksheet To remove the formatting from the worksheet shown in Figure 1. Enter RemoveFormats as the name for your macro.FIGURE 1. Excel macro recorder can record your actions using absolute or relative cell references. perform the following steps: 1.15. Before we look at and try out the newly recorded macro.

xlsm workbook is open. Select cell A1. 7. In the Macro dialog box. . 2. Click OK. Running a Macro 1. 9. 5. click the Clear button’s drop-down arrow. and Sheet1 with the example worksheet is active. Choose View | Macros | View Macros. 4. Ensure that This Workbook is selected in the Store macro in list box. click the Delete button’s drop-down arrow and then select Delete Sheet Rows. and then press Ctrl-A to select the entire worksheet.3. but for now. 8.16. you should use the Macro dialog box. 6. Hands-On 1. Select cells A1:A4 and in the Home tab’s Cells group. Click the Stop Recording button in the status bar. or choose View | Macros | Stop Recording. Select any single cell. You will run this macro the next time you need to clear the worksheet. you should run it at least once to make sure it works correctly. and then select Clear Formats. In the Home tab’s Editing group. Make sure that the Practice_Excel01. Later in this chapter you will learn other ways to run macros. 3. EXECUTING MACROS After you create a macro. click the WhatsInACell macro name as shown in Figure 1.7.

debug (Step Into). .16. Click Run to execute the macro. Now. 6. In the Macro dialog box. 7. The WhatsInACell macro applies the formatting you have previously recorded. or delete. In the Macro dialog box. click the RemoveFormats macro name. you can select a macro to run. let’s proceed to remove the formatting with the RemoveFormats macro: 5. edit. 4. You can also set macro options. Click Run to execute the macro. Choose View | Macros | View Macros.FIGURE 1.

when you turned on the macro recorder.16. 2. you selected This Workbook for the location. Choose View | Macros | View Macros. Excel makes it possible to modify the macro without forcing you to go through the tedious process of recording your keystrokes again. Don’t panic. When you are done. Select the WhatsInACell macro name and click the Edit button. Now take a moment and try switching between both windows. Microsoft Excel opens a special window called Visual Basic Editor (also known as VBE).17. . EDITING MACROS Before you can modify your macro. you must find the location where the macro recorder placed its code. and clicking the Edit button. Quite often. This window is your VBA programming environment. As you recall. Perhaps during the macro recording you selected the wrong font or forgot to change the cell color or maybe you just realized it would be better to include an additional step. Examining the Macro Code 1. ensure that you are back in the VBE window.The RemoveFormats macro quickly removes the formats applied by the WhatsInACell macro. you can quickly switch between the Microsoft Excel application window and the Visual Basic Editor window. Hands-On 1. The easiest way to find your macro is by opening the Macro dialog box shown earlier in Figure 1.8. you will notice that your macro does not perform as expected the first time you run it. Let’s look for the WhatsInACell macro. selecting the macro. as shown in Figure 1. Using the keyboard shortcut Alt+F11.

choose Developer | Visual Basic to switch again to the programming environment. The main part of the Visual Basic Editor window is a docking surface for various windows that you will find extremely useful during the course of creating and testing your VBA procedures. As you can see. Take a look at the menu bar and toolbar in the Visual Basic Editor window. you will become an expert in using these tools. 3. Both of these tools differ from the ones in the Microsoft Excel window. Close the Visual Basic Editor window by using the key combination Alt+Q or choosing File | Close and Return to Microsoft Excel.FIGURE 1. The Visual Basic Editor uses the old Excel style menu bar and toolbar with tools required for programming and testing your recorded macros and VBA procedures.17. Don’t worry if the Visual Basic Editor window seems a bit confusing at the moment. . The Visual Basic Editor window is used for editing macros as well as writing new procedures in Visual Basic for Applications. there is no Ribbon interface. you will become familiar with all the elements of this screen. As you work through the individual chapters of this book. 4. As you work with the recorded macros and start writing your own VBA procedures from scratch. In the Microsoft Excel application window.

In Figure 1. keyboard. Module2.17.VBAProject window. In the following chapters of this book. and so on.” While macros allow you to mimic keyboard actions. and the Code window. you will also use modules to write the code of your own procedures from scratch. the Properties window. Sub WhatsInACell() ' WhatsInACell Macro ' Indicates the contents of the underlying cells: text.17 displays three windows that are docked in the Visual Basic Editor window: the Project Explorer window.” Although the words can be used interchangeably. Notice that the only available property for the module is the Name property. the Module1 object is selected in the Project . In other words. The Project Explorer window shows an open Modules folder. or menu options. Individual modules are stored in a folder called Modules. and therefore the Properties . Excel records your macro actions in special worksheets called Module1. Macro or Procedure? A macro is a series of commands or functions recorded with the help of a built-in macro recorder or entered manually in a Visual Basic module. true procedures can also execute actions that cannot be performed using the mouse. A module resembles a blank document in Microsoft Word. The Module1 (Code) window displays the code of the two procedures that you recorded earlier.Module1 window displays the properties of Module1. The Properties window displays the properties of the object that is currently selected in the Project Explorer window. and formulas. . numbers.Figure 1. many programmers prefer “procedure. You can use this property to change the name of Module1 to a more meaningful name. procedures are more complex macros that incorporate language structures found in the traditional programming languages. The term “macro” is often replaced with the broader term “procedure.

Select Selection.Select Selection.SpecialCells(xlCellTypeConstants. 1).Select Selection.FormulaR1C1 = "Text" Range("A2").' Range("A1").Select ActiveCell.SpecialCells(xlCellTypeFormulas.Style = "20% .SpecialCells(xlCellTypeConstants.Insert Range("A1").Accent4" Range("B1").Select Selection.Select Selection.Style = "Neutral" Range("E2").EntireRow.Style = "Calculation" Range("A1:A4").FormulaR1C1 = "Formulas" Range("B1:B3").Select Selection.Select ActiveCell. 2). 23).Style = "Neutral" Range("B2").Accent4" Range("B2").Select Selection.FormulaR1C1 = "Numbers" Range("A3").Select Selection.Select Selection.Select .Select ActiveCell.Style = "20% .Style = "Calculation" Range("B3").Select Selection.

ThemeFont = xlThemeFontNone End With End Sub Sub RemoveFormats() ' ' RemoveFormats Macro ' Cells.Font .OutlineFont = False .Size = 10 .Strikethrough = False .Subscript = False .TintAndShade = 0 .Delete Range("A1").ClearFormats Range("A1:A4").ThemeColor = xlThemeColorLight1 .Select End Sub .FontStyle = "Bold Italic" .Shadow = False .Name = "Arial Narrow" .Activate Selection.Select Selection.Underline = xlUnderlineStyleNone .Select Range("C2").With Selection.EntireRow.Superscript = False .

Hands-On 1. comments appear in green. let’s focus on finding answers to two questions: How do you read the macro code? How can you edit macros? Notice that the macro code you recorded is located between the Sub and End Sub keywords. MACRO COMMENTS Take a look at the recorded macro code.9. Be sure to start with a single quote. The lines that begin with a single quote denote comments. ' Find and format cells containing text . Visual Basic ignores the comment lines. Make sure that the Visual Basic Editor screen shows the Code window with the WhatsInACell macro. Editing macros boils down to deleting or modifying existing code.SpecialCells(xlCellTypeConstants. Let’s add some comments to the WhatsInACell macro to make the code easier to understand. 2). This is often done while testing and troubleshooting your macros. Adding Comments to the Macro Code 1. 2. Click in front of Selection. By default. You read the code line by line from top to bottom. Select and press Enter.For now. Comments are often placed within the macro code to document the meaning of certain lines that aren’t obvious. Comments can also be used to temporarily disable certain blocks of code that you don’t want to execute. 3. or typing new instructions in the Code window. Move the pointer to the empty line you just created and type the following comment. When the macro code is executed.

About Comments In the VBE Code window. Comments will make your life easier if you need to return to the macro procedure several months later.SpecialCells(xlCellTypeFormulas. You can change the color of comments in the Options dialog box (Tools | Options | Editor Format tab). Click in front of Selection.xlsm.Style = "Calculation" and press Enter. You can also add a comment at the end of the line of code. ANALYZING THE MACRO CODE All macro procedures begin with the keyword Sub and end with the keywords End Sub. or choose File | Save Practice_Excel01. Press Ctrl+S to save the changes in Practice_Excel01.SpecialCells(xlCellTypeConstants. don’t forget to include comments. Select and press Enter. 9.4. The default comment color is green. They will also allow others to understand various parts of your procedure. and then type the text of your comment. to add a comment following the line . Move the pointer to the empty line and type the following comment: ' Find and format cells containing numbers 6. The comment lines don’t do anything except provide information to the user about the purpose of a macro or macro action. The Sub keyword is followed by the macro name and a set of parentheses.xlsm. When you write your own VBA procedures. Select and press Enter. 5. click at the end of this line.Size = 10. 23). 1). On the empty line type the following comment: ' Create a legend 10. Click in front of Selection. press Tab. Move the pointer to the empty line and add the following comment: ' Find and format cells containing formulas 8. Between the keywords Sub and End Sub are statements that Visual . Click after Selection. 7. For example. every line that begins with a single quote is a comment. type a single quote.

The periods appear in almost every line of code and are used to join various elements of the Visual Basic for Applications language. For example. How do you read the instructions written in this language? They are read from the right side of the last period to the left.Basic executes each time you run your macro. you may notice that Excel recorded a lot of information that you didn’t intend to include. Here are a few statements from the WhatsInACell procedure and a description of what they mean: CLEANING UP THE MACRO CODE As you review and analyze your macro code line by line. Visual Basic reads the lines from top to bottom. Notice that the recorded macro contains many periods. . ignoring the statements preceded with a single quote (see the previous section on comments) and stops when it reaches the keywords End Sub.

after selecting cells containing text. in addition to setting the font style to bold italic and the size to 10.Font .Superscript = False . Excel also recorded the current state of other options on the Font tab—strikethrough. and theme font.OutlineFont = False . Cleaning up the Macro Code 1.Subscript = False . outline font. shadow.Shadow = False . Take a look at the following code fragment: With Selection.Underline = xlUnderlineStyleNone . locate the following block of code and delete the lines that are crossed out: .Strikethrough = False . Excel always records all the settings. Hands-On 1. These additional instructions make your macro code longer and more difficult to understand. Let’s do some code cleanup in the WhatsInACell macro. underline. when you finish recording your macro. it is a good idea to go over the recorded statements and delete the unnecessary lines.ThemeFont = xlThemeFontNone End With When you use dialog boxes.Size = 10 . superscript.ThemeColor = xlThemeColorLight1 . theme color. Therefore.TintAndShade = 0 .FontStyle = "Bold Italic" . tint and shade.10.Name = "Arial Narrow" . In the Code window with the WhatInACell macro. subscript.

These statements are the settings that you actually changed in the Format Cells dialog box when you recorded this macro: With Selection.With Selection.Insert .Strikethrough = False .ThemeFont = xlThemeFontNone End With After the cleanup.Select Selection.Subscript = False . Locate the following two lines of code: Range("A1:A4").Insert 3.Size = 10 End With 2.Superscript = False .ThemeColor = xlThemeColorLight1 .Name = "Arial Narrow" .Size = 10 .Shadow = False .OutlineFont = False .Font .Font .Name = "Arial Narrow" .Underline = xlUnderlineStyleNone .EntireRow.FontStyle = "Bold Italic" .FontStyle = "Bold Italic" .EntireRow. only three statements should be left between the keywords With and End With.TintAndShade = 0 . Replace those two lines of code with the following line: Range("A1:A4").

To see the result of your macro. Hands-On 1. For example. If the selected worksheet contains only cells with text and you try to run the WhatsInACell macro. If you didn’t introduce any problems during the modification of your macro. If the Visual Basic Editor encounters an error during the execution of your macro. Visual Basic will enter into break mode and will use the yellow highlighter to indicate the line that it had trouble executing.11. you must switch to the Microsoft Excel window. 2. For example. you may delete an important line of code. TESTING THE MODIFIED MACRO When you modify a recorded macro. In the Visual Basic Editor Code window. Visual Basic will encounter a problem when attempting to select cells with numbers. Before you run macros. Click the End button. the macro will run smoothly and no errors will be reported. At this time. if you try to run the WhatsInACell macro when a blank sheet is selected. Visual Basic may announce “ This action will reset your . and choose Run | Run Sub/UserForm. and make sure that you select the correct worksheet before you try to run the macro again. To make sure that your macro continues to work correctly after your modifications. Save your changes by clicking the Save icon on the Standard toolbar. The same “…No cells were found” message will be displayed. you will get the “Run time error ‘1004’ — No Cells were found” error message. Visual Basic will generate the “ Run time error ‘424’ — Object required ” message when running this line of code. or you may inadvertently remove or omit a necessary period. press Alt+F11.font. you need to run it again. To do this. Click the Debug button in the message box. If you omit the period in With Selection. Testing the Modified Macro Code 1. place the pointer in any line of the WhatsInACell macro code. you will see a dialog box displaying the type of error found. As soon as you correct your error. it is quite possible that you will introduce some errors. and you will be placed in the Code window. you must make sure that your macro can run in the worksheet that is currently selected.4.

however. and paste them into the correct location in your original macro. as there may be more errors to be fixed before the macro can run smoothly. Switch back to the Visual Basic Editor screen by pressing Alt+F11. After correcting the error. Click OK to this message. some edits prevent continuing execution. one thing is for sure—the macro recorder does not make mistakes. Let’s see how this can be achieved with the macro recorder. you must record a new macro. Visual Basic executes the macro behind the scenes. To watch Visual Basic at work. If you want to add additional instructions to your macro using the macro recorder. Suppose you would like to include a thick border around cells A1:B3 when you format your worksheet with the WhatsInACell macro. Recording Additional Features for the Existing Macro in a New Macro . You may argue that Excel records more instructions than are necessary. you must run your macro from the Macro dialog box as demonstrated earlier. Adding new instructions to the macro code is not very difficult if you are already familiar with the Visual Basic language. In most situations. you may realize that you’d like the macro to perform additional tasks.12. or arrange your screen in such a way that the Microsoft Excel and Visual Basic windows can be viewed at the same time. TWO LEVELS OF MACRO EXECUTION You can run your macros from either the Microsoft Excel window or the Visual Basic Editor window. Although you can edit code in break mode.project. You can’t see when Visual Basic selected and applied formatting to the text cells or when it inserted four empty rows for the color legend. you can do this more efficiently when you delegate the extra tasks to the macro recorder. run the macro again. proceed anyway?”. Two monitors attached to your computer will help you greatly in the development work when you need to observe actions performed by your code. However. When you execute the WhatsInACell macro from the VBE screen. IMPROVING YOUR MACRO After you record your macro. copy the sections you want. Hands-On 1. 3.

7. or choose View | Macros | Stop Recording. Choose View | Macros | Record Macro. 5. 2. Select cells A1:B3. 3. The recorded macro is shown in Figure 1. . Click cell A1. Activate the Microsoft Excel window with the sample worksheet you created in this chapter. In the Record Macro dialog box. To view the recorded macro code. 9. Click the drop-down arrow on the Border tool in the Font group of the Home tab. and select Thick Box Border. click OK to accept the default macro name. Remove the thick border from your worksheet by clicking the Undo button in the Office Quick Access toolbar. 8. 6. 4. Click the Stop Recording button in the status bar.18. Notice the thick border around cells A1:B3. press Alt+F11 to switch to the Visual Basic Editor window and locate the new macro in the Code window.1.

If you follow this path. When you create macros with the macro recorder. Do you think you can get rid of some instructions? Before you start deleting unnecessary lines of code. Then you can look up the . you can quickly learn the VBA equivalents for the Excel commands and dialog box settings.FIGURE 1.18. you can safely delete the commented lines. You can comment out the unwanted lines and run the macro with the commented code. And if the macro does not perform correctly. If the Visual Basic Editor does not generate errors. you will never find yourself recording the same keystrokes more than once. think of how you can use the comment feature that you’ve recently learned. you can remove the comments from the lines that may be needed after all. Let’s analyze this code. Microsoft Excel placed the recorded macro in a new Module sheet.

BorderAround Weight:=xlThick The above instruction uses the BorderAround method of the Range object. 3. you will find that Visual Basic has a BorderAround method that allows you to add a border to a range of cells and set the Color. to make your macro code easier to understand. 2. run the RemoveFormats macro to . It appears that the macro recorder handled each border line separately. select Module1 in the Modules folder to activate the Code window with the WhatsInACell macro.VBAProject window. the quickest way to create the thick border around a selection of cells is with the following statement: Range("A1:B3"). It seems hard to believe that Visual Basic does not have a simple one-line command that places all four borders around a selected range of cells. However. properties.13. let’s add it to the WhatsInACell macro. “Excel VBA Fundamentals. Using Visual Basic for Applications. the slower your macro will execute. Add a new line after ActiveCell. If you look long enough.FormulaR1C1 = "Formulas". For example. you may want to put on your detective hat and search for a better way to perform a specific task. It’s quite obvious that the more instructions Visual Basic needs to read. Adding Additional Code to the Existing Macro 1. Learning the right word or expression in any language takes time.”) Now that you know what instruction is needed to produce a thick border around selected cells. LineStyle. and Weight for the new border. take a look at the code the macro recorder generated for placing a border around selected cells. In the blank line. In the Project . Hands-On 1. (You’ll learn about Visual Basic objects.BorderAround Weight:=xlThick 4.meaning and the usage of these Visual Basic commands in the online help. If your worksheet currently contains formatting. and methods in Chapter 3. Eliminating extraneous commands will speed up your macro. enter the following instruction: Range("A1:B3"). It uses the thick line to create a border around cells A1:B3.

as Excel does not have a corresponding Ribbon command or shortcut menu option. In the Code window containing the code of the WhatsInACell macro. or from the Excel worksheet by pressing Alt+F8. add empty lines in the required places of the macro code by pressing Enter. you can add new instructions to your macro by hand. You can delete the code by selecting it and pressing the Delete key. using the Visual Basic for Applications language. Hands-On 1. 8. If the additional instructions are keyboard actions or menu commands. Including Additional Instructions To include additional instructions in the existing macro. 2.clear the formats. Want to add more improvements to your macro? How about a message box to notify you when Visual Basic has finished executing the last macro line? This sort of action cannot be recorded. Place your cursor on the empty line and type the following statement: . You can run this macro from the Visual Basic Editor screen by placing the pointer anywhere in the macro code and pressing F5. Press Alt+F11 to switch to the Microsoft Excel window to see the formatting changes applied by the macro to the worksheet.12. you may use the macro recorder to generate the necessary code and then copy and paste these code lines into the original macro. In the Visual Basic Editor screen. Now run the modified WhatsInACell macro. 7. click in front of the End Sub keywords and press Enter. Let’s see how this is done. However.14. Adding Visual Basic Statements to the Recorded Macro Code 1. and type in the necessary Visual Basic statements. 6. locate and delete the Macro3 code that you recorded in Hands-On 1. 5.

You already know how to run a macro by choosing View | Macros | View Macros or pressing Alt+F8. In the Code window. simply delete the old macro name and enter the new name following the Sub keyword. Let’s get started. or worksheet button. You also tried to run the macro in the VBE Code window using the keyboard shortcut F5 or by choosing Run | Run Sub/UserForm.” 3. you have learned a couple of methods of running macros. these methods of running a macro are not convenient if you need to run your macro often." MsgBox is one of the most frequently used VBA functions. You now know for sure that the macro has finished running. 4. 5. OTHER METHODS OF RUNNING MACROS So far. The name of the macro should communicate its function as clearly as possible. toolbar button. To change the macro name. “VBA Procedures: Subroutines and Functions. you will learn three cool methods of macro execution that will allow you to run your macros using a keyboard shortcut. RENAMING THE MACRO When you add additional actions to your macro. Click OK when Visual Basic completes the last recorded instruction and displays the message. You will learn more about its usage in Chapter 5.19 or by choosing Tools | Macros. Return to the Excel application window and run the RemoveFormats macro.MsgBox "All actions have been performed. In addition. Now run the WhatsInACell macro. you don’t need to press a specific key. Unfortunately. . you can run a macro from the Visual Basic Editor window by clicking a button on the Standard toolbar as shown in Figure 1. In this section. you may want to change the macro name to better indicate its purpose.

the cursor is located in the Shortcut key text box. click the WhatsInACell macro. Excel records the keyboard combination as Ctrl+Shift-I. Hands-On 1. Assigning a Macro to a Keyboard Shortcut 1. 2.20. In the list of macros. Hold down the Shift key and press the letter I on the keyboard.15.FIGURE 1.19. 3. Running the Macro Using a Keyboard Shortcut A popular method to run a macro is by using an assigned keyboard shortcut. you must assign it to your macro. 4. The result is shown in Figure 1. In the Excel application window. press Alt+F8 to open the Macro dialog box. . When the Macro Options dialog box appears. It is much faster to press Ctrl+Shift+I than it is to activate the macro from the Macro dialog box. Before you can use the keyboard shortcut. The Visual Basic code can be run from the toolbar button. and then choose the Options button. Let’s learn how this is done.

assign the Ctrl+Shift+L keyboard shortcut to the RemoveFormats macro.20. Avoid Shortcut Conflicts . you can assign a keyboard shortcut for running a macro. 8. Your macros go to work and your spreadsheet is now formatted.FIGURE 1. On your own. 5. Press Ctrl+Shift+L to run the RemoveFormats macro again. make sure the Microsoft Excel window is active and press Ctrl+-Shift+L to remove the formats and then press Ctrl+Shift+I to run the second macro to format the worksheet. Click OK to close the Macro Options dialog box. Using the Macro Options dialog box. 9. 7. 6. To run your macros using the newly assigned keyboard shortcuts. Click Cancel to close the Macro dialog box and return to the worksheet.

click the Customize Quick Access Toolbar button (the downward-pointing arrow in the title bar) and choose More Commands as shown in Figure 1. Running a Macro from the Quick Access Toolbar 1.21. Excel will run your macro if the workbook containing the macro code is currently open.If you assign to your macro a keyboard shortcut that conflicts with a Microsoft Excel built-in shortcut. Let’s see how it is done from Excel. In the Microsoft Excel window. Running the Macro from the Quick Access Toolbar You can add your own buttons to the built-in Quick Access toolbar. .16. Hands-On 1.

FIGURE 1. In the Customize Quick Access Toolbar drop-down list box.21. Adding a new button to the Quick Access toolbar (Step 1). The current selections are shown in Figure 1. 2. select For Practice_Excel01. The Excel Options dialog box appears with the page titled Customize the Quick Access Toolbar.xlsm. 3. 4. Select WhatsInACell in the list box on the left-hand side.22. select Macros. In the Choose commands from drop-down list box. .

FIGURE 1. Select the blue square button (the rightmost button in the fifth row) in the button gallery as illustrated in Figure 1. 6. . 7.23. click the Modify button. Click the Add button to move the WhatsInACell macro to the list box on the righthand side. Adding a new button to the Quick Access toolbar (Step 2). 5.22. To change the button image for your macro. and click OK.

17. Make sure the Sheet1 worksheet with the sample data is now active. make sure that the image to the left of the macro name has changed. This button will be available whenever the Practice_Excel01. Click OK to close the Excel Options dialog. Select the RemoveFormats macro and click the Run button (or just press Ctrl+Shift+L). Press Alt+F8 to open the Macro dialog box. 8. Again. You should now see a new button on the Quick Access toolbar as shown in Figure 1. 10. Let’s go over the steps that will attach the WhatsInACell macro to a worksheet button. After closing the gallery window. 9. Hands-On 1. Running the Macro from a Worksheet Button Sometimes it makes most sense to place a macro button right on the worksheet where it cannot be missed.24.FIGURE 1.24. and click the blue square button you’ve just added to run the macro assigned to it. Let’s remove the formatting you just applied by running the RemoveFormats macro that you recorded earlier in this chapter.23. A custom button placed on the Quick Access toolbar will run the specified macro. Running a Macro from a Button Placed on a Worksheet .xlsm workbook is active. It will disappear when you activate another workbook. FIGURE 1. Adding a new button to the Quick Access toolbar (Step 3). your macro goes to work and your spreadsheet is now formatted.

right-click Button 1 on the worksheet and choose Edit Text on the shortcut menu. click the first image. If the selection handles are not displayed. 3. When the Assign Macro dialog box appears.26. . 5. When the button is selected. 4.25. do not worry. highlight the default text on the button. 2. Select the default text and enter the new label. choose the WhatsInACell macro and click OK. it looks like the one shown in Figure 1. as shown in Figure 1.25. Activate Sheet1. FIGURE 1. Adding a button to a worksheet. If the text does not fit. To change the button’s label. which represents a button.1. the example worksheet you prepared in this chapter. The Forms toolbar appears. and type Format Cells. In the Form Controls area. Click anywhere in the empty area of the worksheet. Choose Developer | Insert. you will resize the button in Step 7.

Again. 7. 6. click outside the button to exit the selection mode. Because the text you entered is longer than the default button text. Press Alt+F8 to open the Macro dialog box. Let’s remove the formatting you just applied by running the RemoveFormats macro. To run your macro. When you’re done resizing the button. On your own. point to one of the tiny circles that appear in the button’s right edge. Right-click the button you’ve just renamed. let’s resize the button so that the entire text is visible. create another button on this worksheet that will be used for .FIGURE 1. click the button you just created. Select the RemoveFormats macro and click the Run button. A button with an attached macro. 10. and drag right to expand the button until you see the complete entry. 9. click outside the button to exit the edit mode. Format Cells. 8.26. your macro goes to work and your worksheet is now formatted. 11. When you’re done renaming the button.

you assign a macro to it that is stored in a module of This Workbook. 2. or events.running the RemoveFormats macro.25. and choose Assign Macro. While the Form controls can only respond to the Click event. Saving Macros and Running Macros from Another Workbook 1. the ActiveX controls have many different actions. This gives you access to two types of controls: Form controls and ActiveX controls as was shown in Figure 1. The ActiveX controls can be placed on worksheets or custom forms that you create in the Visual Basic Editor window. Save your practice workbook and then close it. you write macro code that is stored with the control itself. When you use a Form control. “Context Menu Programming and Ribbon Customizations. When you use an ActiveX control. You can also run macros from a hyperlink or a button placed in the Ribbon.18. right-click it. or Personal Macro Workbook. Open a brand new workbook. old XLM macro sheets. The Form controls are compatible with earlier versions of Excel and can be used on chart sheets. and worksheets when all you want to do is run a macro by clicking a control.” Adding Controls to a Worksheet You can add controls to a worksheet by choosing the Insert button on the Developer tab. The macros are saved when you save the open workbook. Hands-On 1. Excel 2013 has a large selection of ready-made shapes under the Shapes button on the Insert tab and all you need to do is place the desired shape on the worksheet. New Workbook. that can occur when you use the control. . These techniques will be introduced in Chapter 21. you can assign a macro to any drawing object on a worksheet. In addition to assigning macros to a button in the Form controls or a command button in the ActiveX controls. SAVING MACROS The WhatsInACell and RemoveFormats macros that you created in this chapter are located in a Microsoft Excel workbook.

Save the file as an Excel Workbook named Practice_Excel01Calc. Do not close the Practice_Excel01. there is no trace of your macros in the Macro dialog box. you need to open the file that stores these macros. Select the Practice_Excel01. you can print your macros. so saving it in Excel’s default file format will work just fine. 8. 9. 6. Open the C:\Excel2013_ByExample\Practice_Excel01.xlsm workbook.xlsx in your trusted C:\Excel2013_ByExample folder. Press Alt+F8 to activate the Macro dialog box. 3. We will need it in the next section. Notice that Excel displays macros in all open workbooks. You can print the entire module sheet where your macro is stored or indicate a selection of lines to print. 5.Notice that your custom macro button no longer appears on the Quick Access toolbar. 4. activate Sheet1 and enter the text Addition in cell A1.xlsx workbook file. 7. You should see your new worksheet formatted in the same way the formatting was applied in the Practice_Excel01. let’s enter some data into the worksheet.xlsm workbook file.xlsm workbook. Let’s print the entire module sheet that contains your WhatsInACell macro. . and =Sum(A2:A3) in cell A4. Also. Do not save the changes. the number 2 in cell A2.xlsx workbook.xlsm workbook file. In the new workbook that you just opened. We will not have any macros in this workbook. If you’d like to run the macros you recorded earlier in this chapter in another workbook. PRINTING MACROS If you want to document your macro or perhaps study the macro code when you are away from the computer.xlsm!WhatsInACell macro and click Run. The macro goes to work again. Close the Practice_Excel01Calc. Recall that we told Excel to associate the macro with the Practice_Excel01. But before you do this. Activate Sheet1 in the Practice_Excel01Calc. the number 4 in cell A3.

Hands-On 1.xlsb and places it in one of the following locations: \Users\< username >\AppData\Roaming\Microsoft\Excel\XLSTART \Program Files\Microsoft Office15\Root\Office15\XLSTART Note that AppData is a Windows hidden folder and you will need to unhide it to view its contents. Click OK to print the highlighted code. the Selection option button should be selected. In the Print . Choose File | Print.VBAProject dialog box. Any file saved to the XLSTART folder is loaded automatically each . Switch to the Visual Basic Editor window and double-click Module1 in the Project Explorer window to activate the module containing the WhatsInACell macro. In the Print . If you’d like to only print a certain block of programming code. 4. When you store a macro in the Personal macro workbook. Excel creates a file named Personal. Printing Macro Code 1. 8.VBAProject dialog box.19. the Current Module option button should be selected. Click OK to print the entire module sheet. 7. 6. you can specify to store the macro code in the Personal macro workbook. 3. 2. perform the following steps: 5. STORING MACROS IN THE PERSONAL MACRO WORKBOOK When you record a macro. Choose File | Print. In the module sheet. highlight the code you want to print.

27. 5.xlsb. Choose OK to exit the Record Macro dialog box. 7. click the plus sign (+) to the left of the project name. Choose View | Macros | Record Macro. This activates the Visual Basic Editor window. Make sure you are in the Microsoft Excel application window. Click the Stop Recording button in the status bar. Because you have now turned on the display of formulas.20. In the Record Macro dialog box. To see the macro code. Click in the Shortcut key text box. The Code window shows the code of the FormulasOnOff macro. 3. 9.time you start Excel. 6. Recording a Macro in the Personal Macro Workbook 1. Notice that the Project Explorer window now shows an additional VBA project (Personal. 2. and press Shift+F. The Personal macro workbook is a convenient place to store general-purpose macros like the FormulasOnOff macro recorded in the next HandsOn. 10. Click the plus sign (+) next to the Modules folder to open it and then double-click Module1. 11. The purpose of this macro is to toggle the display of worksheet formulas. enter FormulasOnOff in the Macro name box. The VBA project contains two folders: Microsoft Excel Objects and Modules. Choose Formulas | Formula Auditing | Show Formulas. .xlsb). To open Personal. the worksheet cells show the formulas instead of the values that the formulas produce. as shown in Figure 1. 4. Choose Personal Macro Workbook from the Store macro in the drop-down list. or choose View | Macros | Stop Recording. choose Developer | Controls | View Code . Hands-On 1. 8.

If you record another macro in the same workbook.27. Excel creates a Modules folder and places your macro code in Module1.FIGURE 1. and record a new macro. Excel places it below the previously recorded macro in the same Module1 sheet. reopen the same workbook. If you close Excel.DisplayFormulas = True The setting that will turn off the display of formulas looks like this: ActiveWindow.DisplayFormulas = False 12. you need to connect the statements shown in the previous step in the following way: . you turned on the display of formulas. you must edit it. Notice that each Excel workbook contains a single project. Macros recorded in the Personal.xlsb workbook are accessible from any workbook. To make the macro behave this way. The following recorded macro line sets the display of formulas in the active window to True: ActiveWindow. To make a toggle in VBA. All macros recorded in the same work session are stored in the same module. The first time you record a macro. When you recorded your macro. The macro name suggests that the macro can toggle the formulas. Excel will store it in a new module.

all you will see is the change in the width of . Click Yes to save the changes.DisplayFormulas 13. Choose Run | Run Sub/UserForm to execute the macro. You can use the same idea to create macros that toggle the display of gridlines and other Microsoft Excel features. Because the workbook does not contain any data. You will be prompted to save the changes you made to the Personal macro workbook. Restart Excel. Replace the recorded macro line with the statement in Step 12. Switch back to the Microsoft Excel application window by pressing Alt+F11 and press Ctrl+Shift+F to run the macro again. 16.xlsm workbook file and click OK when prompted to save changes. Close the Practice_Excel01. press Ctrl+Shift+F. the Personal macro workbook will automatically load in the background. To run the FormulasOnOff macro right now.DisplayFormulas End Sub 14. 18. it always knows what to do. The following is the revised macro code: Sub FormulasOnOff() ' ' FormulasOnOff Macro ' ' Keyboard Shortcut: Ctrl+Shift+F ' ActiveWindow. Exit Microsoft Excel.ActiveWindow. When you restart Excel.DisplayFormulas = Not ActiveWindow. 17.DisplayFormulas = Not ActiveWindow. 15. 19. No matter how many times you run this macro.

cls). *. . choose File | Import File to bring the macro code from a text file or another Visual Basic project file (*. Press Alt+F11 to switch back to the Microsoft Excel application window. Switch to the Visual Basic Editor and open the project that contains the macro you want to move to the Personal macro workbook. CHAPTER SUMMARY In this chapter. you have learned how to create macros by recording your selections in the Microsoft Excel application window. Click No when prompted to save changes in Book1. You also learned how to view. read. 22. 20. or create a new module prior to pasting. 21.the worksheet columns. you can take one of the following routes: Record a new macro and choose the Personal macro workbook for its storage location. Storing Other Macros in the Personal Workbook If you want to store other macros in the Personal macro workbook. In the Visual Basic Editor window. Notice that the Personal. and modify the recorded macros in the Visual Basic Editor window. Cut the macro code from the current location and open the Personal macro workbook project. Press Ctrl+Shift+F again to turn off the display of formulas. Press Alt+F11 to switch to the Visual Basic Editor window. you tried various methods of running macros. Paste the macro code into the existing module in the Personal macro workbook.bas. Exit Microsoft Excel. 23. In addition. *.xlsb file is listed in the Project Explorer window as a separate project. This chapter has also explained macro security issues that you should be aware of when opening workbooks containing macro code.frm.

The next chapter introduces you to various windows that are available in the Visual Basic Editor screen. .

Chapter 2 Exploring the Visual Basic Editor (VBE) Now that you know how to record. Press Alt+F11. Test VBA procedures and locate errors. let’s spend some time in the Visual Basic Editor window and become familiar with its features. Choose Developer | Controls | View Code. With the tools located in the Visual Basic Editor window. and edit macros. Create custom forms. View and modify object properties. UNDERSTANDING THE PROJECT EXPLORER WINDOW The Project Explorer window displays a hierarchical list of currently open projects and their elements. you can: Write your own VBA procedures. run. The Visual Basic Editor window can be accessed in the following ways: Choose Developer | Code | Visual Basic. A VBA project can contain the following elements: .

FIGURE 2.1. From the keyboard by pressing Ctrl+R.Worksheets Charts ThisWorkbook—The workbook where the project is stored Modules—Special sheets where programming code is stored Classes—Special modules that allow you to create your own objects Forms References to other projects With the Project Explorer you can manage your projects and easily move between projects that are loaded into memory. .1. You can activate the Project Explorer window in one of three ways: From the View menu by selecting Project Explorer. From the Standard toolbar by clicking the Project Explorer button as shown in Figure 2. Buttons on the Standard toolbar provide a quick way to access many of the Visual Basic Editor features.

Categorized tab—Lists all properties for the selected object by category.2. . The Properties window can be accessed in three ways: From the View menu by selecting Properties Window. You can collapse the list so that you see the categories. The first button from the left (View Code) displays the Code window for the selected module. UNDERSTANDING THE PROPERTIES WINDOW The Properties window allows you to review and set properties of various objects in your project. Alphabetic tab—Lists alphabetically all properties for the selected object. From the keyboard by pressing F4. Properties of the object can be viewed alphabetically or by category by clicking on the appropriate tab as shown in Figure 2. The middle button (View Object) displays either the selected sheet in the Microsoft Excel Object folder or a form located in the Forms folder. From the toolbar by clicking the Properties Window button. or you can expand a category to see the properties.2 in the next section. The button on the right (Toggle Folders) hides and unhides the display of folders in the Project Explorer window.The Project Explorer window contains three buttons as shown in Figure 2. The name of the currently selected object is displayed in the Object box located just below the Properties window’s title bar. The plus sign (+) icon to the left of the category name indicates that the category list can be expanded. You can change the property setting by selecting the property name and typing or selecting the new setting. The minus sign (–) indicates that the category is currently expanded.

.

4. (Top) The Project Explorer window displays a list of currently open projects. you will notice at the top of the Code window two drop-down list boxes that allow you to move quickly within the Visual Basic code. the cursor will jump to the first line of this procedure. UNDERSTANDING THE CODE WINDOW The Code window is used for Visual Basic programming as well as viewing and modifying the code of recorded macros and existing VBA procedures.FIGURE 2. In the Object box on the left side of the Code window. If you select a procedure in the Procedures/Events box.3. you can select the object whose code you want to view. You can then view different sections of a long procedure or a different procedure in each pane. (Bottom) The Properties window displays the settings for the object currently selected in the Project Explorer. choose View | Code. From the menu bar. The box on the right side of the Code window lets you quickly choose a particular procedure or event procedure to view. When you open this box. choose the appropriate UserForm or module. Each module can be opened in a separate Code window. This two-pane display in the Code window is often used for copying or cutting and pasting sections of code between procedures of the same module.3 down to a selected position in the Code window. press F7. By dragging the split bar shown in Figure 2. In Figure 2.2. the names of all procedures located in a module are sorted alphabetically. and click the View Code button. From the keyboard. . There are several ways to activate the Code window: From the Project Explorer window. you can divide the Code window into two panes as illustrated in Figure 2.

use the Procedures/Events box. To select another procedure. Use the vertical scrollbar to scroll through the module’s code. The Procedure View icon displays one procedure at a time in the Code window. skim through Chapter 10. there are two icons. At the bottom left of the Code window. “VBE Tools for Testing and Debugging.FIGURE 2. The Visual Basic Code window has several elements that make it easy to locate procedures and review the VBA code.3. The margin indicator bar is used by Visual Basic Editor to display helpful indicators during editing and debugging. If you’d like to take a quick look at some of these indicators. simply drag the split bar all the way to the top of the Code window. The Full Module View icon displays all the procedures in the selected module.” . To return to the one-window display.

The Form window is used for creating custom dialog boxes and user forms. You will learn how to do these things in Chapter 18.4.5 displays the list of windows that can be docked in the Visual Basic Editor window. “Using Dialog Boxes. . OTHER WINDOWS IN THE VISUAL BASIC EDITOR WINDOW There are several other windows that are frequently used in the Visual Basic environment. you can divide the Code window into two panes by dragging down the split bar shown in Figure 2. Watch window). To review longer procedures. Immediate window) and Chapter 10 (Locals window.” Figure 2. You will learn how to use some of these windows in Chapter 3 (Object Browser.FIGURE 2.3.

ASSIGNING A NAME TO THE VBA PROJECT A project is a set of Microsoft Excel objects. Let’s assign names to the VBA projects (Practice_Excel01. VBAProject. “Automating Worksheet Tasks with Macros.” Avoid Naming Conflicts .xlsm and Personal. Instead of the default name. and references.5. that precedes the name of the workbook in the Project Explorer window. The Docking tab in the Tools | Options dialog box allows you to choose which windows you want to be dockable in the Visual Basic Editor screen.FIGURE 2. modules. each project should have a unique name.xlsb) that you worked with in Chapter 1. forms.

. as shown in Figure 2. The Project Properties dialog box appears. select the name of the project. You can change the name of the project in one of the following ways: In the Project Explorer window. give your projects unique names. Type the new project name in the Project Name text box and click OK. In the Project Explorer window. right-click the name of the project and select VBAProject Properties. and enter a new name.To avoid naming conflicts between your VBA projects.6. in the Properties window. double-click the (Name) property.

6. Hands-On 2. Please note files for the “Hands-On” project may be found on the companion CDROM. Renaming the VBA Project . The Project Properties dialog can be used for changing the name and description of the selected VBA project that is highlighted in the Project Explorer window.FIGURE 2.1.

The code modules are placed in the Modules folder that can be accessed from the Project Explorer window. and so on. In the Properties window. To avoid confusion with the names of the modules. code modules in the new VBA project are again named Module1. Module2.xlsb) as the name of the VBA project. In the Project Explorer window. highlight VBAProject (Personal. RENAMING THE MODULE When you record a macro or create a new procedure from scratch. 8. and so on. Type Personal for the name of the VBA project and press Enter. Notice that the Project Explorer window now displays FirstSteps (Practice_Excel01. Start Microsoft Excel. . window. Recall that the Personal macro workbook where you recorded the FormulasOnOff macro will be automatically loaded when you start Excel. 6. Visual Basic stores your VBA code in special sheets called Module1.xlsm where your WhatsInACell macro code is stored. 5.xlsb). 2. double-click the (Name) property.xlsb) projects.1.xlsm). Having code modules with the same name can be very confusing not only to you but also to Visual Basic because it tries to execute your macros or Visual Basic procedures in an environment where several projects may be open. let’s assign unique names to Module1 in the FirstSteps (Practice_Excel01.xlsm) and Personal (Personal. In the Project Explorer (Practice_Excel01. 3. Notice that the Project Explorer window now displays Personal (Personal. highlight VBA project 4. Module2.xlsm) as the name of the VBA project. double-click the (Name) property. Press Alt+F11 to switch to the Visual Basic Editor window. and open C:\Excel2013_ByExample\Practice_Excel01. When you open up a new workbook and create VBA procedures. This action selects the default project name VBAProject. 7. In the Properties window. Type FirstSteps for the name of the VBA project and press Enter.

3. double-click the (Name) property. In the Properties window. Renaming the Module 1.Hands-On 2.xlsm) project. 6.7 shows the Project Explorer window with WorksheetFormatting as the name of the module. Figure 2. 2. 4. . Figure 2. Module1. In the Project Explorer window. This action selects the default module name.xlsb) project. This action selects the default module name. In the Project Explorer window.7 shows the Project Explorer window with Switches as the name of the module. double-click the (Name) property. Type WorksheetFormatting for the name of Module1 and press Enter. In the Properties window. Type Switches for the name of Module1 and press Enter. Module1. highlight Module1 in the Modules folder under the Personal (Personal.2. 5. highlight Module1 in the Modules folder under the FirstSteps (Practice_Excel01.

.7. The Project Explorer window now shows the unique names that were assigned to VBA projects and modules using the Name property in the Properties window.FIGURE 2. UNDERSTANDING DIGITAL SIGNATURES You already know from Chapter 1 that Excel macros can be signed or unsigned.

3. 4. macros are unsigned and disabled. Click Close to close the Certificates dialog box.By default. Click Cancel to close the Internet Properties dialog box and then close the Control Panel. A digital signature confirms that the programming code comes from a specific author and that it has not been tampered with or altered in any way since the VBA project was signed. 2.3. Viewing Digital Certificates on Your Computer 1. you can digitally sign your VBA projects. you must purchase a digital certificate from a trusted organization called a certification authority (CA). To avoid the security prompt when opening workbooks with macros. it is a good idea to lock the VBA project before digitally signing it so that users will not accidentally modify your VBA code and invalidate your signature by attempting to save the code changes. click the Content tab. Also. In the Control Panel. In the Certificates dialog box. click the Trusted Root Certification Authorities tab. adding a digital signature should be the last step before the workbook file is ready for distribution. or create a digital certificate for your own use as described in the next section.. locate and activate Internet Options (Control Panel | System and Security | Network and Internet | Internet Options).8. 5. Because the digital signature is overwritten when the file is saved. Click the Certificates button. You should see a list of trusted authorities as shown in Figure 2. such as VeriSign. Before you can sign your macros. Inc. 6. Let’s start by taking a look at a list of trusted certification authorities that you could contact. . Hands-On 2. In the Internet Properties dialog box. When you (or others) open a workbook file containing signed macros. you will be able to see who the author is and you can decide whether to always trust macros from that publisher.

A listing of trusted certification authorities can be accessed via Internet Options (in the Control Panel) or Tools | Options (in Internet Explorer). .FIGURE 2. you can create a digital certificate yourself.8. CREATING A DIGITAL CERTIFICATE A digital certificate from a CA can cost several hundred dollars a year. If you simply want to avoid the security warning message when running your own macros. This certificate will only be valid on the machine where it was created. Let’s take a few minutes and create one right now.

look for it in the Microsoft Download center. If you cannot locate the SELFCERT. you will see the Create Digital Certificate dialog box shown in Figure 2.9. When you execute the SELFCERT.exe file on your computer. Locate on your computer the SELFCERT. .9.exe program file and run it by doubleclicking the file name. This file should be located in your C:\Program Files\Microsoft Office 15\root\office15 folder. FIGURE 2. Creating a Digital Certificate for Personal Use 1. Creating a digital certificate for personal use.4.Hands-On 2.exe program.

Using a Digital Certificate to Sign a VBA Project This Hands-On requires that your Macro Security Settings are set to Disable all macros with notification (see Figure 1. Make sure the Practice_Excel01. In the Project Explorer. Click the Protection tab and select the Lock project for viewing check box. The next time you open this workbook and decide to view the code. 2.2. Hands-On 2. right-click the FirstSteps (Practice_Excel01. Press Alt+F11 to switch to the Visual Basic Editor. 3.9 (we are using Macro Works here) and click OK.xlsm workbook is open. 4. When you see a message that the certificate was successfully created. then click OK.2 in Chapter 1). . 5. Enter secret for the password and re-enter it in the Confirm password box. let’s use it to sign the macros you created in Chapter 1.5.xlsm workbook file for this exercise. We will use the Practice_Excel01. 3. 1. SIGNING A VBA PROJECT Now that you’ve created a digital certificate on your machine. click OK. Enter a name for the certificate as shown in Figure 2. you’ll need to provide the password you typed in this step.xlsm) project and click FirstSteps Properties on the shortcut menu.

You may want to replace the signature for either of the following reasons: You purchased an approved signature from a certification authority and you’d like to use it instead of the self-issued signature or the current signature has expired. A locked VBA project does not prevent you from replacing the current digital signature with another.Although you don’t need to lock the project from yourself. 6.10. . as shown in Figure 2. Select Tools | Digital Signature. You should see the Digital Signature dialog box. Steps 4 to 5 demonstrate how you can prevent others from viewing and altering your code.

11). 7. .10. Click on the Choose button in the Digital Signature dialog box. Visual Basic begins searching for certificates on your computer and after a short moment you should see the Windows Security window with the certificate you created earlier (see Figure 2.FIGURE 2. Signing a VBA project.

8.11. You should see the information about the certificate as shown in Figure 2.FIGURE 2. . Selecting a digital certificate.12. Click the provided link to view certificate details of Macro Works.

FIGURE 2. Viewing the Certificate Information. Click OK in the Window Security dialog to accept selected Macro Works certificate. Click OK to close the Certificate Details window.12. 9. 10. .

which now displays Macro Works as the name of the selected certificate as shown in Figure 2.13.You will be returned to the Digital Signature dialog box. .

13. 11.FIGURE 2. After selecting a digital certificate.xlsm workbook. 14. . Click Yes when prompted to save the changes.xlsm workbook file from the C:\Excel2010_ByExample folder to any other folder that has not been designated as a trusted location. copy the Practice_Excel01. Click Save when prompted to save changes in the Personal macro workbook. 13. You may want to copy this file to the C:\Excel2013_HandsOn folder that contains text files for this book’s Hands-On exercises. Click OK to finish signing your VBA project. In Windows Explorer. Close the Practice_Excel01. 12. its name appears in the Digital Signature dialog box. Exit Microsoft Excel.

Click the Macros have been disabled message in the Security Warning message bar as shown in Figure 2.14.15. FIGURE 2. Excel displays the dialog box shown in Figure 2. If you don’t see the message. 17. 18. Excel displays the security warning message that macros have been disabled.xlsm file to open the file in Excel. Excel activates the File Tab and displays the file information.2 in Chapter 1). .Macros dialog box. The Security Alert . as shown in Figure 2.14. 16. Click the drop-down arrow in the Enable Content button and select Advanced Options.15. This displays the certificate details. Do not click the Enable Content button.14. Click the Show Signature Details link in the Security Alert .Macros dialog box now displays the name of your digital signature. Double-click on the copy of the Practice_Excel01. ensure that your Macro Security Settings are set to Disable all macros with notification (see Figure 1.

19. In the Security Alert . General information about a digital signature.15. 20.FIGURE 2. you will notice that the Macro Works digital certificate has been added to the Trusted Publishers list as shown in Figure 2. select the option button to Trust all documents from this publisher. . Click OK to exit the Digital Signature Details dialog box.Macros dialog box.16. When you open the Trust Center. and then click OK.

xlsm) project in the Project Explorer window. Because this VBA project is locked you will be asked to enter the password. Press Alt+F11 to switch to the Visual Basic Editor screen. Press Alt+F11 to switch back to the Excel application window. make changes to the contents of your worksheet at any time. Double-click the FirstSteps (Practice_Excel01. 21. . however. 23. 25. You can. Enter secret for the password and click OK. 24.FIGURE 2. even if the VBA project is locked and signed. The Macro Works digital certificate that you used to sign the workbook created in Chapter 1 has been added to the list of Trusted Publishers in Excel’s Trust Center dialog box. 22. Now the VBA project is unlocked for your eyes only.16. Do not make any changes to the code as this will invalidate the digital signature.

Macros dialog. Reopen the C:\Excel2013_HandsOn\Practice_Excel01. CHAPTER SUMMARY This chapter has given you a quick tour of the Visual Basic Editor window so that you are ready to start working with it in the next chapter.xlsm workbook. 27. . You learned how to sign a VBA project with a self-issued digital certificate and how to protect your macros from others by locking a VBA project.26. Notice that the workbook file now opens without the Security Alert . Close the Practice_Excel01.xlsm workbook and exit Excel. The next chapter introduces you to the fundamentals of Visual Basic for Applications. Close the Practice_Excel01.xlsm workbook. You will acquire a useful VBA vocabulary that will let you delegate a great many tedious tasks to Excel.

There are various types of instructions. you will learn the terms and rules of VBA. . In Chapter 1. MODULES. and calls to other procedures. you learned the most popular VBA keywords—the words Sub and End Sub. These instructions are automatically placed in a workbook sheet called a module. AND PROCEDURES In Chapter 1. These words carry a special meaning in Visual Basic. which begin and end a procedure.” “Delete the contents of cell A5.” “Copy the formula from cell A1 to cell B1 ”? You may already know the individual words. A VBA procedure contains all of the recorded instructions. but do you know how to combine them correctly so that Excel can carry out these tasks? In this chapter. UNDERSTANDING INSTRUCTIONS. When the module sheet opens up in the Code window. To review the recorded macro code. you are able to analyze your procedure’s code. such as keywords. How do you say in Visual Basic. The same is true about learning how to program in Visual Basic for Applications. Let’s start with keywords.Chapter 3 Excel VBA Fundamentals Language study is a long-term activity during which you pass through various stages of proficiency. or the Personal macro workbook. you must activate the Visual Basic Editor window and double-click the Modules folder in the Project Explorer window. Excel stores the module in a Modules folder located in the current workbook. operators. you need to acquire new vocabulary and grammar. Because keywords are reserved by Visual Basic. There are no shortcuts. keywords appear in blue. a new workbook. Each line in a procedure is an instruction. By default. “Add a new worksheet to a workbook. don’t use these words for other purposes. you learned that Microsoft Excel’s macro recorder creates a series of instructions that are the exact equivalents of the actions you perform. Before you can customize Microsoft Excel with VBA.

. To call the procedure FormulasOnOff from the WhatsInACell macro. you must also include the module name in addition to the procedure name. FormulasOnOff End Sub However. When Visual Basic reaches this line. How can you do this? Without knowing any better. as shown in the following example: Sub WhatsInACell() Instructions. For example. and comparison. However. if two or more modules contain a procedure with the same name. Let’s suppose . Visual Basic instructions can contain operators. Suppose you want to include the statement you entered in the FormulasOnOff macro inside the WhatsInACell macro. Then it will return to the WhatsInACell macro to continue on with the remaining code. it will jump right into the FormulasOnOff procedure and execute its code. For example. In this book. you can call the procedure by specifying its name. if you want to process the FormulasOnOff macro instructions while Visual Basic executes the WhatsInACell macro. you get many opportunities to see how operators are used in VBA procedures. Instead of copying instructions between procedures. join. logical. Before you can try out an example of this. Is it hard to picture this? Let’s take the WhatsInACell macro you recorded in Chapter 1. enter FormulasOnOff on a separate line within this procedure. you could copy the required line of code from one procedure to another. Operators allow you to combine. There are four types of operators: arithmetic. you must learn how to call procedures from different projects. stopping when it reaches the End Sub keywords. there is an easier and quicker way. CALLING A PROCEDURE FROM ANOTHER PROJECT You can call a procedure located in any module in the same project by specifying the procedure name. all you need to do is specify the procedure name..In addition to keywords. the division operator (/) can be used to calculate the percentage of the total. Calls to procedures allow you to quickly jump to other procedures and execute other sets of instructions. Let’s suppose that the procedure FormulasOnOff is located in another module but in the same VBA project as the WhatsInACell macro. and manipulate certain values. string concatenation. Another type of Visual Basic instruction is a call to a procedure.

while the Switches module and Formulas module both contain the FormulasOnOff macro. as shown in the following example. begin by setting up the reference to that project.1 you will learn how you can call the FormulasOnOff macro. enter secret and click OK. Switches.. In Hands-On 3. Start Microsoft Excel and open the C:\Excel2013_ByExample\Practice_Excel01. from the WhatsInACell macro. Running a VBA Procedure from Another Procedure 1.xlsb) project. . located in the Personal (Personal.that the FirstSteps (Practice_Excel01.xlsm workbook file you created in Chapter 1. you need to precede the procedure name with the module name. Hands-On 3.xlsm). You do this in the References dialog box. Please note files for the “Hands-On” project may be found on the companion CD-ROM.xlsm) project has three modules.1. double-click FirstSteps (Practice_Excel01. To call FormulasOnOff (located in the Switches module) from the WhatsInACell macro.. If you are prompted for a password. In the Project Explorer window. Press Alt+F11 to switch to the Microsoft Visual Basic Editor window. 3. as shown in the following example: Sub WhatsInACell() Instructions.FormulasOnOff End Sub To call a procedure from a different project. The WorksheetFormatting module contains the WhatsInACell macro. 2.

and click OK. Choose Tools | References . Note that if a VBA project is locked for viewing.1. click the check box next to Personal as shown in Figure 3. make sure hidden files and extensions are selected in folder options.4. the References command on the Tools menu is disabled. click the Browse button and look for the Personal. 5. In the References dialog box. .xlsb file in one of the following locations: \Users\< username >\AppData\Roaming\Microsoft\Excel\XLSTART \Program Files\Microsoft Office 15\XLSTART To see the AppData folder. If Personal is not listed in the Available References area of the References dialog box.

. as shown in Figure 3. you must establish a reference to the other project. If you want to execute a procedure located in a different project. After you have set up a reference to another VBA project.1. The References dialog box lists all the references available to your project.Figure 3.2. the Project Explorer window displays the References folder with the name of the created reference.

xlsb workbook. A reference has been established to the Personal. .2.2 to call the FormulasOnOff macro from the WhatsInACell procedure.Figure 3. let’s proceed to Hands-On 3. Now that the reference to the Personal project has been established.

Hands-On 3.2. Calling One Macro from Another Macro

1. In the Project Explorer window, double-click WorksheetFormatting in
FirstSteps (Practice_Excel01.xlsm).
2. In the WhatsInACell macro, enter a new line just before MsgBox “All actions
have been performed” and type FormulasOnOff.
3. Press Alt+F11 to return to the Microsoft Excel window and make sure that
Sheet1 contains the example spreadsheet.
4. Run the WhatsInACell macro using any of the techniques you learned in Chapter
1. After you run this macro, Sheet1 should be formatted as shown in Figure 3.3.

Figure 3.3. This worksheet has been formatted in one step using the
WhatsInACell and FormulasOnOff macros.

5. Click the Remove Formats button on the worksheet.
6. Press Ctrl+~ on the keyboard to remove the display of formulas (or alternatively
run the FormulasOnOff macro).
How Visual Basic Locates the Called Procedure
When you call a procedure, Visual Basic first looks for it in the same module

where the calling procedure (WhatsInACell) is located. If the called procedure
(FormulasOnOff) is not found in the same module, Visual Basic searches other
modules in the same project. If the procedure still can’t be found, Visual Basic
checks the references to other projects.

Setting up a Reference to Another VBA Project
If you want to call a procedure from another VBA project and that project is
currently closed, perform the following steps to establish the project reference:
1. Choose Tools | References.
2. In the References dialog box, click the Browse button and open the folder where
the project is located. By default, the Add Reference dialog box lists Library
Files (*.olb, .tlb, .dll).
3. Choose Microsoft Excel Files (*.xlsm, *.xlam, *.xls) from the Files of Type
drop-down list.
4. Select the file that contains the procedure you want to set the reference to.
5. Click the Open button. The name of the project will be added as the last entry in
the References dialog box.
6. Click OK to close the References dialog box.

UNDERSTANDING OBJECTS, PROPERTIES, AND
METHODS
You can create procedures that control many features of Microsoft Excel through
the use of Visual Basic for Applications. You can also control a large number of other
applications. The power of Visual Basic comes from its ability to control and manage
various objects. But what is an object?
An object is a thing you can control with VBA. Workbooks, a worksheet, a range
in a worksheet, a chart, or a toolbar are just a few examples of the objects you may
want to control while working in Excel. Excel contains a multitude of objects that you
can manipulate in different ways. All of these objects are organized in a hierarchy.

Some objects may contain other objects. For example, Microsoft Excel is an
Application object. The Application object contains other objects, such as workbooks
or command bars. The Workbook object may contain other objects, such as
worksheets or charts. In this chapter, you will learn how to control the following
Excel objects: Range, Window, Worksheet, Workbook, and Application. You begin
by learning about the Range object. You can’t do much work in spreadsheets unless
you know how to manipulate ranges of cells.
Certain objects look alike. For example, if you open a new workbook and
examine its worksheets, you won’t see any differences. A group of like objects is
called a collection. A Worksheets collection includes all worksheets in a particular
workbook, while the CommandBars collection contains all the toolbars and menu
bars. Collections are also objects. In Microsoft Excel, the most frequently used
collections are:
Workbooks collection—Represents all currently open workbooks.
Worksheets collection—Represents all the Worksheet objects in the specified or
active workbook. Each Worksheet object represents a worksheet.
Sheets collection—Represents all the sheets in the specified or active workbook.
The Sheets collection can contain Chart or Worksheet objects.
Windows collection—Represents all the Window objects in Microsoft Excel.
The Windows collection for the Application object contains all the windows in
the application, whereas the Windows collection for the Workbook object
contains only the windows in the specified workbook.
When you work with collections, you can perform the same action on all the
objects in the collection.
Each object has some characteristics that allow you to describe the object. In
Visual Basic, the object’s characteristics are called properties. For example, a
Workbook object has a Name property, and the Range object has such properties as
Column, Font, Formula, Name, Row, Style, and Value. The object properties can be
set. When you set an object’s property, you control its appearance or its position.
Object properties can take on only one specific value at any one time. For example,
the active workbook can’t be called two different names at the same time.
The most difficult part of Visual Basic is to understand the fact that some
properties can also be objects. Let’s consider the Range object. You can change the
appearance of the selected range of cells by setting the Font property. But the font can

have a different name (Times New Roman, Arial, …), different size (10, 12, 14, …),
and different style (bold, italic, underline, …). These are font properties. If the font
has properties, then the font is also an object.
Properties are great. They let you change the look of the object, but how can you
control the actions? Before you can make Excel carry out some tasks, you need to
know another term. Objects have methods. Each action you want the object to perform
is called a method. The most important Visual Basic method is the Add method, which
you can use to add a new workbook or worksheet. Objects can use various methods.
For example, the Range object has special methods that allow you to clear the cell
contents (ClearContents method), formats (ClearFormats method), and both
contents and formats (Clear method). Other methods allow objects to be selected,
copied, or moved.
Methods can have optional parameters that specify how the method is to be
carried out. For example, the Workbook object has a method called Close. You can
close any open workbook using this method. If there are changes to the workbook,
Microsoft Excel will display a message prompting you to save the changes. You can
use the Close method with the SaveChanges parameter set to False to close the
workbook and discard any changes that have been made to it, as in the following
example:
Workbooks("Practice_Excel01.xls").Close
SaveChanges:=False

MICROSOFT EXCEL OBJECT MODEL
When you learn new things, theory can give you the necessary background, but
how do you really know what’s where? All the available Excel objects as well as
their properties and methods can be looked up in the online Excel Object Model
Reference that you can access by choosing Help | Microsoft Visual Basic for
Applications Help in the Visual Basic Editor window. Figure 3.4 illustrates the Excel
object model reference in the online help. This page can be accessed via the following
link:
http://msdn.microsoft.com/en-us/library/ff194068.aspx

Objects are listed alphabetically for easy perusal, and when you click the object
you will see object subcategories that list the object’s properties, methods, and events.
Reading the object model reference is a great way to learn about Excel objects and
collections of objects. The time you spend here will pay big dividends later when you
need to write complex VBA procedures from scratch. A good way to get started is to
always look up objects that you come across in Excel programming texts or example
procedures. Now take a few minutes to familiarize yourself with the main Excel object
—Application. This object allows you to specify application-level properties and
execute application-level methods. You will see several examples of working with the
Application object later in this chapter.

Figure 3.4. In your VBA programming work, always refer to the Excel
Object Model Reference that contains documentation for all the objects,
properties, methods, and events contained in the Excel object model.
VBA and Prior Versions of Microsoft Excel
Microsoft Excel online help lists changes made to the Microsoft Excel Object
Model in prior versions of Excel. Many objects, properties, and methods have been
replaced with new and improved features. To provide backward compatibility,
replaced objects have been hidden. For more information, see the online help. Hidden
objects can also be located in the Object Browser. If you right-click in the Object

Browser window, you can choose the option Show hidden members. You will learn
how to use the Object Browser later in this chapter.

WRITING VBA STATEMENTS
Suppose you want to delete the contents of cell A4. To do this manually, you
would select cell A4 and press the Delete key on your keyboard. To perform the same
operation using Visual Basic, you first need to find out how to make Excel select an
appropriate cell. Cell A4, like any other worksheet cell, is represented by the Range
object. Visual Basic does not have a Delete method for deleting contents of cells.
Instead, you should use the ClearContents method, as in the following example:
Range("A4").ClearContents
Notice the dot operator between the name of the object and its method. This
instruction removes the contents of cell A4. However, how do you make Excel delete
the contents of cell A4 located in the first sheet of the Practice_Excel03.xlsm
workbook? Let’s also assume that there are several workbooks open. If you don’t
want to end up deleting the contents of cell A4 from the wrong workbook or
worksheet, you must write a detailed instruction so that Visual Basic knows where to
locate the necessary cell:

Application.Workbooks("Practice_Excel03.xlsm").Worksheets
("Sheet1").Range("A4").ClearContents
The above instruction should be written on one line and read from right to left as
follows: Clear the contents of cell A4, which is part of a range located in a worksheet
named Sheet1 contained in a workbook named Practice_Excel03.xlsm, which in turn
is part of the Excel application. Be sure to include the letter “s” at the end of the
collection names: Workbooks and Worksheets. All references to the names of
workbooks, worksheets, and cells must be enclosed in quotation marks.

SYNTAX VERSUS GRAMMAR
Now that you know the basic elements of VBA (objects, properties, and methods),

it’s time to start using them. But how do you combine objects, properties, and methods
into correct language structures? Every language has grammar rules that people follow
in order to make themselves understood. Whether you communicate in English,
Spanish, French, or another language, you apply certain rules to your writing and
speech. In programming, we use the term syntax to specify language rules. You can
look up the syntax of each object, property, or method in the online help or in the
Object Browser window.
To make sure Excel always understands what you mean, just stick to the
following rules:
Rule #1: Referring to the property of an object
If the property does not have arguments, the syntax is as follows:
Object.Property
Object is a placeholder. It is where you should place the name of the actual
object that you are trying to access. Property is also a placeholder. Here you place the
name of the object’s characteristics. For example, to refer to the value entered in cell
A4 on your worksheet, you can write the following instruction:

Notice that there is a period between the name of the object and its property.
When you need to access the property of an object that is contained within
several other objects, you must include the names of all objects in turn, separated by
the dot operator, as shown below:
ActiveSheet.Shapes(2).Line.Weight
The example above references the Weight property of the Line object and refers
to the second object in the collection of Shapes located in the active worksheet.

Some properties require one or more arguments. For example, when using the
Offset property, you can select a cell relative to the active cell. The Offset property
requires two arguments. The first argument indicates the row number (rowOffset),
and the second one determines the column number (columnOffset).

In this example, assuming the active cell is A1, Offset(3, 2) will reference the
cell located three rows down and two columns to the right of cell A1. In other words,
cell C4 is referenced. Because the arguments placed within parentheses are often
difficult to understand, it’s common practice to precede the value of the argument with
its name, as in the following example:
ActiveCell.Offset(rowOffset:=3,
columnOffset:=2)
Notice that a colon and an equals sign always follow the named arguments. When
you use the named arguments, you can list them in any order. The above instruction can
also be written as follows:
ActiveCell.Offset(columnOffset:=2,
rowOffset:=3)
The revised instruction does not change the meaning; you are still referencing cell
C4 assuming that A1 is the active cell. However, if you transpose the arguments in a
statement that does not use named arguments, you will end up referencing another cell.
For example, the statement ActiveCell.Offset(2, 3) will reference cell D3
instead of C4.
Rule #2: Changing the property of an object
Object.Property = Value
Value is a new value that you want to assign to the property of the object. The
value can be:

A number. The following instruction enters the number 25 in cell A4.

Text entered in quotes. The following instruction changes the font of the active
cell to Times New Roman.
ActiveCell.Font.Name = "Times New Roman"
A logical value (True or False). The following instruction applies bold
formatting to the active cell.
ActiveCell.Font.Bold = True
Rule #3: Returning the current value of the object property
Variable = Object.Property
Variable is the name of the storage location where Visual Basic is going to store
the property setting. You will learn about variables in Chapter 4, “Using Variables,
Data Types, and Constants.”

This instruction saves the current value of cell A4 in the variable named
CellValue.
Rule #4: Referring to the object’s method
If the method does not have arguments, the syntax is as follows:
Object.Method

Object is a placeholder. It is where you should place the name of the actual
object that you are trying to access. Method is also a placeholder. Here you place the
name of the action you want to perform on the object. For example, to clear the
contents in cell A4, use the following instruction:

If the method requires arguments, the syntax is as follows:
Object.Method (argument1, argument2, ...
argumentN)
For example, using the GoTo method, you can quickly select any range in a
workbook. The syntax of the GoTo method is shown below:
Object.GoTo(Reference, Scroll)
The Reference argument is the destination cell or range. The Scroll argument
can be set to True to scroll through the window or to False to not scroll through the
window. For example, the following VBA statement selects cell P100 in Sheet1 and
scrolls through the window:
Application.GoTo _
Reference:=Worksheets("Sheet1").Range("P100"),
_
Scroll:=True
The above instruction did not fit on one line, so it was broken into sections using
the special line continuation character (the underscore), described in the next section.

BREAKING UP LONG VBA STATEMENTS

You can break up a long VBA statement into two or more lines to make your
procedure more readable. Visual Basic has a special line continuation character that
can be used at the end of a line to indicate that the next line is a continuation of the
previous one, as in the following example:
Selection.PasteSpecial _
Paste:=xlValues, _
Operation:=xlMultiply, _
SkipBlanks: =False, _
Transpose:=False
The line continuation character is the underscore (_). You must precede the
underscore with a space.
You can use the line continuation character in your code before or after:
Operators; for example: &, +, Like, NOT, AND
A comma
An equals sign
An assignment operator (:=)
You cannot use the line continuation character between a colon and an equals
sign. For example, the following use of the continuation character is not recognized by
Visual Basic:
Selection.PasteSpecial Paste: _
=xlValues, Operation: _
=xlMultiply, SkipBlanks: _
=False, Transpose: _
=False
Also, you may not use the line continuation character within text enclosed in
quotes. For example, the following usage of the underscore is invalid:

MsgBox "To continue the long instruction, use the _
line continuation character."
The above instruction should be broken up as follows:
MsgBox "To continue the long instruction, use the "
& _
"line continuation character."

UNDERSTANDING VBA ERRORS
In the course of writing or editing VBA procedures, no matter how careful you are,
you’re likely to make some mistakes. For example, you may misspell a statement,
misplace a comma or quote, or forget a period or ending parenthesis. These kinds of
mistakes are known as syntax errors. Fortunately, Visual Basic is quite helpful in
spotting this kind of error. To have Visual Basic automatically check for correct
syntax after you enter a line of code, choose Tools | Options in the Visual Basic Editor
window. Make sure the Auto Syntax Check setting is checked on the Editor tab as
shown in Figure 3.5.

Figure 3.5. The Auto Syntax Check setting on the Editor tab of the Options
dialog box allows you to find typos in your VBA procedures.
When Visual Basic finds a syntax error, it displays an error message box and
changes the color of the incorrect line of code to red as shown in Figure 3.6, or
another color that can be set on the Editor Format tab in the Options dialog box.

Figure 3.6. This error message was caused by a missing beginning
parenthesis in front of xlCellTypeConstants.
If the explanation in the error message isn’t clear, try clicking the Help button for
more information. If the Visual Basic online help cannot point you in the right
direction, return to your procedure and carefully examine the offending instruction for
missed letters, quotes, periods, colons, equals signs, and beginning and ending
parentheses.
Finding syntax errors can be aggravating and time-consuming. Certain syntax
errors can be caught only during the execution of the procedure. While attempting to
run your procedure, Visual Basic can find errors that were caused by using invalid
arguments or omitting instructions that are used in pairs, such as If statements and
looping structures.

In addition to syntax errors, there are two other types of errors: runtime and
logic. Runtime errors occur while the procedure is running. A typical runtime error is
shown in Figure 3.7.
Runtime errors are often caused by those unexpected situations that the
programmer did not think of while writing the code. These occur, for example, when
the program is trying to access a drive or a file that does not exist on a user’s
computer, or copy a file to a CD-ROM or other media without first checking whether
the media is available.

Figure 3.7. When Visual Basic tries to select text cells when none exist in the
selected worksheet or range of cells, a runtime error occurs. In this example, the
procedure was run when a blank sheet was selected.
Program Bugs
You’ve probably heard more than once that “computer programs are full of bugs.”

In programming, errors are called bugs, and debugging is the process of eliminating
errors from your programs. The first step in debugging a procedure is to correct all
syntax errors. Visual Basic provides a myriad of tools with which to track down and
eliminate bugs. In this chapter, you will find out how you can use Visual Basic’s
assistance to write code with minimum errors. In Part IV, “Error Handling and
Debugging,” you will learn how to use special debugging tools to trap errors in your
VBA procedures.
The logic error often does not generate a specific error message. The
procedure may have no flaws in its syntax and may even run without errors, yet it
produces incorrect results. Logic errors are usually very difficult to locate, and
those that happen intermittently are so well concealed that you can count on
spending long hours, and even days, trying to locate the source of the error.

IN SEARCH OF HELP
When you use the macro recorder, all your actions are translated into VBA
instructions and placed in a module. When studying the recorded procedure, don’t
forget that help is within your reach. While the meaning of some of the instructions
may be pretty straightforward, you will probably find some of them less obvious. This
is the time to ask for help. When you’re working alone, your VBA tutor is just a click
or keypress away. You can quickly get to the necessary help page from the Visual
Basic Code window. Let’s take a few minutes to examine how, with the help of the
built-in VBA tutor, you can make the first instruction in the WhatsInACell procedure a
part of your VBA vocabulary:
Selection.SpecialCells(xlCellTypeConstants,
2).Select
The above instruction can be broken into three parts. What parts? Is Selection an
object or a property? What is SpecialCells? What is Select? To answer these
questions, perform the following exercise.

Hands-On 3.3. Dissecting the Meaning of a VBA Statement

1. In the Visual Basic Editor window, activate the Code window with the
WhatsInACell procedure.
2. Position the cursor anywhere within the word Selection in the following
statement:
Selection.SpecialCells(xlCellTypeConstants,
2).Select

3. Press F1.
The online help system opens up. Because the cursor was located within the word
Selection, the screen tells you that Selection is a property of an Application or a
Window object. If you position the cursor within the next unknown term
(SpecialCells) and again follow the steps above, you end up on the SpecialCells
help screen and find out that SpecialCells is a method that returns a Range object as
described in Figure 3.8.

Figure 3.8. Objects, properties, and methods of Visual Basic for
Applications are explained in detail in the online help.
Notice that each Help screen contains lots of information. You can find out what
a particular expression returns and what parameters it takes. Additional information
can be found in the Remarks area. There is also an example section that shows
example statements or procedures that use the particular object, method, or property.
You can easily copy the code from the example into your own procedure. Simply
highlight the lines you want to copy and press Ctrl+C, or right-click the selection and
choose Copy from the shortcut menu. Switch to the Visual Basic Code window, click
in the location where you want to paste the code example, and press Ctrl+V or choose
Edit | Paste.

ON-THE-FLY SYNTAX AND PROGRAMMING ASSISTANCE
Figure 3.9 shows the Edit toolbar in the Visual Basic Editor window that contains
several buttons that let you enter correctly formatted VBA instructions with speed and
ease. If the Edit toolbar isn’t currently docked in the Visual Basic Editor window, you
can turn it on by choosing View | Toolbars | Edit.

Figure 3.9. Buttons located on the Edit toolbar make it easy to write and

format VBA instructions.
Writing procedures in Visual Basic requires that you use hundreds of built-in
instructions and functions. Because most people cannot memorize the correct syntax of
all the instructions that are available in VBA, the IntelliSense® technology provides
you with syntax and programming assistance on demand during the course of entering
instructions. While working in the Code window, you can have special windows pop
up and guide you through the process of creating correct VBA code.
List Properties/Methods
Each object can contain a number of properties and methods. When you enter the
name of the object and a period that separates the name of the object from its property
or method in the Code window, a pop-up menu may appear. This menu lists the
properties and methods available for the object that precedes the period as shown in
Figure 3.10. To turn on this automated feature, choose Tools | Options. In the Options
dialog box, click the Editor tab, and make sure the Auto List Members check box is
selected.

Figure 3.10. While you are entering the VBA instructions, Visual Basic
suggests properties and methods that can be used with the particular object.

To choose an item from the pop-up menu that appears, start typing the name of the
property or method that you want to select. When Excel highlights the correct item
name, press Enter to insert the item into your code and start a new line. Or, if you want
to continue writing instructions on the same line, press the Tab key instead. You can
also double-click the item to insert it in your code. To close the pop-up menu without
inserting an item, simply press Esc. When you press Esc to remove the pop-up menu,
Visual Basic will not display it again for the same object. To display the
Properties/Methods pop-up menu again, you can:
Press Ctrl+J.
Use the Backspace key to delete the period and type the period again.
Right-click in the Code window and select List Properties/Methods from the
shortcut menu.
Choose Edit | List Properties/Methods.
Click the List Properties/Methods button on the Edit toolbar.
List Constants
Earlier in this chapter, you learned that to assign a value to a property, you need to
use the following form:
Object.Property = Value
If there is a check mark next to the Auto List Members setting on the Editor tab in
the Options dialog box, Excel displays a pop-up menu listing the constants that are
valid for the property that precedes the equals sign.
A constant is a value that indicates a specific state or result. Excel and other
member applications of the Microsoft Office suite have a number of predefined, builtin constants. You will learn about constants, their types, and usage in Chapter 4.
Suppose you want your program to turn on the Page Break Preview of your
worksheet. In the Microsoft Excel application window, the View tab lists four types of
workbook views:

The Normal View is the default view for most tasks in Excel.
Page Layout View allows you to view the document as it will appear on the
printed page.
Page Break Preview allows you to see where pages will break when the
document is printed.
Custom Views allows you to save the set of display and print settings as a custom
view.
The first three view options are represented by a built-in constant. Microsoft
Excel constant names begin with the characters “xl.” As soon as you enter in the Code
window the instruction:
ActiveWindow.View =
a pop-up menu will appear with the names of valid constants for the property, as
shown in Figure 3.11.

Figure 3.11. The List Constants pop-up menu displays a list of constants that
are valid for the property entered.
To work with the List Constants pop-up menu, use the same techniques as for the
List Properties/Methods pop-up menu outlined in the preceding section.
The List Constants pop-up menu can be activated by pressing Ctrl+Shift+J or
clicking the List Constants button on the Edit toolbar.
Parameter Info

If you’ve had a chance to work with Excel worksheet functions, you already know
that many functions require one or more arguments (or parameters). For example,
here’s the syntax for the most common worksheet function:
SUM(number1,number2, ...)
where number1, number2, … are 1 to 30 arguments that you can add up.
Similar to functions, Visual Basic methods may require one or more arguments. If
a method requires an argument, you can see the names of required and optional
arguments in a tooltip box that appears just below the cursor as soon as you type the
beginning parenthesis as illustrated in Figure 3.12. In the tooltip, the current argument
is displayed in bold. When you supply the first argument and enter the comma, Visual
Basic displays the next argument in bold. Optional arguments are surrounded by
square brackets [ ].
You can open the Parameter Info tooltip using the keyboard. To do this, enter the
method or function name, follow it with the left parenthesis, and press Ctrl+Shift+I.
You can also click the Parameter Info button on the Edit toolbar or choose Edit |
Parameter Info.

Figure 3.12. A tooltip displays a list of arguments utilized by a VBA method.
The Parameter Info feature makes it easy for you to supply correct arguments to a
VBA method. In addition, it reminds you of two other things that are very important for
the method to work correctly: the order of the arguments and the required data type of
each argument. You will learn about data types in Chapter 4.
Quick Info
When you select an instruction, function, method, procedure name, or constant in
the Code window and then click the Quick Info button on the Edit toolbar (or press

Ctrl+I), Visual Basic will display the syntax of the highlighted item, as well as the
value of a constant, as depicted in Figure 3.13. The Quick Info feature can be turned
on or off using the Options dialog box. To use the feature, click the Editor tab and
choose the Auto Quick Info option.

Figure 3.13. The Quick Info feature can provide you with a list of arguments
required by a selected method or function, a value of a selected constant, or the
type of the selected object or property.
Complete Word
Another way to increase the speed of writing VBA procedures in the Code
window is with the Complete Word feature. As you enter the first few letters of a
keyword and press Ctrl+Spacebar, or click the Complete Word button on the Edit
toolbar, Visual Basic will save you time entering the remaining letters by completing
the keyword entry for you. For example, when you enter the first four letters of the
keyword Application (Appl) in the Code window and press Ctrl+Spacebar, Visual
Basic will complete the rest of the word, and in the place of “Appl,” you will see the
entire word “Application.”
If there are several VBA keywords that begin with the same letters, Visual Basic
will display a pop-up menu listing all the keywords when you press Ctrl+Spacebar.
Select the appropriate keyword from the pop-up menu and press Enter.
Indent/Outdent
As you saw in Figure 3.5, the Editor tab in the Options dialog box contains a
number of settings that you can enable to make many automated features available in
the Code window. If the Auto Indent option is turned on, you can automatically indent
the selected lines of code by the number of characters specified in the Tab Width text
box. The default entry for Auto Indent is four characters. You can easily change the
Tab Width by typing a new value in the text box.
Why would you want to use indentation in your code? When you indent certain

lines in your VBA procedures, you make them more readable and easier to understand.
Indenting is especially recommended for entering lines of code that make decisions or
repeat actions. You will learn how to create these kinds of Visual Basic instructions in
Chapters 6 and 7, “Decision Making with VBA” and “Repeating Actions in VBA.”
Let’s spend a few minutes learning how to apply the indent and outdent features to the
lines of code in the WhatsInACell macro.

Hands-On 3.4. Indenting/Outdenting Visual Basic Code

1. In the Project Explorer window, select the FirstSteps (Practice_Excel01.xlsm)
VBA project and activate the WorksheetFormatting module that contains the code
of the WhatsInACell macro.
2. Select the block of code beginning with the keyword With and ending with the
keywords End With.
3. Click the Indent button on the Edit toolbar or press Tab on the keyboard. The
selected block of instructions will move four spaces to the right if you are using
the default setting in the Tab Width box in the Options dialog box (Editor tab).
4. Click the Outdent button on the Edit toolbar or press Shift+Tab to return the
selected lines of code to the previous location in the Code window.
The Indent and Outdent options are also available from the Edit menu.
Comment Block/Uncomment Block
In Chapter 1, you learned that a single quote placed at the beginning of a line of
code denotes a comment. Not only do comments make it easier to understand what the
procedure does, but they are also very useful in testing and troubleshooting VBA
procedures.
For example, when you execute a procedure, it may not run as expected. Instead
of deleting the lines that may be responsible for the problems you encounter, you may
want to skip those lines of code for now and return to them later. By placing a single
quote at the beginning of the line you want to avoid, you can continue checking the
other parts of your procedure. While commenting one line of code by typing a single

quote works fine for most people, when it comes to turning entire blocks of code into
comments, you’ll find the Comment Block and Uncomment Block buttons on the Edit
toolbar very handy and easy to use.
To comment a few lines of code, simply select the lines and click the Comment
Block button.
To turn the commented code back into VBA instructions, select the lines and
click the Uncomment Block button.
If you don’t select text and click the Comment Block button, the single quote
is added only to the line of code where the cursor is currently located.

USING THE OBJECT BROWSER
If you want to move easily through the myriad of VBA elements and features,
examine the capabilities of the Object Browser. This special built-in tool is available
in the Visual Basic Editor window.
To access the Object Browser, use any of the following methods:
Press F2.
Choose View | Object Browser.
Click the Object Browser button on the toolbar.
The Object Browser allows you to browse through the objects that are available
to your VBA procedures, as well as view their properties, methods, and events. With
the aid of the Object Browser, you can move quickly between procedures in your own
VBA projects, as well as search for objects and methods across object type libraries.
The Object Browser window is divided into three sections as illustrated in
Figure 3.14. The top of the window displays the Project/Library drop-down list box
with the names of all libraries and projects that are available to the currently active
VBA project. A library is a special file that contains information about the objects in
an application. New libraries can be added via the References dialog box (Tools |
References). The entry for < All Libraries > lists the objects of all libraries that are
installed on your computer. When you select the library called Excel, you will see
only the names of the objects that are exclusive to Microsoft Excel. In contrast to the
Excel library, the VBA library lists the names of all the objects in Visual Basic for

Applications.

Figure 3.14. The Object Browser window allows you to browse through all
the objects, properties, and methods available to the current VBA project.
Below the Project/Library drop-down list box is a Search text box that allows
you to quickly find information in a particular library. This field remembers the last
four items for which you searched. To find only whole words, you can right-click
anywhere in the Object Browser window and choose Find Whole Word Only from the
shortcut menu.

The Search Results section of the Object Browser displays the library, class, and
member elements that met the criteria entered in the Search text box as shown in
Figure 3.15.

Figure 3.15. Searching for answers in the Object Browser.
When you type the search text and click the Search button (the binoculars icon),
Visual Basic expands the Object Browser dialog box to show the Search Results area.
You can hide or show the Search Results by clicking the button located to the right of
the Search button.
The Classes list box displays the available object classes in the selected library.
If you select a VBA project, this list shows objects in the project. In Figure 3.15 the
Application object class is selected. When you highlight a class, the list on the right-

hand side (Members) shows the properties, methods, and events available for that
class. By default, members are listed alphabetically. You can, however, organize the
members list by group type (properties, methods, or events) using the Group Members
command from the Object Browser shortcut menu.
If you select a VBA project in the Project/Library list box, the Members list box
will list all the procedures available in this project. To examine the code of a
procedure, simply double-click its name. If you select a VBA library, you will see a
listing of Visual Basic built-in functions and constants. If you need more information
on the selected class or a member, click the question mark button at the top of the
Object Browser window.
The bottom of the Object Browser window displays a code template area with
the definition of the selected member. If you click the green hyperlink text in the code
template, you can quickly jump to the selected member’s class or library in the Object
Browser window. Text displayed in the code template area can be copied to the
Windows clipboard and then pasted to a Code window. If the Code window is visible
while the Object Browser window is open, you can save time by dragging the
highlighted code template and dropping it into the Code window.
You can easily adjust the size of the various sections of the Object Browser
window by dragging the dividing horizontal and vertical lines.
Now that you’ve discovered the Object Browser, you may wonder how you can
put it to use in VBA programming. Let’s assume that you placed a text box in the
middle of your worksheet. How can you make Excel move this text box so that it is
positioned at the top left-hand corner of the sheet? Hands-On 3.5 should provide the
answer to this question.

Hands-On 3.5. Writing a VBA Procedure to Move a Text Box on the
Worksheet

1. Open a new workbook.
2. Choose Insert | Text |Text Box.
3. Now draw a box in the middle of the sheet and enter any text as shown in Figure
3.16.

4. Select any cell outside the text box area.
5. Press Alt+F11 to activate the Visual Basic Editor window, and select Personal
(Personal.xlsb) in the Project Explorer window.
6. Choose Insert | Module to add a new module sheet to the Personal Workbook.
7. In the Properties window, enter the new name for this module: Manipulations.
8. Choose View | Object Browser or press F2.
9. In the Project/Library list box, click the drop-down arrow and select the Excel
library.
10. Enter textbox as the search text in the Search box as shown in Figure 3.17, and
then click the Search button. Make sure you don’t enter a space in the search
string.

Figure 3.16. Excel displays the name of the inserted object in the Name
box above the worksheet.

you will see the Help window with more details on how to use this method. Visual Basic searches the Excel library and displays the search results. The code template at the bottom of the Object Browser shows the correct syntax for using this method.Figure 3.18. Using the Object Browser window. Looking at the members list.17. you can find the appropriate VBA instructions for writing your own procedures. It appears that the Shapes object shown in Figure 3. . you can quickly determine that the AddTextbox method is used for adding a new text box to a worksheet.17 is in control of our text box operations. as shown in Figure 3. If you select the AddTextbox method and press F1.

.

18.Shapes("TextBox 1") . as shown below: Sub MoveTextBox() With ActiveSheet. instead of: With ActiveSheet. To get detailed information on any item found in the ObjectBrowser.Top = 0 End With End Sub The MoveTextBox procedure selects TextBox 1 in the collection of Shapes. All you have to do now is return to the Code window and write the procedure to move the text box to the upper left-hand corner. Double-click the Manipulations module and enter the MoveTextBox procedure. TextBox 1 is the default name of the first object placed in the worksheet. Close the Object Browser window and the Help window if they are open.Left = 0 . you can refer to the member of a collection by its index. select the item and press F1.Figure 3. Excel assigns a new number (index) to it. you can quickly figure out that the Left and Top properties determine the position of the text box in a worksheet. Instead of using the object name.Shapes(1) . Each time you add a new object to your worksheet. When you examine the parameters of the AddTextbox method and their explanations in the Help window.Shapes("TextBox 1") enter: With ActiveSheet. 11. For example.Select .

Hands-On 3. Notice that the text box is now positioned at the top left-hand corner of the worksheet. 5. a circle. Press Alt+F11 to switch to the Microsoft Excel application window. 2.Left = 0 . or a rectangle—does not matter. Click outside the circle to deselect it. and so on. Place a small circle in the same worksheet where you originally placed the text box in Hands-On 3. the second object a number 2. Use the Oval shape in the Basic Shapes area of the Insert | Illustrations Shapes tool. 13. write a VBA procedure that will place the circle inside the text box. Writing a VBA Procedure to Move a Circle on the Worksheet 1. Let’s manipulate another object with Visual Basic by following the steps in Hands-On 3. Hold down the Shift key while drawing on the worksheet to create a perfect circle.Select . Press Alt+F11 to activate the Visual Basic Editor screen. In the Manipulations module’s Code window.5. 3. 4.12.6. Keep in mind that Excel numbers objects consecutively.Top = 0 . The type of object—whether it is a text box.6.Shapes(2) . The MoveCircle procedure shown below demonstrates how to move a circle to the top left-hand corner of the active worksheet: Sub MoveCircle() With ActiveSheet. Choose Run | Run Sub/UserForm to execute this procedure. The first object is assigned a number 1.

. USING THE VBA OBJECT LIBRARY In the previous examples. you will see how to use one of the built-in VBA functions to create a new Windows subfolder without leaving Excel. Enter file as the search text in the Search box and press the Search button.End With End Sub Moving a circle is similar to moving a text box or any other object placed in a worksheet. Notice that instead of referring to the circle by its name. interact with users. 7. 6. convert data types. In the following Hands-On 3. Visual Basic will enter the ending keywords End Sub. the procedure uses the object’s index. the VBA object library provides access to many built-in VBA functions grouped by categories. On a new line. 3. Press F2 to activate the Object Browser. Writing a VBA Procedure to Create a Folder in Windows 1. Hands-On 3. They allow you to manage files. you used the properties of objects that are members of the Shapes collection in the Excel object library.7 exercise. Oval 2. deal with text strings.7. 2. Click the drop-down arrow in the Project/Library list box and select VBA. 5. These functions are general in nature. set the date and time. or perform mathematical calculations. While the Excel library contains objects specific to using Microsoft Excel. 4. Press Enter. Return to the Manipulations module where you entered the MoveTextBox and MoveCircle procedures. type the name of the new procedure: Sub NewFolder().19. Scroll down in the Members list box and highlight the MkDir method as shown in Figure 3.

followed by “C:\Study. consult the Object Browser for names of the built-in VBA functions.19. 10.” Be sure to enter the name of the entire path in quotes. Click the Copy button (the middle button in the top row) in the Object Browser window to copy the selected method name to the Windows clipboard. The NewFolder procedure should look like this: . 8. Return to the Manipulations Code window and paste the copied instruction inside the procedure NewFolder.Figure 3. When writing procedures from scratch. 9. Enter a space.

Sub NewFolder() MkDir "C:\Study" End Sub 11. you could replace the MkDir method with the RmDir method. as shown here: Sub RemoveFolder() RmDir "C:\Study" End Sub The RmDir method allows you to remove unwanted folders from your hard disk. However. let’s write a new procedure called RemoveFolder in the Manipulations Code window. how about getting rid of it programmatically? The Object Browser displays many other methods that are useful for working with folders and files. To see the folder. and then rerun the NewFolder procedure. Check Windows Explorer to see that the Study folder is gone. Position the insertion point within the code of the NewFolder procedure and choose Run | Run Sub/UserForm to execute the NewFolder procedure. you may realize that you don’t need it after all. To remove the Study folder from your hard drive. Although you could easily delete the folder while in Windows Explorer. The RmDir method is just as simple to use as the MkDir method. Position the insertion point within the code of the RemoveFolder procedure and choose Run | Run Sub/UserForm to execute the RemoveFolder procedure. After creating a new folder. activate Windows Explorer. When you run the NewFolder procedure. 12. Locating Procedures with the Object Browser . Visual Basic creates a new folder on drive C. 13.

20. The left side of the Object Browser displays the names of objects that are included in the selected project. 2.8 exercise demonstrates how you can see.In addition to locating objects. and methods.8. Figure 3. select Personal from the Project/Library drop-down list as shown in Figure 3. properties. In the Object Browser. The Object Browser lists all the procedures available in a particular VBA project. Visual Basic positions the cursor in the first line of the selected procedure. Hands-On 3. The Members list box on the right shows the names of all the available procedures.20. which procedures are stored in the Personal Workbook. The Hands-On 3. the Object Browser is a handy tool for locating and accessing procedures written in various VBA projects. Using Object Browser to Locate VBA Procedures 1. at a glance. Double-click the NewFolder procedure. .

interactive language exercise: Enter a simple VBA instruction and Excel will check it out and display the result in the next line. and operators present in the Visual Basic language before using them in your own VBA procedures. The Immediate window is used for trying out various instructions. click the Close button in the top right-hand corner of the window. The Immediate window can be moved anywhere on the Visual Basic Editor screen or it can be docked so that it always appears in the same area of the screen. Hands-On 3. Arrange the screen so that both the Microsoft Excel window and the Visual Basic window are placed side by side as presented in Figure 3. To close the Immediate window. If the statement produces the expected result. The docking setting can be turned on and off on the Docking tab in the Options dialog box (Tools | Options).9. How can you do this quickly and painlessly? How can you try out some of the newly learned VBA statements? Here is a short. Entering and Executing VBA Statements in the Immediate Window 1.USING THE IMMEDIATE WINDOW Before you start creating full-fledged VBA procedures (this awaits you in the next chapter!). . In the Visual Basic Editor window. simply press Ctrl+G while in the Visual Basic Editor screen. choose View | Immediate Window.21. begin with some warm-up exercises to build up your VBA vocabulary. Use it to try out your statements. The Immediate window allows you to type VBA statements and test their results immediately without having to write a procedure. To quickly access the Immediate window. functions. The Immediate window is like a scratch pad. Let’s begin by setting up your exercise screen. It is a great tool for experimenting with your new language. 2. you can copy the statement from the Immediate window into your procedure (or you can drag it right onto the Code window if it is visible).

In the Immediate window. 3. type another VBA statement and be sure to press Enter when you’re done: Range("A1:A4"). A2.Activate When you press the Enter key. Visual Basic gets to work. Enter the following instruction in the Immediate window: . and A4 in the active worksheet. 5. The Sheet2 tab at the bottom of the workbook should now be highlighted. 4. type the following instruction and press Enter: Worksheets("Sheet2"). A3. Visual Basic highlights the cells A1.Figure 3.21. VBA activates a second sheet in the current workbook.Select As soon as you press Enter. By positioning the Microsoft Excel and Visual Basic windows side by side you can watch the execution of the instructions entered in the Immediate window. If you entered the above VBA statement correctly. In the Immediate window.

Visual Basic places the number 55 in every cell of the specified range. This statement is an abbreviated way of referring to the Range object. Enter the following instruction in the Immediate window: ActiveCell. Excel executed the statement on the line where the cursor was located.ClearContents When you press Enter. Cells A1:A4 are now empty. If you want to execute the same instruction again. Every time you pressed the Enter key. 7.22 shows all the instructions entered in the Immediate window in this exercise.Value = 55 When you press Enter. click anywhere in the line containing the instruction and press Enter. A1:A4. VBA deletes the results of the previous statement from the selected cells. The full syntax is more readable: Range("A1:A4"). Figure 3.Value = 55 6.Select When you press Enter. .[A1:A4]. Enter the following instruction in the Immediate window: Selection. Visual Basic makes cell A1 active.

These actions could have been performed manually by clicking the mouse in various areas of the worksheet and entering data. For more practice you may want to rerun the statements shown in Figure 3. Note that the contents of the Immediate window are automatically deleted when you exit Microsoft Excel. When working in the Immediate window. the name of the active sheet. Excel remembers the instructions entered in the Immediate window even after you close this window. Suppose you want to find out which cells are currently selected. Start from the instruction displayed in the second line of the Immediate window. the Immediate window also allows you to ask questions. you entered several instructions. Instead of simply performing actions. Let’s return to the Immediate window to ask some questions. Hands-On 3. Obtaining Information in the Immediate Window So far you have used the Immediate window to perform actions. Execute the instructions one by one by clicking in the appropriate line and pressing the Enter key. you can easily get answers to these and other questions. the value of the active cell. Obtaining Information in the Immediate Window .22. Instructions entered in the Immediate window are executed as soon as you press the Enter key. In the preceding exercise.Figure 3.10. or the number of the current window.22.

3. Excel returns the absolute address of the cells that are currently selected ($A$1:$A$4). How about finding the name of the application? 5.1.Address When you press Enter. Press Enter to have Excel reselect cells A1:A4. as shown in the next step. and press Enter: ?Selection. 2. you can use the Print keyword.Name Excel will reveal its full name: Microsoft Excel. enter the following question. it will display the result of the instruction on a separate line in the Immediate window. Click in the new line of the Immediate window. The question mark (?) in the above statement tells Excel to display the result of the instruction in the Immediate window. Instead. Excel will not select anything in the worksheet. Instead of the question mark.Select. . In this case. In a new line in the Immediate window. enter the following statement and press Enter: Print ActiveWorkbook.Name Excel enters the name of the active workbook on a new line in the Immediate window. Click the mouse in the second line of the Immediate window where you previously entered the instruction Range(“A1:A4”). enter the following statement and press Enter: ?Application. In a new line in the Immediate window. 4.

Select [A1:A4]. you can enter them on one line. 96 on separate lines in the Immediate window. When you press the Enter key. 6. as in the following example: ?3+2:?12*8 Notice the colon separating the two blocks of instructions.ClearContents ActiveCell.Value = 55 Selection. The following lists all the instructions you entered in the Immediate window including Excel’s answers to your questions: Worksheets("Sheet2").The Immediate window can also be used for a quick calculation.Select ?Selection.Activate Range("A1:A4").Address $A$1:$A$4 Print ActiveWorkbook. But what if you want to know right away the result of 3+2 and 12*8? Instead of entering these instructions on separate lines. enter the following statement and press Enter: ?12/3 Excel shows the result of the division on the next line. Excel displays the results 5.Name Book2 ?Application.Name Microsoft Excel . In a new line in the Immediate window.

?12/3 4 ?3+2:?12*8 5 96 To delete the instructions from the Immediate window. Window (Windows). copy. properties. how to format cells. LEARNING ABOUT OBJECTS Creating custom applications in Excel requires a working knowledge of common objects or collections of objects such as Range. press Ctrl+A to highlight all the lines and then press Delete. activate the Immediate window. Worksheet (Worksheets). mastering these techniques in Visual Basic for Applications requires a little . and how to move. If you want to experiment with VBA and see the results of the VBA commands immediately. In preceding sections. Here’s a summary of when to use a specific tool: When in doubt about objects. you will most likely begin searching for instructions that allow you to manipulate worksheet cells. To help you better understand the VBA syntax. You will need to know how to select cells. or methods in an existing VBA procedure. the remaining pages of this chapter contain a number of VBA language drills. how to enter data in cells. You will get the most out of these drills if you take the time to work through them in the Immediate window. Although these tasks can be easily performed with the mouse or keyboard. If you need a quick listing of properties and methods for every available object or have trouble locating a hard-to-find procedure. fire up the online help by pressing F1. you explored several methods of learning about Visual Basic. and Application. go with the Object Browser. WORKING WITH WORKSHEET CELLS When you are ready to write your own VBA procedure to automate a particular spreadsheet task. and delete cells. how to assign range names. Workbook (Workbooks).

Using the Range Property The Range property returns a cell or a range of cells. Hands-On 3. “A5”. The reference can include the range operator. Let’s try out a couple of statements in Hands-On 3. Practice Using the Range Property to Select Worksheet Cells Using the Cells Property You can use the Cells property to return a single cell. “A1”). There are three properties that allow you to access the Range object: the Range property.12. Arguments are entered in parentheses. When you omit arguments. When selecting a single cell. this property requires two arguments. The first argument indicates the row number and the second one is the column number. which is a comma (for example. The reference to the range must be in an A1-style and in quotation marks (for example. Hands-On 3. a range of cells.practice. and the Offset property. which is a colon (for example. or the union operator.12. “A1:B2”). Excel selects all the cells in the active worksheet. “B12”). Practice Using the Cells Property to Select Worksheet Cells (Part I) . or a column. the Cells property. a row. You must use the Range object to refer to a single cell.11.

Excel will select the range of cells where the top cell is specified by the result of the first Cells property and the bottom cell is defined by the result of the second Cells property. The cells returned by the Cells properties are then used as a reference for the Range object. cell C1 is the third one.Notice how you can combine the Range property and the Cells property: Range(Cells(6. 1). and so on.Select In the above example. A worksheet is a collection of cells. cell B1 is the second one. Hands-On 3. while the second one returns cell A10. Practice Using the Cells Property to Select Worksheet Cells (Part II) . the first Cells property returns cell A6. Cell 16384 is the last cell in the first worksheet row. Now let’s write some practice statements in Hands-On 3. Excel numbers the cells in the following way: Cell A1 is the first cell in a worksheet. Cells(10.12.12. You can also use the Cells property with a single argument that identifies a cell’s position in the collection of a worksheet’s cells. As a result. 1)).

You can also shift the selection to the right or left a specified number of columns. Let’s try out some examples in Hands-On 3. Now that you’ve discovered two ways to select cells (Range property and Cells property). How can you select a cell whose address you don’t know? The answer: Have Excel select a cell based on an existing selection. you used the Range references in Excel formulas and functions long before you decided to learn about VBA. Using the Cells property is more convenient. you may not know exactly where a specific cell is located. Quite often when automating worksheet tasks. In calculating the position of a new range.13. however. when it comes to working with cells as a collection. after all. Using the Offset Property Another very flexible way to refer to a worksheet cell is with the Offset property. . you may wonder why you should bother using the more complicated Cells property. the Offset property uses two arguments. The first argument indicates the row offset and the second one is the column offset. you can refer to a worksheet cell without explicitly using the Item property.Notice that the word Item is a property that returns a single member of a collection. Use this property to access all the cells or a single cell from a collection. Because Item is the default member for a collection. It’s quite obvious that the Range property is more readable. The Offset property calculates a new range by shifting the starting selection down or up a specified number of rows.

Excel selects cell D2. you may occasionally need to change the size of a selection of cells. When working with the Offset property. you can rewrite the first two statements in the following way: Selection. .Select Notice that the third example in the practice table above displays zero (0) in the position of the second argument. The second part requires another property.Select will cause an error if the active cell is located in the first row.13. Before you combine these two properties. -1).Select Selection. Selecting Cells Using the Offset Property In the first example above. let’s proceed to Hands-On 3. The instruction ActiveCell. You can combine the Offset property with the Resize property to answer the above question. Excel chooses cell C13.Offset(1.Offset(-2. As soon as you enter the second example. Excel has a special Resize property. 3). How about shifting the selection two rows down and two columns to the right and then changing the size of the new selection? Let’s say the new selection should highlight cells C7:C8.Hands-On 3. 0). Suppose that the starting selection is A5:A10. Zero entered as a first or second argument of the Offset property indicates a current row or column. The Offset property can only take care of the first part of this task.Offset(–1.14 to learn how you can use them separately. If cells A1 and D15 are already selected.

14. 4). cells C7:F8 are selected. The second instruction shifts the current selection to cells C7:C12. Activate the Immediate window and enter the following instructions: Range("A5:A10"). Recording a Selection of Cells By default.Select The first instruction selects range A5:A10. Like the Offset property.Hands-On 3.Select Selection. If you turn . the instruction Selection. and the second argument specifies the number of columns.Offset(2. 2).Resize(2. The first argument is the number of rows you intend to include in the selection.Resize(2. 4). 2. Cell A5 is the active cell. the Resize property determines the new size of the range. Instead of range C7:C12. 4).Resize(2.Select In this statement. Cell C7 is located two rows below the active cell A5 and two columns to the right of A5. and the Select method selects the specified range of cells. Arrange the screen so that the Microsoft Excel window and the Visual Basic window are side by side. Writing a VBA Statement to Resize a Selection of Cells 1. The last two instructions can be combined in the following way: Selection. the Resize property takes two arguments. Hence.Select resizes the current selection to two rows and four columns. Now the active cell is C7. 2).Select Selection. The last instruction resizes the current selection. the macro recorder selects cells using the Range property.Offset(2. the Offset property calculates the beginning of a new range.

Select ActiveCell. 0). To do this. The first and third lines in this set of instructions reference cell A1. enter any text.Select You can have the macro recorder use the Offset property if you tell it to use relative references.Select ActiveCell. make sure Use Relative References is not selected if your next macro does not require the use of relative addressing.FormulaR1C1 = "text" ActiveCell.Range("A1"). 0). you may already be familiar with the following keyboard shortcuts: End-up arrow. the macro recorder has its own way of getting things done. OTHER METHODS OF SELECTING CELLS If you often have to quickly access certain remote cells in your worksheet.Offset(3. you can delete the reference to Range(“A1”): ActiveCell. and select cell A5.FormulaR1C1 = "text" ActiveCell. click View | Macros | Use Relative References. 0).Select ActiveCell.Offset(3. As you remember from Chapter 1. 0).Select When you record a procedure using the relative references. you will see the following lines of code in the Visual Basic Editor window: Range("A2"). The macro recorder produces the following lines of code: ActiveCell.Offset(-1. the procedure will always select a cell relative to the active cell. even though nothing was said about cell A1.Select After recording a procedure using the relative reference.FormulaR1C1 = "text" Range("A5"). To make the above instructions less complex.Offset(-1. and then choose Record Macro. End-down .Range("A1").on the macro recorder and select cell A2.

xlUp. and End-right arrow. Hands-On 3. you can use the End property to quickly move to remote cells. In VBA.16.arrow. End-left arrow. Selecting Entire Rows and Columns When you select a range of cells you may want to find out how many rows or columns are included in the selection. Let’s move around the worksheet by writing statements listed in Hands-On 3.15. Hands-On 3.16 to quickly select entire rows and columns. Use the following Excel built-in Direction Enumeration constants to jump in the specified direction: xlToRight.15. xlToLeft. Selecting Cells Using the End Property Notice that the End property requires an argument that indicates the direction you want to move. Let’s now write the statements in Hands-On 3. Let’s have Excel count rows and columns in . xlDown. Selecting Rows and Columns Excel uses the EntireRow and EntireColumn properties to select the entire row or column.

Visual Basic tells you that the selected Range(“A1:D15”) occupies the width of four columns.Count As soon as you press Enter.Count As soon as you press Enter. Type the following VBA statement in the Immediate window and press Enter: Range("A1:D15").17. 1.Range(“A1:D15”). To find out the number of columns in the selected range. Visual Basic will highlight the range A1:D15 when you press Enter. 2. In the Immediate window.Select If the Microsoft Excel window is visible. use the Count property as shown in Hands-On 3.Columns. Visual Basic displays the answer on the next line. 4. . enter the following statement: ?Selection. position the cursor anywhere within the word Rows or Columns and press F1 to find out more information about these useful properties. enter the following statement: ?Selection. To find out how many rows are in the selected range. Your selection includes 15 rows. 3.Rows. Obtaining Information about the Worksheet How big is an Excel worksheet? How many columns and rows does it contain? If you ever forget the details.

Using the Value property: ActiveSheet.Hands-On 3.18.17. Entering Data in a Worksheet The information entered in a worksheet can be text.576 rows and 16.Formula = "=4 * 25" In both examples shown above. Counting Rows and Columns A Microsoft Excel 2013 worksheet has 1.18. you can use either the Value property or the Formula property of the Range object. To enter data in a cell or range of cells.048.Range("A1:C4").Value = "=4 * 25" Using the Formula property: ActiveSheet. Using VBA Statements to Enter Data in a Worksheet . Let’s proceed to some practice in Hands-On 3. cells A1:C4 display 100—the result of the multiplication 4 * 25. or formulas.Range("A1:C4").384 columns. Hands-On 3. numbers.

Returning Information Entered in a Worksheet In some Visual Basic procedures you will undoubtedly need to return the contents of a cell or a range of cells. Although you can use either the Value or Formula property.Value will return the value of 100. you must use the Formula property: ?Range("A1"). this time the two Range object’s properties are not interchangeable. then the instruction ?Range("A1").Formula Excel will display the formula (= 4 * 25) instead of its result (100). for example. Your VBA procedure may need to find out the type of formatting applied to a . If. cell A1 contains a formula = 4 * 25. Finding Out about Cell Formatting A frequent spreadsheet task is applying formatting to a selected cell or a range. The Value property displays the result of a formula entered in a specified cell. If you want to display the formula instead of its result.

NumberFormat = "$#.” which indicates that no special formatting was applied to the selected cell. You can look up the available format codes in the Format Cells dialog box in the Microsoft Excel application window as shown in Figure 3.NumberFormat Upon entering the above statement in the Immediate window. enter the following instruction: Range("A1"). Excel displays the word “General. use the NumberFormat property: ?Range("A1"). cell A1 will display $125. . To change the format of a cell to dollars and cents using VBA.00" If you enter 125 in cell A1 after it has been formatted with the above VBA instruction.00.23.##0.particular worksheet cell. To retrieve the cell formatting.

press the Alt.23. To quickly bring up this dialog box. Moving. Visual Basic allows you to automate these worksheet editing tasks with three simple-to-use methods: Cut.Figure 3. and Deleting Cells In the process of developing a new worksheet model. F. you often find yourself moving and copying cells and deleting cell contents. H. and M keys one at a time. You can apply different formatting to selected cells and ranges using format codes. and Clear. refer to the online help for guidelines on creating user-defined formats. And now let’s do some hands-on exercises to get some practice in the most . If the format you want to apply is not listed in the Format Cells dialog box. Copying. Copy. as displayed in the Custom category in the Format Cells dialog box.

In the last example. This argument specifies the address of a cell or a range of cells where you want to place the cut or copied data. If you want to be specific about what you delete. use the following methods: ClearContents—Clears ClearFormats—Clears only applied formats ClearComments—Clears ClearNotes—Clears only data from a cell or range of cells all cell comments from the specified range notes and sound notes from all the cells in the specified range ClearHyperlinks—Removes ClearOutline—Clears all hyperlinks from the specified range the outline for the specified range WORKING WITH WORKBOOKS AND WORKSHEETS . and Deleting Cells Notice that the first two methods in the table require a special argument called Destination.frequently used worksheet operations. The Clear method deletes everything from the specified cell or range. Moving. the Cut method is used without the Destination argument to remove data from the specified cell. including any applied formats and cell comments. Hands-On 3. Copying.19.

You cannot work with an existing workbook if you don’t know how to open it. make sure you have opened a new workbook.21 will give you the language skills necessary for dealing with workbooks and worksheets.Now that you’ve got your feet wet working with worksheet cells and ranges. all workbooks are now closed. You cannot prepare a new spreadsheet if you don’t know how to open a new workbook.20 and 3. Working with Workbooks If you worked through the last example in Hands-On 3-20. you must know how to add a new . it’s time to move up one level and learn how you can control a single workbook. Hands-On 3.20. Open. These important tasks are handled by the following VBA methods: Add. When you deal with individual worksheets. Before you experiment with worksheets. and Close. The next series of drills in Hands-On 3. as well as an entire collection of workbooks. You cannot remove a workbook from the screen if you don’t know how to close a workbook.

and copy. Working with Worksheets Notice the difference between the Select and Activate methods: The Select and Activate methods can be used interchangeably if only one worksheet is selected. Sheets Other than Worksheets In addition to worksheets. only one worksheet can be active at a time. move. In Visual Basic.21. To add a new chart sheet to your workbook. name a worksheet. Hands-On 3.worksheet to a workbook. As you know. and delete worksheets. the Activate method allows you to decide which one of the selected worksheets is active. each of these tasks is handled by a special method or property. the collection of workbooks contains chart sheets. If you select a group of worksheets. use the Add method: . select a worksheet or a group of worksheets.

Hands-On 3.1.1 Arguments of the Arrange method of the Windows object .22 you will learn how you can arrange your screen with Visual Basic for Applications. The argument that allows you to control the way the windows are positioned on your screen is called ArrangeStyle. all windows are tiled.Count WORKING WITH WINDOWS When you work with several Excel workbooks and need to compare or consolidate data or when you want to see different parts of the same worksheet.Add To count the chart sheets. you are bound to use the options available from the Microsoft Excel Window menu: New Window and Arrange.22. In Hands-On 3. use: ?Charts. If you omit the ArrangeStyle argument. Working with Windows When you display windows on screen. Table 3.Charts. The Arrange method has many arguments as shown in Table 3. you can decide how to arrange them.

1.Instead of the names of constants. As you know. The Application object represents the Excel application itself. Excel allows you to save the screen settings by using the Save Workspace button on the View tab. you learned that objects are organized in a special structure called the object model.SaveWorkspace "Project" The above instruction saves the screen settings in the workspace file named Project.Arrange ArrangeStyle:=xlArrangeStyleCascade Or simply: Windows. To cascade all windows. such as saving the way your screen looks at the end of a day’s work or quitting the application. you can use the value equivalents shown in Table 3. By controlling the Application object. use the following VBA instruction: Windows. you can perform many tasks.Arrange ArrangeStyle:=7 MANAGING THE EXCEL APPLICATION At the beginning of this chapter. The next time you need to work with the same files and arrangement of . The task of saving the workspace can be easily performed with VBA: Application.

23. You got answers to questions such as “How many worksheets are in the active workbook?” or “What are the contents of cell A4?” Excel did not mind any of your . and Excel will bring up the correct files and restore your screen with those settings.xlwx file. Working with the Excel Application CHAPTER SUMMARY In this chapter. Visual Basic procedures usually contain more than one line of code. For this reason. And now let’s write some statements that use the Application object. you learned many basic VBA terms and how to use some built-in tools that make it easier to write and troubleshoot VBA statements.windows. In fact. you learned how to question Excel for the vital information. simply open the Project. Hands-On 3. you still need to learn a couple of things. Before you can start creating complete VBA procedures. You should now have a good idea of how the most common Microsoft Excel objects are organized and controlled. they can become quite complex. how can you save information returned by Excel so that your procedures can use it later? While entering instructions in the Immediate window. For example. This chapter focused on teaching you how to use these new language skills to gain control over Microsoft Excel immediately without writing complete VBA procedures. we focused on the Immediate window.

“nosy” questions. you will need to know how to save Excel answers. In the next chapter. As long as you phrased your question by following the strict VBA syntax rules. Excel gave you the answer. you will learn how to save this kind of information for later use by using variables. You will also explore data types and constants. . When you start writing your own procedures.

Because your procedures will handle different kinds of information. you should understand how Visual Basic stores data. SAVING RESULTS OF VBA STATEMENTS In Chapter 3. how variables are declared. when you write Visual Basic procedures outside of the Immediate window. you have a purpose in mind: You want to manipulate data.048. When you omit the question mark and enter Rows. you can’t use the question mark. When you delegate the task or finally get around to doing it yourself. Visual Basic won’t stop suddenly to tell you the result of this instruction. This chapter shows you how your VBA procedures can memorize important pieces of information for use in later statements or calculations. you must tell Visual Basic to memorize it.Chapter 4 Using Variables. certain things need to be done at once while others can be put off until later.Count. Data Types. You will learn how a procedure can keep a “to-do” entry in a variable. when you entered ? Rows. results returned by Visual Basic instructions can be written to variables. just as in life. while working in the Immediate window. The data type determines how the data is stored in the computer’s memory. and Constants In programming. For example. When you postpone a task.576 rows in a worksheet. However. you tried several Visual Basic instructions that returned some information. In programming. data can be . DATA TYPES When you create Visual Basic procedures. For example.Count in your procedure. you cross it off the list. you may enter it in your mental or paper “to-do” listand classify it by its type or importance. If you want to know the result after executing a particular instruction. you found out that there are 1. and how they relate to data types and constants.

etc. is capable of handling the data that your procedure has to manipulate.6 and “Understanding the Type Statement”). text. The Visual Basic data types are shown in Table 4. date.1. You will see an example of a userdefined data type in Chapter 14. In addition to the built-in data types. Table 4. “Using Low-Level File Access” (see Hands-On 14. some of them are more expensive than others. it assigns the Variant data type. If you forget to tell Visual Basic the type of your data. to conserve memory and make your procedure run faster. VBA data types . at the same time. The Variant type has the ability to figure out on its own what kind of data is being manipulated and then take on that type. you should select the data type that uses the least amount of bytes and. you can define your own data types. object.1. Therefore.stored as a number. Because data types take up different amounts of space in the computer’s memory.

.

it’s best to use short and simple variable names. When the variable names are comprised of one or more words. strName) can be quickly recognized within the code of your procedure as the one holding the text string.048. you can make up a name such as AllRows. and some punctuation marks. Using short names will save you typing time when you need to refer to the variable in your Visual Basic procedure. Len.576 has to remind you of the total number of rows in a worksheet (a very important piece of information when you want to bring external data into Excel 2013). Visual Basic doesn’t care whether you use uppercase or lowercase letters in variable names. but most programmers use lowercase letters. use the underscore (_) as a separator. The names of variables can contain characters. NumOfRows. or TotalRows. Some programmers use a prefix to identify the type of a variable. Local. For example. Each time you want to remember a result of a VBA instruction. Currency. think of a name that will represent it. or Exit will generate an error message if used as a variable name. numbers. they use title case. If you want the name of the variable to include more than one word. Reserved Words Can’t Be Used for Variable Names You can use any label you want for a variable name. A variable name that begins with"str” (for example. except for the reserved words that VBA uses. . For example. Empty. except for the following: . Visual Basic statements and certain other words that have a special meaning in VBA cannot be used as names of variables. Meaningful Variable Names Give variables names that can help you remember their roles.WHAT ARE VARIABLES? A variable is simply a name that is used to refer to an item of data. if the number 1. as in the names NumOfRows and First_Name. and so on. # $ % & @ ! The name of a variable cannot begin with a number or contain a space. words such as Name. Although the name of a variable can contain as many as 254 characters.

Explicit variable declaration helps prevent errors caused by misspelled variable names. Although implicit variable declaration is convenient (it allows you to create variables on the fly and assign values without knowing in advance the data type of the values being assigned). Variables declared implicitly are automatically assigned the Variant data type shown in Table 4. If you don’t let Visual Basic know about the variable prior to using it. Because Visual Basic does not know what type of data your variable will store. This is called explicit variable declaration. it reserves only as much memory as is absolutely necessary to store the data.1. Because Visual Basic knows the data type. How to Declare Variables . Visual Basic may display a runtime error or create a new variable. Explicit variable declaration makes your code easier to read and understand because all the variables are listed at the very beginning of the procedure. When you declare your variable. Visual Basic has to reserve more memory to store your data. Because a Variant can store any type of data. Visual Basic automatically corrects the variable name based on the spelling used in the variable declaration. it assigns it a Variant data type. it can cause several problems.How to Create Variables You can create a variable by declaring it with a special command or by just using it in a statement. There are several advantages to explicit variable declaration: Explicit variable declaration speeds up the execution of your procedure. You are guaranteed to waste some time troubleshooting problems that could have been easily avoided had you declared your variable at the beginning of the procedure. you make Visual Basic aware of the variable’s name and data type. This causes your procedure to run slower because Visual Basic has to check the data type every time it deals with your variable. you are implicitly telling VBA that you want to create this variable. as outlined below: If you misspell a variable name in your procedure.

Dim stands for dimension. so you declare another variable to hold the employee’s first and last name: Dim FullName As String Because the word “Name” is on the VBA list of reserved words. you must tell the procedure the employee’s date of birth. To do this. you declare a variable called DateOfBirth. this variable has been assigned the Integer data type. as long as it is not one of the VBA keywords. Declaring variables is regarded as a good programming practice because it makes programs easier to read and helps prevent certain types of errors. Because age is displayed as a whole number. as follows: Dim DateOfBirth As Date Notice that the Dim keyword is followed by the name of the variable (DateOfBirth). The Date data type tells Visual Basic that the variable DateOfBirth will store a date. This name can be anything you choose. To hold the employee’s full name. The Dim keyword is followed by the name of the variable and then the variable type.You declare a variable with the Dim keyword. followed by one of the data types from Table 4. because the data it will hold is text. Informal Variables Variables that are not explicitly declared with Dim statements are said to be implicitly declared. To store the employee’s age.1. You may also want your procedure to keep track of the employee’s name. Specify the data type the variable will hold by placing the As keyword after its name. Suppose you want the procedure to display the age of an employee. These variables are automatically assigned a data type called . using it in your VBA procedure would guarantee an error. call the variable FullName and declare it as the String data type. declare the age variable as follows: Dim age As Integer The age variable will store the number of years between today’s date and the employee’s date of birth. Before you can calculate the age.

For example." End Sub The variables are declared at the beginning of the procedure in which they are going to be used.Variant. They can hold numbers. age As Integer Notice that the Dim keyword appears only once at the beginning of the variable declaration line. let’s take a look at a procedure that uses them: Sub AgeCalc() ' variable declaration Dim FullName As String Dim DateOfBirth As Date Dim age As Integer ' assign values to variables FullName = "John Smith" DateOfBirth = #01/03/1967# ' calculate age age = Year(Now())-Year(DateOfBirth) ' print results to the Immediate window Debug. If you want. DateOfBirth As Date.Print FullName &" is" & age &" years old. as shown here: Dim FullName As String. and other types of information. . the variables are declared on separate lines. You can create a variable by simply assigning some value to a variable name anywhere in your VBA procedure. you can declare several variables on the same line. strings. In this procedure. you will implicitly declare a variable in the following way: DaysLeft = 100 Now that you know how to declare your variables. separating each variable name with a comma.

Count statement to the variable NumOfRows. you should choose a data type that can accommodate a larger number: Sub HowManyRows2() Dim NumOfRows As Long NumOfRows = Rows.Print. Then the full name of the employee as well as the age is printed to the Immediate window using the instruction Debug. when Visual Basic attempts to write the result of the Rows. it creates the variables with the specified names and reserves memory space to store their values.” This error results from selecting an invalid data type for that variable. To assign a value to a variable. you must view the Immediate window to see the results. Let’s see what happens when you declare a variable with the incorrect data type." End Sub A wrong data type can cause an error. To correct the problem. Using the data supplied by the DateOfBirth variable. When the Visual Basic procedure has executed. Text data should be surrounded by quotation marks. The data you enter here must be of the type determined by the variable declaration. the procedure fails and Excel displays the message"Run-time error 6— Overflow. Visual Basic calculates the age of an employee and stores the result of the calculation in the age variable. Sub HowManyRows() Dim NumOfRows As Integer NumOfRows = Rows.Count MsgBox"The worksheet has" & NumOfRows &" rows.Count .When Visual Basic executes the variable declaration statements. The purpose of the following procedure is to calculate the total number of rows in a worksheet and then display the results in a dialog box. Then specific values are assigned to these variables. and dates by the # characters. In the procedure above. begin with a variable name followed by an equals sign. The value entered to the right of the equals sign is the data you want to store in the variable. The number of rows in a spreadsheet does not fit the Integer data range.

Concatenation You can combine two or more strings to form a new string. Integer variables . What Is the Variable Type? You can quickly find out the type of a variable used in your procedure by rightclicking the variable name and selecting Quick Info from the shortcut menu. It’s highly recommended that you create typed variables. Specifying the Data Type of a Variable If you don’t specify the variable’s data type in the Dim statement. You have seen examples of concatenated strings in the AgeCalc and HowManyRows2 procedures above. Visual Basic will assign to your variable the Variant data type. When you declare a variable of a certain data type." End Sub You can also correct the problem caused by the assignment of the wrong data type in the first example above by deleting the variable type (As Integer). When you rerun the procedure. Visual Basic can work with many types of numeric variables. However. the cost of using Variants is barely noticeable. Concatenation is represented by an ampersand character (&). For instance. Notice that there is an extra space between “is” and the ending quote: “His name is. “His name is" & FirstName will produce the following string: His name is John. you end up with an untyped variable. The name of the person is determined by the contents of the FirstName variable. Although Variants use up more memory than any other variable type and also slow down the speed at which your procedures run (because Visual Basic has to do extra work to check the Variant’s context).” Concatenation of strings also can be represented by a plus sign (+). many programmers prefer to restrict the plus sign to operations on numbers to eliminate ambiguity. The joining operation is called concatenation. your VBA procedure runs faster because Visual Basic does not have to stop to analyze the Variant variable to determine its type. when it comes to short procedures.MsgBox "The worksheet has" & NumOfRows &" rows. Untyped variables in VBA are always Variant data types.

you can only store the type of information in it that you determined in the declaration statement. if your variable was declared to hold whole numbers and your data uses decimals. you can tell Visual Basic how long the string should be. After you declare a variable. To declare the FirstName variable as String. the String variable will be dynamic. Unlike the Integer and Long variables. and instead of 23.647. When you declare a variable of String data type. Assigning string values to numeric variables or numeric values to string variables results in the error message “Type mismatch” or causes Visual Basic to modify the value. When you run the MyNumber procedure shown below. Sub MyNumber() Dim myNum As Integer myNum = 23.147. This means that Visual Basic will make enough space in computer memory to handle whatever amount of text is assigned to it. For example.147. Long variables can hold whole numbers in the range –2.11 MsgBox myNum End Sub If you don’t declare a variable with a Dim statement. you can append the dollar sign to the variable name: Dim FirstName$ . Double. For instance: Dim extension As String * 3 declares a fixed-length String variable named extension that is three characters long.768 to 32. the Single and Double variables can hold decimals.483. Single. If you don’t assign a specific length. and Currency. Visual Basic modifies the data to fit the variable’s data type (Integer).648 to 2.11 the variable ends up holding a value of 23. String variables are used to refer to text.483.767. Other types of numeric variables are Long. Visual Basic will disregard the decimals and use only the whole part of the number. you can still designate a type for it by using a special character at the end of the variable name.can only hold whole numbers from –32.

Type declaration characters Notice that the type declaration characters can only be used with six data types. Table 4. The type declaration characters are shown in Table 4. Sub AgeCalc2() ' variable declaration Dim FullName$ Dim DateOfBirth As Date Dim age% ' assign values to variables FullName$ = "John Smith" DateOfBirth = #1/3/1967# ' calculate age age% = Year(Now()) . In the AgeCalc2 procedure below we use two type declaration characters shown in Table 4.This declaration is the same as Dim FirstName As String.Year(DateOfBirth) ' print results to the Immediate window Debug. append the character to the end of the variable name.2." .Print FullName$ &" is" & age% &" years old.2. To use the type declaration character.2.

If you don’t add the type symbol or the As command. In the Properties window. 4. Activate the Visual Basic Editor window. enter the CalcCost procedure shown below: . let’s gain experience using them. Open a new workbook and C:\Excel2013_ByExample\Practice_Excel04. select the new project and change the name of the project in the Properties window to Chapter4. a new module to the Chapter4 5.xlsm. the variable will be the default data type Variant. In the Project Explorer window. 6.1. Please note files for the “Hands-On” project may be found on the companion CD-ROM. Writing a VBA Procedure with Variables 1.End Sub Declaring Typed Variables The variable type can be indicated by the As keyword or a type symbol. In the Code window. In Hands-On 4. change the name of Module1 to Variables. C ho o s e Insert | Module to add (Practice_Excel04. Assigning Values to Variables Now that you know how to name and declare variables and have seen examples of using variables in complete procedures.1 we will begin by creating a variable and assigning it a specific value. 3. Hands-On 4. save it as 2.xlsm) VBA project.

This can be a number." Range("A8"). you should enter the value of the variable. .Formula = "Price" Range("B4"). After the equals sign. The cost calculation uses the values supplied by the slsPrice and slsTax variables.Sub CalcCost() slsPrice = 35 slsTax = 0.NumberFormat = "0.5%.Formula = "The cost of calculator" Range("A4"). slsTax.Formula = slsPrice Range("A5").Formula = strMsg End Sub The above procedure calculates the cost of purchasing a calculator using the following assumptions: The price of a calculator is 35 dollars and the sales tax equals 8. The variables slsPrice and slsTax were created by assigning some values to variable names at the beginning of the procedure. The cost variable was assigned a value that is a result of a calculation: slsPrice + (slsPrice * slsTax). and strMsg. they all have the same data type—Variant.085 Range("A1"). When you assign values to variables. place an equals sign after the name of the variable. This message is then entered as a complete sentence in a worksheet cell.Formula = slsPrice * slsTax cost = slsPrice + (slsPrice * slsTax) With Range("B6") . a formula.Formula = cost . Because none of these variables have been explicitly declared. The procedure uses four variables: slsPrice. cost.Formula = "Sales Tax" Range("A6"). The strMsg variable puts together a text message to the user.00" End With strMsg = "The calculator total is $" & cost &".Formula = "Cost" Range("B5").

slsTax. The & character attaches yet another string. When you run this procedure. Let’s examine the contents of the strMsg variable. strMsg = "The calculator total is $" & cost &". and cost are easily understood. String variables are set to the empty string (“”). When you require a period at the end of a sentence.” If this happens. The & character must be used every time you want to append a new piece of information to the previous string. click OK to close the message box. The & character allows another string or the contents of a variable to be appended to the string. Visual Basic may display the following message: “Compile error: Variable not defined. the value stored in the strMsg variable is a little more involved. Notice that there is an extra space before the ending quotation marks. Variables assume their default value. Position the cursor anywhere within the CalcCost procedure and choose Run | Run Sub/UserForm. 7. 1899. Variable Initialization When Visual Basic creates a new variable. The cost variable is a placeholder. Numerical variables are set to zero (0).or text surrounded by quotation marks. The actual cost of the calculator will be displayed here when the procedure runs. While the values assigned to the variables slsPrice." The string “The calculator total is" is surrounded by quotation marks. you must attach it separately when it follows the name of the variable. The dollar sign inside the quotes is used to denote the Currency data type. it is surrounded by the quotes. Now let’s execute the CalcCost procedure. The period is surrounded by quotes. Because the dollar symbol is a character. Boolean variables are initialized to False. it initializes the variable. Visual Basic will select the slsPrice variable and highlight the . and Date variables are set to December 30.

Visual Basic goes to work with no objections. For now. you will learn how to fix problems in break mode. exit this mode by choosing Run | Reset. The VBA procedure can enter data and calculate results in a worksheet. Later in this book.name of the CalcCost procedure. 8.1. while the cost in strMsg displays three decimals. After the procedure has finished executing. you must apply the required format not to the cell but to the cost variable itself. To change . VBA has special functions that allow you to change the format of data. Now go to the top of the Code window and delete the statement Option Explicit that appears on the first line. press Alt+F11to switch to Microsoft Excel. Cell A8 displays the contents of the strMsg variable. The title bar displays"Microsoft Visual Basic – Practice_Excel04. The Option Explicit statement means that all variables used within this module must be formally declared. You will learn about this statement in the next section. To display the cost of a calculator with two decimal places in cell A8. choose Run | Run Sub/UserForm to rerun the procedure.1.” The Visual Basic break mode allows you to correct the problem before you continue. When the Option Explicit statement is removed from the Code window. Notice that the cost entered in cell B6 has two decimal places. The result of the procedure should match Figure 4. This time.xlsm [break]. FIGURE 4.

00") 10. you may wonder why you should bother declaring variables if Visual Basic can handle undeclared variables so well.Formula = cost 11. 9. What will happen if the second time you use the cost variable you omit the “o” and refer to it as cst? Range("B6")."0."0.Formula slsTax with the following instruction: = slsPrice * Range("B5"). This function has the following syntax: Format(expression. After trying out the CalcCost procedure. . In short procedures. however. Replace the statement Range("B5").00") 12. The CalcCost procedure is very short.00") The result of the CalcCost procedure after introducing these two mistakes is shown in Figure 4. Change the calculation of the cost variable in the CalcCost procedure: cost = Format(slsPrice + (slsPrice * slsTax).2.the format of the cost variable. Notice that now the text displayed in cell A8 shows the cost of the calculator formatted with two decimal places."0. so you don’t need to worry about how many bytes of memory will be consumed each time Visual Basic uses the Variant variable.Formula = cst What will you end up with if instead of slsTax you use the word Tax in the formula? Cost = Format(slsPrice + (slsPrice * Tax).Formula = Format((slsPrice * slsTax). Rerun the modified procedure. format) where expression is a value or variable that you want to format and format is the type of format you want to apply. it is not the memory that matters but the mistakes you are bound to make when typing variable names. you will now use the Format function. Replace the With…End With block of instructions with the following: Range("B6").

This brings us to the next section. CONVERTING BETWEEN DATA TYPES While VBA handles a lot of data type conversion automatically in the background. Notice that in Figure 4.2. Misspelling variable names can produce incorrect results. italso provides a number of data conversion functions (see Table 4. which explains how to make sure this kind of error doesn’t occur.2 cell B6 does not show a value because Visual Basic does not find the assignment statement for the cst variable.3) that allow you to convert one data type to another. it displays the price of the calculator (see cell A8) as the total cost. It simply does what you tell it to do. Visual Basic does not guess. be sure to replace the names of the variables cst and tax with cost and slsTax in the appropriate lines of the VBA codebefore you continue. Because Visual Basic does not know the sales tax. If you have made changes in the variable names as described above. These functions should be used in situations where .Figure 4.

you will find theCInt and Clng functions quite handy. you may want to use the CCur function to force currency arithmetic.Print"Amount = $" & myMoneyAmount End Sub When using the CCur function. By using this function you can ensure that the date is formatted according to the locale setting of your system. as in the following example procedure: Sub ShowMoney() 'declare variables of two different types Dim myAmount As Single Dim myMoneyAmount As Currency myAmount = 345. currency options are recognized depending on the locale setting of your computer. The same holds true for the CDate function.Value If IsDate(myEntry) Then myRangeValue = CDate(myEntry) End If Debug.34 myMoneyAmount = CCur(myAmount) Debug. single-precision or double-precision number.Print myRangeValue End Sub In cases where you need to round the value to the nearest even number. For example.you want to show the result of an operation as a particular data type rather than the default data type. Sub ConvertToDate() 'assume you have entered Jan 1 2011 in cell A1 Dim myEntry As String Dim myRangeValue As Date myEntry = Sheet2. Use the IsDate function to determine whether a return value can be converted to date or time. as demonstrated in the following . instead of showing the result of your calculation as an Integer.Range("A1").

Print"New Amount = " & myIntAmount End Sub As you can see in the code of the above procedures.3. Table 4.procedure: Sub ShowInteger() 'declare variables of two different types Dim myAmount As Single Dim myIntAmount As Integer myAmount = 345. a constant. the syntax for the VBA conversion functions is as follows: conversionFunctionName(variablename) where variablename is the name of a variable. or an expression (like x + y) that evaluates to a particular data type. VBA data type conversion functions .64 myIntAmount = CInt(myAmount) Debug.Print"Original Amount = " & myAmount Debug.

.

Return to the Code window where you entered the CalcCost procedure. type Option Explicit and press Enter.Forcing Declaration of Variables Visual Basic has the Option Explicit statement that automatically reminds you to formally declare all your variables. At the top of the module window (in the first line). The Option Explicit statement will cause Visual Basic to generate an error message when you try to run a procedure that contains undeclared variables as demonstrated in Hands-On 4. Excel will display the statement in blue.2.2.1. Hands-On 4. Writing a VBA Procedure with Explicitly Declared Variables This Hands-On requires prior completion of Hands-On 4. 2. This statement has to be entered at the top of each of your modules. . 1.

Formula = "Price" Range("B4"). Visual Basic will generate the same error as soon as it encounters another variable name that was not declared. Visual Basic displays the error message “Compile error: Variable not defined.Formula = "Cost" .3.Formula = slsPrice Range("A5").Formula = "Sales Tax" Range("A6"). Click OK to exit the message box. Enter the following declarations at the beginning of the CalcCost procedure: ' declaration of variables Dim slsPrice As Currency Dim slsTax As Single Dim cost As Currency Dim strMsg As String The revised CalcCost procedure is shown below: Sub CalcCost() ' declaration of variables Dim slsPrice As Currency Dim slsTax As Single Dim cost As Currency Dim strMsg As String slsPrice = 35 slsTax = 0. Choose Run | Reset to reset the VBA project. Visual Basic highlights the name of the variable slsPrice.Formula = "The cost of calculator" Range("A4"). Now you have to formally declare this variable.” 4.085 Range("A1"). 6. 5. When you declare the slsPrice variable and rerun your procedure. Run the CalcCost procedure.

Option Explicit forces formal (explicit) declaration of all variables in a particular module.Formula = cost strMsg = "The calculator total is $" & cost &". The term . From now on. 3. Rerun the procedure to ensure that Excel no longer displays the error. One big advantage of using Option Explicit is that any mistyping of the variable name will be detected at compile time (when Visual Basic attempts to translate the source code to executable code). If included. you must enter the Option Explicit statement manually by editing the module yourself. Choose OK to close the Options dialogbox. If you want to require variables to be explicitly declared in a previously created module. Choose Tools | Options.Formula = Format((slsPrice * slsTax). Understanding the Scope of Variables Variables can have different ranges of influence in a VBA procedure. follow these steps: 1. Make sure that the Require Variable Declaration check box is selected in theOptions dialog box (Editor tab). the Option Explicit statement must appear in a module before any procedures."0.Formula = strMsg End Sub 7.00") cost = Format(slsPrice + (slsPrice * slsTax). every new module will beadded with the Option Explicit statement inline 1.00") Range("B6").Range("B5"). Option Explicit in Every Module To automatically include Option Explicit in every new module you create." Range("A8"). 2."0.

scope defines the availability of a particular variable to the same procedure. the CalcCost procedure can have the slsTax variable. In other words. In programming. Both variables are independent of each other. Module-Level Variables Local variables help save computer memory. you often want the variable to be available to other VBA procedures after the procedure in which the variable was declared has finished running. Undeclared variables always have a procedure-level scope. other procedures. you want to declare a module-level variable. to make the slsTax variable available to any other procedure in the Variables module. the variable dies and Visual Basic returns the memory space used by the variable to the computer. declare the slsTax variable in the following way: . Variables declared with the Dim keyword placed within a VBA procedure have a procedure-level scope. For instance. you must place the Dim keyword at the top of the module sheet before any procedures (just below the Option Explicit keyword). As soon as the procedure ends. however. However. The position of the Dim keyword in the module sheet determines the scope of a variable. This situation requires that you change the scope of a variable. A variable’s name must be unique within its scope. you can use the same variable name in different procedures. Variables can have the following three levels of scope in Visual Basic for Applications: Procedure-level scope Module-level scope Project-level scope Procedure-Level (Local) Variables From this chapter. To declare a module-level variable. This means that you cannot declare two variables with the same name in the same procedure. you already know how to declare a variable by using the Dim keyword. Local variables can only be used in the procedure in which they were declared. Procedure-level variables are frequently referred to as local variables. and the ExpenseRep procedure in the same module can have its own variable called slsTax. Instead of a procedure-level variable. and other VBA projects.

2.. In the Code window.. In the same module where the CalcCost procedure is located..Option Explicit Dim slsTax As Single Sub CalcCost() .99 cost = slsPrice + (slsPrice * slsTax) MsgBox slsTax MsgBox cost . In Hands-On 4.3.3. cut the declaration line Dim slsTax As Single in the Variables module from the CalcCost procedure and paste it at the top of the module sheet below the Option Explicit statement. below the Option Explicit statement. you need another procedure that uses the slsTax variable. we will write a new VBA procedure named ExpenseRep. Writing another VBA Procedure with a Module-Level Variable 1. the Dim keyword is located at the top of the module. Hands-On 4. Before you can see how this works. End Sub In the example above. enter the code of the ExpenseRep procedure as shown below: Sub ExpenseRep() Dim slsPrice As Currency Dim cost As Currency slsPrice = 55.Instructions of the procedure..

As soon as you attempt to calculate the cost by running the ExpenseRep procedure. the contents of this variable would be empty upon the termination of the CalcCost procedure. The slsPrice variable is then assigned a value of 55. 3. you can use the Private keyword instead of the Dim keyword. Run the ExpenseRep procedure. Run the CalcCost procedure. After Visual Basic executes the CalcCost procedure that you revised in HandsOn 4. 4. Run the ExpenseRep procedure again. which was declared at a module level. 5.99. so it displays zero in the first message box. When you run the CalcCost procedure.2. The cost includes the sales tax stored in the slsTax variable. The slsPrice variable is independent of the slsPrice variable that is declared within the CalcCost procedure. Visual Basic retrieves the value of the slsTax variable and uses it in the calculation. For instance: Private slsTax As Single . Visual Basic does not know the value of the slsTax variable. the contents of the slsTax variable equals 0. If slsTax were a local variable. Visual Basic erases the contents of all the variables except for the slsTax variable. Because you have not yet run the CalcCost procedure.End Sub The ExpenseRep procedure declares two Currency type variables: slsPrice and cost. Private Variables When you declare variables at a module level. The ExpenseRep procedure calculates the cost of a purchase.085. the slsTax variable has been declared at the module level. Because the sales tax is the same as the one used in the CalcCost procedure.

Private variables are available only to the procedures that are part of the module where they were declared. For example: Option Explicit Option Private Module Public slsTax As Single Sub CalcCost() ... For instance: Option Explicit Public slsTax As Single Sub CalcCost() . When you want to work with a variable in all the procedures in all the open VBA projects. This means that they can be used in any Visual Basic for Applications module. you can use the Option Private Module statement at the top of the module sheet.Instructions of the procedure. End Sub Project-Level Variables Module-level variables that are declared with the Public keyword (instead of Dim) have project-level scope..Instructions of the procedure. you must declare it with the Public keyword. just below the Option Explicit statement and before the declaration line.. Keeping the Project-Level Variable Private To prevent a project-level variable’s contents from being referenced outside its project. Private variables are always declared at the top of the module after the Option Explicit statement. End Sub .....

can reinitialize these variables if required by the program’s logic. Hands-On 4. write the following procedure: Sub CostOfPurchase() ' declare variables Static allPurchase Dim newPurchase As String .4.Notice that the slsTax variable declared at the top of the module with the Public keyword will now be available to any other procedure or VBA project. In the Code window of the Variables module. Visual Basic. Local variables have a lifetime as long as a procedure is running. static variables do not lose their contents when the program is not in their procedure. For example.4 demonstrates the use of the static variable named allPurchase. Module-level and project-level variables preserve their values as long as the project is open. Notice how this variable keeps track of the running total. Static variables are declared at the procedure level. The lifetime of a variable determines how long a variable retains its value. the static variable still retains the original value. Understanding and Using Static Variables A variable declared with the Static keyword is a special type of local variable. Visual Basic allows you to extend the lifetime of a local variable by changing the way it is declared. Lifetime of Variables In addition to scope. and they are reinitialized every time the program is run. when a VBA procedure with a static variable calls another procedure. The CostOfPurchase procedure shown in Hands-On 4. Unlike local variables declared with the Dim keyword. after Visual Basic executes the statements of the called procedure and returns to the calling procedure. variables have a lifetime. however. Local variables declared with the Dim statement lose their values when a procedure has finished. Writing a VBA Procedure with a Static Variable 1.

” Click OK in the message box. The next instruction. Visual Basic displays the message “The cost of a new purchase is: 100. For example. Visual Basic assigns this value to the variable newPurchase. position the insertion point anywhere within the word CSng and press F1.Dim purchCost As Single newPurchase = InputBox("Enter the cost of a purchase:") purchCost = CSng(newPurchase) allPurchase = allPurchase + purchCost ' display results MsgBox "The cost of a new purchase is:" & newPurchase MsgBox "The running cost is:" & allPurchase End Sub The above procedure begins with declaring a static variable named allPurchase and two other local variables: newPurchase and purchCost. allPurchase = allPurchase + purchCost. enter 100 and click OK or press Enter. As soon as you input the value and click OK. When the dialog box appears. Because the result of the InputBox function is always a string. The CSng function requires one argument—the value you want to translate. enter a number. The InputBox function used in this procedure displays a dialog box and waits for the user to enter the value. To find out more about the CSng function. 2. however. the newPurchase variable was declared as the String data type. Visual Basic displays the . Position the cursor anywhere within the CostOfPurchase procedure and press F5. adds to the current purchase value the new value supplied by the InputBox function. That’s why the next instruction uses a type conversion function (CSng) to translate the text value into a numeric variable of the Single data type. use strings in mathematical calculations.The number obtained as the result of the CSng function is then stored in the variable purchCost. The InputBox function is discussed in detail in Chapter 5. You can’t.

second message “The running cost is: 100. 1). These variables are called object variables. Object variables don’t store data. Object variables make it easy to locate data. enter another number. the value of the static variable is increased by the new value supplied in the dialog box. When you run this procedure for the first time.” Click OK in the message box.” 3. 5). they tell where the data is located. Cells(10. Storing data is the main reason for using “normal” variables in your procedures. For instance: Dim myRange As Object . The allPurchase variable will keep the running total for as long as the project is open. Visual Basic displays the second message “The running cost is: 150. Now you will learn how you can represent an object with the object variable. For example. For example. enter 50 and click OK or press Enter. Visual Basic displays the message"The cost of a new purchase is: 50. Object variables are declared similarly to the variables you already know. you enter the word Object as the data type. instead. In Chapter 3. Declaring and Using Object Variables The variables that you’ve learned about thus far are used to store data.Range(Cells(1. with the object variable you can tell Visual Basic that the data is located in cell E10 of the active worksheet. there are special variables that refer to the Visual Basic objects. When the input dialog appears. In addition to the normal variables that store data.Select Instead of using long references to the object. Rerun the same procedure. 4. The only difference is that after the As keyword. You can run the CostOfPurchase procedure as many times as you want. you can declare an object variable that will tell Visual Basic where the data is located. you often need to write long instructions. the content of the allPurchase variable is the same as the content of the purchCost variable. When writing Visual Basic procedures. such as: Worksheets("Sheet1").” When you run the procedure the second time. you worked with several objects in the Immediate window.

Cells(10.” Again. The UseObjVariable procedure shown in Hands-On 4. 5)) myRange. 1). Range(Cells(1. Assign a value to the object variable by using the Set keyword. Cells(10.The statement above declares the object variable named myRange. Hands-On 4.Interior . Visual Basic will display an error message—"Run-time error 91: Object variable or With block variable not set. 5)) The above statement assigns a value to the object variable myRange. Writing a VBA Procedure with Object Variables 1. Well.5 demonstrates the use of the object variable called myRange. If you omit the word Set. it’s time to see a practical example. You also have to assign a specific value to the object variable before you can use this variable in your procedure. write the following procedure: Sub UseObjVariable() Dim myRange As Object Set myRange = Worksheets("Sheet1").5. This value refers to cells A1:E10 in Sheet1.BorderAround Weight:=xlMedium With myRange. 1). The Set keyword must be followed by the equals sign and the value that the variable will refer to._ Range(Cells(1. For example: Set myRange = Worksheets("Sheet1"). In the Code window of the Variables module. it’s not enough to declare the object variable.

it refers to another range (E12:J12)._ Range(Cells(12. every time you want to reference this range. you can use the myRange object variable. The instruction Debug. Cells(12. you’ll use the shortcut—the name of the object variable.Pattern = xlSolid End With Set myRange = Worksheets("Sheet1"). Instead of writing a long instruction: Worksheets("Sheet1"). The next statement sets the object variable myRange to the range A1:E10 on Sheet1. Again. From now on. 1). you don’t need to write the long instruction to reference the object that you want to manipulate. 5). After the number 54 is entered in the new range (E12:J12). Instead of the full object name.Print IsObject(myRange) will enter True in the . the procedure shows you how you can make sure that a specific variable is of the Object type.BorderAround Weight:=xlMedium you can take a shortcut by using the name of the object variable: myRange.BorderAround Weight:=xlMedium The next series of statements changes the color of the selected range of cells (A1:E10). The next statement assigns a new reference to the object variable myRange.Value = 54 Debug. Cells(10. instead of using the entire object’s address.Range(Cells(1. and the next time you use myRange. The purpose of this procedure is to create a border around the range A1:E10.Print IsObject(myRange) End Sub Let’s examine the code of the UseObjVariable procedure line by line. The procedure begins with the declaration of the object variable myRange.ColorIndex = 6 . 10)) myRange. 5)). Visual Basic forgets the old reference..

They are shorter and easier to remember than the actual values to which they point.Immediate window if myRange is an object variable. then you can declare the Worksheet object: Dim mySheet As Worksheet Set mySheet = Worksheets("Marketing") When the object variable is no longer needed. it’s a good idea to create object variables that refer to a particular type of object to make your programs more readable and faster. Advantages of Using Object Variables They can be used instead of the actual object. IsObject is a VBA function that indicates whether a specific value represents an object variable. For instance. Because Visual Basic has many types of objects. You can change their meaning while your procedure is running. you can declare the myRange object variable as a Range object: Dim myRange As Range If you want to refer to a particular worksheet. Using Specific Object Variables The object variable can refer to any type of object. in the UseObjVariable procedure (see the previous section). This frees up memory and system resources: . you can assign Nothing to it. instead of the generic object variable (Object). Position the cursor anywhere within the UseObjVariable procedure and press F5. 2.

The VarType function returns an integer indicating the type of a variable. Using the Built-in VarType Function . 2.6. Figure 4. Let’s see how you can use the VarType function in the Immediate window.7. Right-click the variable name and choose Definition from the shortcut menu. Visual Basic will jump to the variable declaration line. Try finding definitions of other variables in other procedures created in this chapter using both methods of jumping to the variable definition. Determining a Data Type of a Variable You can find out the type of a variable by using one of the VBA built-in functions. Hands-On 4. 5. you can quickly locate the definition of the variable by selecting the variable name and pressing Shift+F2 or choosing View | Definition. Locate the statement purchCost = CSng(newPurchase). Press Ctrl+Shift+F2 or choose View | Last Position to return your mouse pointer to its previous position. 4. 3. Return to the previous location by pressing Ctrl+Shift+F2. Hands-On 4. Locate the code of the CostOfPurchase procedure.3 displays the VarType function’s syntax and the values it returns.Set mySheet = Nothing Finding a Variable Definition When you find an instruction in a VBA procedure that assigns a value to a variable.6. Let’s take a look at how this works in Hands-On 4. Finding a Variable Definition in the Code Window 1.

In the Visual Basic Editor window. Type the following statements that assign values to variables: age = 18 birthdate = #1/1/1981# firstName = "John" 3. As shown in Figure 4. . Visual Basic returns 2. 2. the number 2 represents the Integer data type.3. If you make a mistake in the variable name (let’s say you type birthday. Now ask Visual Basic what type of data each of the variables holds: ?VarType(age) When you press Enter.1. If you type: ?VarType(birthdate) Visual Basic returns 7 for Date. Visual Basic returns zero (0). If you type: ?VarType(firstName) Visual Basic tells you that the value stored in the variable firstName is a String type (8). instead of birthdate). choose View | Immediate Window.

With the built-in VarType function. you can learn the data type the variable holds.FIGURE 4.3. can be used . The Select Case statement. which is covered in Chapter 6.

to write a function procedure (functions are covered in the next chapter) to return a user-friendly name of the variable type. Public Function GetFriendlyVarType(vType As Variant) As String Select Case VarType(vType) Case 0 GetFriendlyVarType = "Empty" Case 1 GetFriendlyVarType = "Null" Case 2 GetFriendlyVarType = "Integer" Case 3 GetFriendlyVarType = "Long" Case 4 GetFriendlyVarType = "Single" Case 5 GetFriendlyVarType = "Double" Case 6 GetFriendlyVarType = "Currency" Case 7 GetFriendlyVarType = "Date" Case 8 GetFriendlyVarType = "String" Case 9 GetFriendlyVarType = "Object" Case 10 GetFriendlyVarType = "Error" Case 11 GetFriendlyVarType = "Boolean" .

a value was assigned to myVariable in the Immediate window.Case 12 GetFriendlyVarType = "Variant" Case 13 GetFriendlyVarType = "Data Object" Case 14 GetFriendlyVarType = "Decimal" Case 17 GetFriendlyVarType = "Byte" Case 20 GetFriendlyVarType = "LongLong" Case 36 GetFriendlyVarType = "Variant containing UDT" Case Is >= 8192 GetFriendlyVarType = "Array" Case Else GetFriendlyVarType = "Unknown" End Select End Function To test the above function. a question mark was used to query the contents of the result variable: myVariable= "Today is Saturday" result = GetFriendlyVarType(myVariable) ?result myVariable=#07-12-2013# result = GetFriendlyVarType(myVariable) . Then. The result of the GetFriendlyVarType function was assigned to the variable named result.

as in the following examples: Const dialogName = "Enter Data" As String Const slsTax = 8. use the . Declare constants by using the Const statement. like a variable. just before the first Sub statement. USING CONSTANTS IN VBA PROCEDURES The contents of a variable can change while your procedure is executing. Visual Basic requires that you declare constants before you use them. has a scope. you should use constants. declare it at the procedure level. For instance: Sub WedAnniv() Const Age As Integer = 25 MsgBox (Age) End Sub If you want to use a constant in all the procedures of a module. For instance: Private Const driveLetterAs String = "C:" The Private constant has to be declared at the top of the module. A constant is like a named variable that always refers to the same value. use the Private keyword in front of the Const statement. If you want to make a constant available to all modules in the workbook. and the second one returned Date.?result The first variable assignment returned String as the data type. To make a constant available within a single procedure. just below the name of the procedure.5 Const ColorIdx = 3 A constant. If your procedure needs to refer to unchanged values over and over again.

Hands-On 4. several constants can be declared on one line if separated by commas. just before the first Sub statement. choose View | Object Browser. When declaring a constant. you can simply change the value in the declaration of the Const statement instead of tracking down every occurrence of that value. . For instance: Public Const NumOfChars As Integer = 255 The Public constant has to be declared at the top of the module. In the Project/Library list box.8 where we open the Object Browser to take a look at the list of Excel constants. For example. 2. you can use any one of the following data types: Boolean. This way. if the value changes (for example. For instance: Const Age As Integer = 25. Viewing Excel Constants in the Object Browser 1. Date. Double. the sales tax goes up). City As String = "Denver" Using constants makes your VBA procedures more readable and easier to maintain. Integer. Single. Like variables. click the drop-down arrow and select Excel. Let’s proceed to Hands-On 4. String. if you refer to a certain value several times in your procedure. Long. or Variant. These built-in constants can be looked up using the Object Browser window.Public keyword in front of the Const statement. Built-in Constants Both Microsoft Excel and Visual Basic for Applications have a long list of predefined constants that do not need to be declared. Byte.8. In the Visual Basic Editor window. use a constant instead of the value. Currency.

Visual Basic shows the result of the search in the Search Results area.” . 4. To look up VBA constants.4. Enter constants as the search text in the Search box and press Enter or click the Search button. choose VBA in the Project/Library list box. Scroll down in the Classes list box to locate and then select Constantsas shown in Figure 4. Notice that the names of the VBA built-in constants begin with the prefix “vb.” 5. Notice that the names of all the constants begin with the prefix “xl. The right side of the Object Browser window displays a list of all built-in constants that are available in the Microsoft Excel object library.3.

4. CHAPTER SUMMARY . Use the Object Browser to look up any built-in constant.Figure 4.

This chapter introduced several new VBA concepts such as data types. . Now that you know what variables are and how to use them. You learned how to declare various types of variables and define their types. and constants. You also saw the difference between a variable and a constant. In addition. you are capable of creating VBA procedures that can manipulate data in more meaningful ways than you saw in previous chapters. variables. you will learn about built-in functions that will allow your VBA procedure to interact with users. you will expand your VBA knowledge by learning how to write procedures with arguments as well as function procedures. In the next chapter.

They begin with the keyword Function and end with the keywords End Function. With property procedures you can set and get the value of an object’s property or set a reference to an object. Function procedures (functions) perform specific tasks that return values. In this chapter.” In this chapter. you will take a thorough look at the two most useful VBA functions: MsgBox and InputBox. In addition. You will learn how to create custom objects and use property procedures in Chapter 9. They begin with the keyword Sub and end with the keywords End Sub.Chapter 5 VBA Procedures: Subroutines and Functions Earlier in this book you learned that a procedure is a group of instructions that allows you to accomplish specific tasks when your program runs. you will learn how to create and execute custom functions. you will create your first function procedure. In Chapter 1. Property procedures are used with custom objects. you find out how variables (see Chapter 4) are used in passing values to subroutines and functions. ABOUT FUNCTION PROCEDURES . you learned various ways to execute this type of procedure."Working with Collections and Class Modules. VBA has three types of procedures: Subroutine procedures (subroutines) perform some useful tasks but don’t return any values. Later in the chapter. Subroutines can be recorded with the macro recorder (as you did in Chapter 1) or written from scratch in the Visual Basic Editor window (see Chapters 3 and 4). Function procedures can be executed from a subroutine or accessed from a worksheet just like any Excel built-in function.

xlsm). In the Properties window. there will be times when you may require a custom calculation. Among the reasons for creating custom VBA functions are the following: To analyze data and perform calculations To modify data and report information To take a specific action based on supplied or calculated data Creating a Function Procedure Like Excel functions. you can perform a wide variety of calculations automatically. The best way to learn about functions is to create one.xlsm. save it as and select VBAProject 3. You can build any functions that are not supplied with Excel. However. Please note files for the “Hands-On” project may be found on the companion CD-ROM. change the name of the project name to ProcAndFunctions. Select the ProcAndFunctions (Practice_Excel05. Writing a Simple Function Procedure 1. you will create a function procedure that sums two values.1. After setting up a new VBA project. so let’s get started. function procedures perform calculations and return values. Open a new Excel workbook and C:\Excel2013_ByExample\Practice_Excel05.With the hundreds of built-in Excel functions. 4. Switch to the Visual Basic Editor window (Practice_Excel05. With VBA programming. Hands-On 5.xlsm) project in the Project . 2. you can quickly fulfill this special need by creating a function procedure.

In the Properties window. 7. In the Add Procedure dialog box. In the Project Explorer window.1: Name: SumItUp Type: Function Scope: Public . change the Module1 name to Sample1. 6. highlight Sample1 and click anywhere in the Code window. 5. make the entries shown in Figure 5. The Add Procedure dialog box appears. Choose Insert | Procedure.Explorer window. and choose Insert | Module.

1. Visual Basic automatically creates the procedure type you choose.FIGURE 5.n) . 8. When you use the Add Procedure dialog box. Modify the function declaration as follows: Public Function SumItUp(m. Click OK to close the Add Procedure dialog box. Visual Basic enters an empty function procedure that looks like this: Public Function SumItUp() End Function 9.

2. Type the following statement between the Public Function and End Function statements: SumItUp = m + n This statement instructs Visual Basic to add the value stored in the n variable to the value stored in the m variable and return the result to the SumItUp function. The Public keyword is optional. By doing this. type the function name followed by the equals sign and the value you want it to return. Notice the keyword Function followed by the name of the function (SumItUp) and a pair of parentheses.n) represents a value. The completed custom function procedure is shown below: Public Function SumItUp(m.n) SumItUp = m + n End Function The first statement declares the name of the function procedure. Each of the passed in variables (m. to see how to execute the SumItUp function. 10. Every function procedure ends with the End Function statement Check out Hands-On 5. you will list the data items that the function will use in the calculation. your custom function will be able to add any two numbers that you specify. To specify the value that you want the function to return. you can make the function more flexible by providing it with the arguments in the form of variables. In the statement above. You will supply the values for each of these variables when you run this function. set the name of the function equal to the total of m + n. About Function Names . The Public keyword indicates that the function is accessible to all other procedures in all other modules. Instead of passing the actual values to the function.End Function The purpose of this function is to add two values. In the parentheses.

VBA procedures have scope. In the following sections. you created your first function. Scoping VBA Procedures In the previous chapter. you will learn special techniques for executing functions. Running a Function Procedure from a Worksheet A custom function procedure is like an Excel built-in function. you learned that the variable’s scope determines which modules and procedures it can be used in. you can skip the Public keyword if you want.2. This means they can be called by other procedures in any module. A procedure scope determines whether it can be called by procedures in other modules. a function procedure can be executed in just two ways: You can use it in a worksheet formula or you can call it from another procedure. Like variables.2.Function names should suggest the role that the function performs. Executing a Function Procedure from within an Excel Worksheet . a function procedure is useless unless you know how to execute it. And if you replace the Public keyword with the Private keyword. This section shows you how to put your new function to work. Because procedures are public by default. Unlike a subroutine. If you don’t know the exact name of the function or its arguments. you can use the Formula palette to help enter the required function in a worksheet as shown in Hands-On 5. your procedure will be available only to other procedures in the same module. Executing a Function Procedure Congratulations! In the previous section. However. and must conform to the rules for naming variables (see Chapter 4). Hands-On 5. all VBA procedures are public. not to procedures in other modules. By default.

In the function name box.n). Click the Insert Function (fx) button on the Formula bar. Excel displays the Insert Function dialog box. When you highlight the name of the function in the function name box. locate and select the SumItUp function that was created earlier in this chapter. The lower portion of the dialog box displays an alphabetical listing of all the functions in the selected category. 2. select User Defined. 3.1. the bottom part of the dialog box displays the function’s syntax: SumItUp(m. Switch to the Microsoft Excel window and select any cell. In the category drop-down box. .

4.2. They also appear in the list of all Excel built-in functions when you select All in the category drop-down. Click OK to begin writing a formula. The Function Arguments dialog box appears. VBA custom function procedures are listed under the User Defined category in the Insert Function dialog box. as shown in Figure 5.3.FIGURE 5. This dialog displays the name of the function and each of its arguments: m and n. .

whether built-in or custom-made with VBA programming. double-click the cell . Enter new values for the function’s m and n arguments and click OK To edit the arguments’ values directly in the cell. 7. select the cell that displays the function’s result and click the Insert Function (fx) button to access the Function Arguments dialog box. Click OK to exit the Function Arguments dialog. the function will return an error if you skip either one of the arguments.3. To edit the function. Enter the values for the arguments as shown in Figure 5. or enter your own values. Excel enters the SumItUp function in the selected cell and displays its result. Because both arguments (m and n) are required. 6. 5. As you type the values in the argument text boxes.3.FIGURE 5. The Formula palette feature is helpful in entering any worksheet function. Excel displays the values you entered and the current result of the function.

enter the RunSumItUp procedure. Excel will display zero (0) as the result of the function. On the worksheet. To do this. n As Single m = 370000 n = 3459. Sub RunSumItUp() Dim m As Single. When you click OK.3. Hands-On 5. enter C1 for the m argument and C2 for the n argument. Private Functions Are Not Visible to Users Functions declared with the Private keyword do not appear in the Insert Function dialog box. The following procedure calls the SumItUp function and prints the result of the calculation to the Immediate window.PrintSumItUp(m.containing the function and make the necessary changes. enter the values in cells C1 and C2 and your custom function will recalculate the result just like any other built-in Excel function. In the same module where you entered the code of the SumItUp function procedure. Running a Function Procedure from Another VBA Procedure To execute a custom function. Executing a Function from a VBA Procedure 1. write a VBA subroutine and call the function when you need it.3. in the Function Arguments dialog box shown in Figure 5.77 Debug.n) MsgBox"Open the Immediate Window to see the . simply enter cell references instead of values. They can only be run from another VBA procedure. Private functions cannot be used in a formula. You may also set up the SumItUp function to perform calculations based on the values entered in cells. For example.

Visual Basic calls the SumItUp function and passes the values stored in the m and n variables to it. You can find more information about using the MsgBox function later in this chapter. the MsgBox function informs the user where to look for the result.) A Quick Test of a Function After you write your custom function. Remember to enclose the function’s arguments in parentheses. Set up a reference to the workbook containing your custom functions. For example. Visual Basic returns to the RunSumItUp subroutine and uses the Debug. type: ? SumItUp(54. Ensuring Availability of Your Custom Functions Your custom VBA function is only available as long as the workbook where the function is stored is open. (Go back to Chapter 3 for information about setting up a reference to another project. To make sure that your custom VBA functions are available every time you work with Microsoft Excel. 367. you can quickly try it out in the Immediate window. Place the mouse pointer anywhere within the RunSumItUp procedure and press F5 to run it. The next two statements assign the values to those variables. These variables will be used to feed the data to the function.24) .result. Save the workbook with your custom VBA function in the XLStart folder. 2." End Sub Notice how the above subroutine uses one Dim statement to declare the m and n variables. the function is no longer available. Finally. Next. When the function procedure statement SumItUp= m + n is executed. you can do one of the following: Store your functions in the Personal macro workbook.Print statement to print the function’s result to the Immediate window. To display the value of a function. open the Immediate window and type a question mark (?) followed by the function name. If you close the workbook.

unless you change the values entered in the specified cells. These procedures did not require that you provide additional data before they could be run. For example. Your function procedure runs. you can pass values to custom VBA procedures. procedures (both subroutines and functions) often take arguments. Type the following NumOfCharacters subroutine in the same module (Sample1) where you entered the SumItUp function: Sub NumOfCharacters() Dim f As Integer Dim l As Integer f = Len(InputBox("Enter first name:")) l = Len(InputBox("Enter last name:")) .24 PASSING ARGUMENTS So far you’ve created simple VBA procedures that carried out specific tasks. Just like you can pass any values to Excel’s built-in functions. We will write a procedure that collects the user’s first and last names. However. we will call the SumItUp function to get the sum of characters in a person’s first and last names. Multiple arguments are separated with commas.4.and press Enter. respectively. using the values you passed for the m and n arguments. The result of the function appears on a line below: 421. Next. the Sum function =SUM(A4:A5) will return 15. Passing Arguments to Functions (Example 1) 1. Hands-On 5. Arguments are one or more values needed for a procedure to do something. you already know that Excel’s built-in functions can produce different results based on the values you supply to them. Let’s see how you can pass some values from a subroutine procedure to the SumItUp function. Having used Excel for a while. Arguments are entered within parentheses. in real life. if cells A4 and A5 contain the numbers 5 and 10.

Visual Basic places the result of the Len function in the f variable for further reference. You can run the NumOfCharacters procedure as many times as you’d like. Visual Basic displays the input box asking for the first name. After that.l) End Sub 2. Visual Basic adds up the two numbers and returns the result to the SumItUp function. Once the substitution is done. There are no more tasks to perform inside the function procedure. Now a message appears on the screen displaying the total number of characters. For more information on the use of this function. so Visual Basic returns to the subroutine and provides the SumItUp function’s result as an argument to the MsgBox function. Click OK to exit the message box. see the section titled “Using the InputBox Function” later in this chapter. because the result is not yet ready. However. Place the mouse pointer within the code of the NumOfCharacters procedure and press F5. and press Enter or click OK. Enter any name. What happens next? Visual Basic encounters the MsgBox function. each time supplying different first and last names. Visual Basic jumps quickly to the SumItUp function to perform the calculation using the values saved earlier in the f and l variables. Visual Basic substitutes the m argument with the value of the f variable and the n argument with the value of the l variable. Visual Basic passes the last name to the Len function to get the number of characters. Inside the function procedure. 5. . The Len function calculates the number of characters in the supplied text.MsgBoxSumItUp(f. Then that number is stored in the l variable. Enter any last name. This function tells Visual Basic to display the result of the SumItUp function. This box is generated by the following function: InputBox("Enter first name:"). 4. 3. Visual Basic takes the text you entered and supplies it as an argument to the Len function. Visual Basic displays the next input box. this time asking for the last name. and press Enter or click OK. Now. let’s look at another example of passing arguments using variables.

. it collects the data from the user and stores the values of the first and last names in the variables m and n. n As String. The result is the full name of the user (first and last names separated by a space).5. Visual Basic substitutes the variables’ contents for the arguments of the JoinText function and assigns the result to the name of the function (JoinText). Activate the Sample2 module and enter the EnterText subroutine as shown below: Sub EnterText() Dim m As String. Passing Arguments to Functions (Example 2) 1. Enter the following function procedure: Function JoinText(k.Hands-On 5. r As String m = InputBox ("Enter your first name:") n = InputBox("Enter your last name:") r = JoinText(m. Then these values are passed to the JoinText function. The MsgBox function then displays the contents of the r variable in a message box.xlsm) project and change the module’s name to Sample2. When Visual Basic returns to the EnterText procedure. Add a new module to the ProcAndFunctions (Practice_Excel05. n) MsgBox r End Sub 3. 2. it stores the function’s value in the r variable. 4. Place the cursor anywhere inside the code of the EnterText procedure and press F5 to run it.o) JoinText = k +"" + o End Function As Visual Basic executes the statements of the procedure.

Once the function does something. When a subroutine calls a function procedure. Function NumOfDays() NumOfDays = 7 End Function Sub DaysInAWeek() MsgBox"There are"&NumOfDays&" days in a week. they cannot include statements for inserting. When you specify the data type for your function’s result. or formatting data in a worksheet. If you don’t specify the data type. the result . opening files. you get the same advantages as when you specify the data type for your variables: Your procedure uses memory more efficiently. When you declare a function procedure. it passes the required arguments as variables to it. n) What Function Procedures Cannot Do Functions cannot perform any actions. or changing the way the screen looks. and therefore it runs faster. assign the value to the name of the function.You can call the JoinText function directly from the MsgBox function like this: MsgBoxJoinText(m." End Sub Specifying Argument Types In the preceding section. Each argument name refers to whatever value you provide at the time the function is called. you learned that functions perform some calculations based on data received through their arguments. For instance. Visual Basic assigns the default type (Variant data type) to your function’s result. To pass a specific value from a function to a subroutine. the NumOfDays function shown below passes the value of 7 to the subroutine DaysInAWeek. Argument names are like variables. deleting. you list the names of arguments inside a set of parentheses. For example.

33 num2 = 19. Long.24 result = MultiplyIt(num1. Passing Arguments to Functions (Example 3) 1. Hands-On 5. To specify the data type for your function’s result. For example: Function MultiplyIt(num1. The result of your function procedure can be String. Like variables. add the keyword As and the name of the desired data type to the end of the function declaration line. num2) As Integer Let’s take a look at an example of a function that returns an Integer number. 2. functions can have types.is assigned to the function name. etc. num2) MsgBox result End Sub 3. Notice that the function procedure’s name is used as if it were a variable.xlsm) project and change the module’s name to Sample3. Add a new module to the ProcAndFunctions (Practice_Excel05. although the arguments passed to it are declared as Single data types in a calling subroutine. Enter the MultiplyIt function procedure below the HowMuch subroutine: . Integer.6. Activate the Sample3 module and enter the How Much subroutine as shown below: Sub HowMuch() Dim num1 As Single Dim num2 As Single Dim result As Single num1 = 45.

when you pass arguments as variables Visual Basic can suddenly change the value of the variables. the HowMuch procedure will display the result in the data type specified in the declaration line of the result variable.5.7. num2 As Integer. num3 As Integer . Passing Arguments to Functions (Example 4) 1. Instead of 872. Let’s look at the following example. you should precede the name of the argument in the function’s declaration line with the keyword ByVal.Function MultiplyIt(num1. To ensure that the called function procedure does not alter the value of the passed in arguments. Add a new module to the ProcAndFunctions (Practice_Excel05. How about passing different values each time you run the procedure? Instead of hard coding the values to be used in the multiplication. Refer to the Enter Text procedure in Hands-On 5. Activate the Sample4 module and type the procedures shown below: Sub ThreeNumbers() Dim num1 As Integer. use the Input Box function to ask the user for the values at runtime. If you don’t assign the data type to the MultiplyIt function’s result. Hands-On 5. Passing Arguments by Reference and Value In some procedures. 4. the result of the multiplication will be 872. Run the How Much procedure. you may want to assign the Integer data type to the result of the function to ensure that the result is a whole number. num2) As Integer MultiplyIt = num1 * num2 End Function Because the values stored in the variables num1 and num2 are not whole numbers.xlsm) project and change the module’s name to Sample4.1492. 2.

Inside the function procedure. The function’s arguments are the variables num1. and 30. ByVal num2. when the function passes the calculated average to the ThreeNumbers procedure. notice that prior to the calculation of the average. The values stored in these variables are the same as the original values assigned to them—10. Therefore. and num3. the MyAverage function changes the value of the num1 variable. The next three MsgBox functions show the contents of each of the variables. ByVal num3) num1 = num1 + 1 MyAverage = (num1 + num2 + num3) / 3 End Function To prevent the function from altering values of arguments. 3. Notice that all of the function arguments are preceded with the keyword ByVal. num2. The ThreeNumbersprocedure assigns values to three variables and then calls the MyAverage function to calculate and return the average of the numbers stored in these variables. Run the ThreeNumbers procedure. as expected.num1 = 10 num2 = 20 num3 = 30 MsgBoxMyAverage(num1. What will happen if you omit the keyword ByVal in front of the num1 argument in the MyAverage function’s declaration line? The function’s result will still be the . num2. the MsgBox function displays the result as 20. Also. num3) MsgBox num1 MsgBox num2 MsgBox num3 End Sub Function MyAverage(ByVal num1. use the keyword ByVal before the arguments’ names (See the “Know Your Keywords: ByRef and ByVal” sidebar). 20. the num1 variable equals 11 (10 + 1).3333333333333 and not 20.

You .3333333333333 instead of 20) but has also modified the original data stored in the num1 variable. but the contents of the num1 variable displayed by MsgBoxnum1 is now 11. precede the name of the argument with the Optional keyword. the original data does not change—only the copy changes. use the ByVal keyword. If the function changes the value of an argument passed by value. Optional arguments must always be the Variant data type. the original value is changed. This means that Visual Basic makes a copy of the original data and passes that copy to a function. Visual Basic has two keywords that give or deny permission to change the contents of a variable—ByRef and ByVal. you created a function to calculate the average of three numbers. To indicate that a procedure argument is not always required. By default. Know Your Keywords: ByRef and ByVal Because any of the variables passed to a function procedure (or a subroutine) can be changed by the receiving procedure. however. the original value of the num1 variable remained the same. When you use the ByVal keyword in front of an argument name. To prevent Visual Basic from permanently changing the values supplied to the function. Using Optional Arguments At times you may want to supply an additional value to a function.same. In the preceding section. referring to the original data specified in the function’s argument at the time the function is called. you don’t need to explicitly insert the ByRef keyword. Suppose that sometimes you’d like to use this function to calculate the average of two numbers. it is important to know how to protect the original value of a variable. you’d like the function to perform the same calculation for a group of two or more people. Let’s say you have a function that calculates the price of a meal per person. Visual Basic passes the argument by value. You will get this result if you omit the ByVal keyword in front of the num1 argument in the MyAverage function’s declaration line. That’s why when the MyAverage function changed the value of the num1 argument. If you want the function procedure to change the original value. Arguments that are optional come at the end of the argument list. Visual Basic passes information into a function procedure (or a subroutine) by reference (ByRef keyword). following the names of all the required arguments. if the function alters the value of the argument. Sometimes. This means that you can’t specify the optional argument’s type by using the As keyword. T h e MyAverage function has not only returned an unexpected result (20. because passed variables default to ByRef. So.

2. The arguments num1 and num2 are required. The optional argument is listed at the end of the argument list.1 End If Avg = (num1+num2+num3)/totalNums End Function Let’s take a few minutes to analyze the Avg function. Visual Basic treats all of these arguments as Variants. This function can take up to three arguments. The argument num3 is optional. Activate the Sample5 module and enter the function procedure Avg shown below: Function Avg(num1. Hands-On 5. the totalNums variable is declared as an Integer and then assigned a beginning value of 3. Notice that the name of the optional argument is preceded with the Optional keyword. and num3 arguments is not declared. let’s create the Avg function to calculate the average for two or three numbers. the handy built-in function . num2. Inside the function procedure.xlsm) project and change the module’s name to Sample5. num2. Optional num3) Dim totalNums As Integer totalNums = 3 If IsMissing(num3)Then num3 = 0 totalNums = totalNums . Writing Functions with Optional Arguments 1. Because the function has to be capable of calculating an average of two or three numbers.could define the third argument of the MyAverage function as optional. To preserve the original MyAverage function. Because the type of the num1. Add a new module to the ProcAndFunctions (Practice_Excel05.8.

Hence. Visual Basic displays the name of the optional argument enclosed in square brackets. This way. 3. Make sure you run it with two and then with three arguments. totalNums is 2. then (Then) Visual Basic supplies a zero for the value of the third argument (num3 = 0) and reduces the value stored in the argument totalNums by one (totalNums = totalNums – 1). In addition. The IsMissing function allows you to determine whether or not the optional argument was supplied.IsMissing checks for the number of supplied arguments. The next statement calculates the average based on the supplied data. (See Chapter 6 for a detailed description of decisionmaking statements used in VBA. Visual Basic displays the result: 2. you’ll be able to quickly determine when the values of arguments were altered. and the result is assigned to the name of the function. the IsMissing function puts in its place the value of zero (0). and at the same time it deducts the value of 1 from the value stored in t h e totalNums variable.3.3333333333333. How else can you run the Avg function? On your own. If the third (optional) argument is not supplied. the Avg function allows you to calculate the average of two or three numbers. You decide which values and how many values (two or three) you want to average.) If the num3 argument is missing (IsMissing). the subroutine should show the original values of arguments. Testing a Function Procedure To test whether a custom function does what it was designed to do. run this function from a worksheet. As you’ve seen. This function returns the logical value true if the third argument is not supplied. If the . write a simple subroutine that will call the function and display its result. When you start typing the values for the function’s arguments in the Immediate window. The IsMissing function is used here with the decision-making statement If…Then. Now call this function from the Immediate window like this: ?Avg(2. if the optional argument is missing. If you enter the following: ?Avg(2.5.5) this time the result is 3.3) As soon as you press Enter. and it returns false when the third argument is given.

. you can also inform the users about an unexpected error or the result of a specific calculation. the MsgBox or InputBox function. for example.aspx Take. These functions can be looked up in the Visual Basic online help: http://msdn. You create a simple message box by following the MsgBox function name with the text enclosed in quotation marks.com/en-us/library/office/jj692811. You closed the message box by clicking the OK button or pressing the Enter key.4.function procedure uses optional arguments. When you make a mistake. So far you have seen a simple implementation of this function. a dialog box comes up and displays a message informing you of the error. In the next section. You will also learn how to get information from the user with the InputBox function. Visual Basic displays the message box shown in Figure 5. One of the features of a good program is its interaction with the user. to display the message “The procedure is complete. LOCATING BUILT-IN FUNCTIONS VBA comes with numerous built-in functions. you interact with the application by using various dialog boxes. You do this with the help of the MsgBox function." You can quickly try out the above instruction by entering it in the Immediate window. you will find out how to control the way your message looks. When you write your own procedures.” you write the following statement: MsgBox "The procedure is complete. When you work with Microsoft Excel. you’ll also need to check those situations in which the optional arguments may be missing. In other words. one-button dialog box.microsoft. Using the MsgBox Function The MsgBox function that you have used thus far was limited to displaying a message to the user in a simple. When you type this instruction and press Enter.

buttons] [. When you enter a long text string for the prompt argument. is required.” You can also assign your own help topic. Let’s do some exercises in the Immediate window to . The arguments listed in square brackets are optional. The MsgBox function allows you to use other arguments that make it possible to set the number of buttons that should be available in the message box or change the title of the message box from the default. [. prompt. place the text as the argument of the MsgBox function.4.FIGURE 5. Visual Basic decides how to break the text so it fits the message box. title]. “Microsoft Excel. context]) Notice that while the MsgBox function has five arguments. To display a message to the user. only the first one. The syntax of the MsgBox function is as follows: MsgBox (prompt [. helpfile.

MsgBox"All processes completed successfully. Hands-On 5. This long message will look more appealing when you take the text formatting into your own hands. and then press Enter. Visual Basic shows the resulting dialog box. Be sure to enter the entire text string on one line. Now connect an external storage device to your computer. Chr(13) returns a carriage return character (this is . you can break it into several lines using the VBA Chr function. and it returns a character represented by this number. Formatting Text for Display in the MsgBox Function 1. For example." As soon as you press Enter.learn various text formatting techniques. The following procedure will copy the workbook file to the attached device. When the text of your message is particularly long.5.9. The Chr function requires one argument and a number from 0 to 255. Enter the following instruction in the Immediate window. FIGURE 5.

You can break a long text string into several lines by using the Chr(13) function. as shown in the revised statement below: MsgBox "All processes completed successfully. . 2.6. The following procedure " &Chr(13) _ & "will copy the workbook file to the attached device. and Chr(10) returns a linefeed character (useful for adding spacing between the text lines). "&Chr(13) _ & "Now connect an external storage device "&Chr(13) _ & "to your computer.the same as pressing the Enter key). You must surround each text fragment with quotation marks." FIGURE 5. Modify the instruction entered in the previous step in the following way: MsgBox "All processes completed successfully. Quoted text embedded in a text string requires an additional set of quotation marks.

As you can see." _ The Chr(13) function indicates a place where you’d like to start a new line." End Sub When you run the MyMessage procedure. Note: When you enter exceptionally long text messages on one line. 4."& Chr(13) _ & "Now connect an external storage device" & Chr(13) _ & "to your computer.6. To improve the readability of your message.xlsm) project and change the module’s name to Sample6. Add a new module to the ProcAndFunctions (Practice_Excel05. The following procedure" & Chr(13) _ & "will copy the workbook file to the attached device. text entered on several lines is more readable. and the code is easier to maintain. The string concatenation character (&) is used to add a carriage return character to a concatenated string. it’s easy to make a mistake."&Chr(13) _ & "Now connect an external storage device "&Chr(13) _ & "to your computer. you may want to add more . Visual Basic displays the same message as the one shown in Figure 5. Unfortunately. The following procedure " &Chr(13) _ & "will copy the workbook file to the attached device. Visual Basic has a special line continuation character (an underscore _) that allows you to break a long VBA statement into several lines. the line continuation character cannot be used in the Immediate window. 3. Activate the Sample6 module and enter the MyMessage subroutine as shown below. Be sure to precede each line continuation character (_) with a space: Sub MyMessage() MsgBox"All processes completed successfully. As you recall.

"_ & Chr(10) &Chr(10) _ & "Now connect an external storage device "_ &Chr(13) &Chr(13) _ & "to your computer. 5. use two Chr(13) or two Chr(10) functions. as shown in the following step. Enter the following MyMessage2 procedure: Sub MyMessage2() MsgBox"All processes completed successfully.spacing between the text lines by including blank lines. The following procedure "_ & Chr(10) &Chr(10) _ & "will copy the workbook file to the attached device. . To do this." End Sub Figure 5.7 displays the message box generated by the MyMessage2 procedure.

Table 5.1.7. This argument can be a constant or a number. You can increase the readability of your message by increasing spacing between the selected text lines. the resulting message box includes only the OK button.1. let’s take a closer look at the next argument of the MsgBox function. it’s frequently used.FIGURE 5. The buttons argument specifies how many and what types of buttons you want to appear in the message box. as shown in Table 5. as you’ve seen in the preceding examples. If you omit this argument. Settings for the MsgBoxbuttons argument . Although the buttons argument is optional. Now that you’ve mastered the text formatting techniques.

the default button is selected . one of them is considered a default button.When should you use the buttons argument? Suppose you want the user of your procedure to respond to a question with Yes or No. When the user presses Enter. If a message box includes more than one button. Your message box may then require two buttons.

Because you can display various types of messages (critical. and the No button as the default button. you can visually indicate the importance of the message by including in the buttons argument the graphical representation (icon) for the chosen message type. If the message box is application modal (vbApplication Modal). and press Enter: MsgBox"Do you want to proceed?". For example. icon settings. Let’s go back to the Immediate window for more testing of the capabilities of the MsgBox function. information). you must include the vbSystemModal setting in the buttons argument. . the question mark icon. You should arrive at 292 (4+32+256). warning. default button settings. and other MsgBox display settings. Using a Built-in MsgBox Function with Arguments (Example 1) 1. the user must close the message box before continuing to use your application. to display a message box with two buttons (Yes and No).1 and add them up. To quickly see the message box using the calculated message box argument. To create a buttons argument.10. look up the corresponding values in Table 5. Hands-On 5. enter the following statement in the Immediate window. message box modality.automatically. 292 The resulting message box is shown in Figure 5. On the other hand. you can add up the values for each setting you want to include. In addition to the type of message. if you want to suspend all the applications until the user responds to the message box.8. the buttons argument can include a setting to determine whether the message box must be closed before a user switches to another application. It’s quite possible that the user may want to switch to another program or perform another task before responding to the question posed in your message box. The buttons argument settings are divided into five groups: button settings. Only one setting from each group can be included in the buttons argument.

Now enter the following revised statement on one line in the Immediate window and press Enter. The following example shows how to use the buttons argument inside the Visual Basic procedure. Using a Built-in MsgBox Function with Arguments . vbYesNo + vbQuestion + vbDefaultButton2 This statement (which must be entered on one line) produces the same result shown in Figure 5. When you derive the buttons argument by adding up the constant values. MsgBox"Do you want to proceed?". it’s better to use the constants instead of their values.11. Hands-On 5. your procedure becomes less readable.8. There’s no reference table where you can check the hidden meaning of 292. 2.FIGURE 5. You can specify the number of buttons to include in the message box by using the optional buttons argument. To improve the readability of your MsgBox function.8 and is more readable.

If you press Enter. The settings for the buttons argument is placed in the myButtons variable. you can use their values.xlsm) project and change the module’s name to Sample7. To change the default button. then run it: Sub MsgYesNo() Dim question As String Dim myButtons As Integer question = "Do you want to open a new workbook?" myButtons = vbYesNo + vbQuestion + vbDefaultButton2 MsgBox question. by specifying the names of the buttons argument’s constants. 4. When you run the procedure.8. Instead of using the names of constants. T he question and myButtons variables are used as arguments for the MsgBox function. The third argument of the MsgBox function is title. as shown earlier in Figure 5. as it allows you to create procedures that don’t . use the vbDefaultButton1 setting instead.(Example 2) 3. you make your procedure easier to understand for yourself and others who may work with this procedure in the future. the question variable stores the text of your message. it’s very handy. you see the result displayed. myButtons End Sub In the above subroutine. Excel removes the MsgBox from the screen. It’s the default button for this dialog box. While this is also an optional argument. Add a new module to the ProcAndFunctions (Practice_Excel05. as in the following: myButtons = 4 + 32 + 256 However. Activate the Sample7 module and enter the MsgYesNo subroutine shown below.Notice that the No button is selected. Nothing happens because your procedure does not have any more instructions following the MsgBox function.

and 55 is the context topic you want to use. you must precede the value of each argument with its name: MsgBox title:=myTitle. Suppose HelpX.” Notice that the arguments are listed in the order determined by the MsgBox function. If you don’t specify the value for the title argument. When you use the helpfile argument. This argument indicates which help subject in the specified help file you want to display. Visual Basic displays the default text. myTitle End Sub The text for the title argument is stored in the variable myTitle. Using this argument. you can set the title bar of your message box to any text you want. The helpfile argument indicates the name of a special help file that contains additional information you may want to display to your VBA procedure user. To include this information in your MsgBox function. buttons:=myButtons The last two optional arguments—helpfile and context—are used by programmers who are experienced with using help files in the Windows environment. you would use the . If you would like to list the arguments in any order. When you specify this argument. “Microsoft Excel.provide visual clues to the fact that you programmed them with Microsoft Excel. you must also use the context argument.” The following MsgYesNo2 procedure demonstrates the use of the title argument: Sub MsgYesNo2() Dim question As String Dim myButtons As Integer Dim myTitle As String question = "Do you want to open a new workbook?" myButtons = vbYesNo + vbQuestion + vbDefaultButton2 myTitle = "New workbook" MsgBox question. Suppose you want the MsgYesNo procedure to display in its title the text “New workbook.hlp is the help file you created. prompt:=question. the Help button will be added to your message box. myButtons.

broken down into several lines with the line continuation character. _ prompt:=question _ buttons:=mybuttons _ helpFile:= "HelpX. To do this.2 shows values that the MsgBox function returns. Hands-On 5. Values returned by the MsgBox function Let’s revise the MsgYesNo2 procedure to show which button the user has chosen. clicking the OK button or pressing the Enter key removes the message box from the screen. your procedure should detect which button was pressed. However. Table 5. _ context:=55 The above is a single VBA statement. you must save the result of the message box in a variable.12. when the message box has more than one button. Using a Built-in MsgBox Function with Arguments (Example 3) . Returning Values from the MsgBox Function When you display a simple message box dialog with one button.2.following instruction: MsgBox title:=mytitle. Table 5.hlp".

6). myButtons. myButtons. MsgBox Function—With or Without Parentheses? Use parentheses around the MsgBox function’s argument list when you want to use the result returned by the function. Activate the Sample7 module and enter the MsgYesNo3 subroutine as shown below: Sub MsgYesNo3() Dim question As String Dim myButtons As Integer Dim myTitle As String Dim myChoice As Integer question = "Do you want to open a new workbook?" myButtons = vbYesNo + vbQuestion + vbDefaultButton2 myTitle = "New workbook" myChoice = MsgBox(question. When you run the MsgYesNo3 procedure. myTitle) 2. When you click on the Yes button. myTitle) MsgBoxmyChoice End Sub In the above procedure. the number 7 is displayed. By listing the function’s arguments without parentheses. you tell Visual Basic that you want to ignore the function’s . a two-button message box is displayed. When you click the No button.1. the statement MsgBoxmyChoice displays the number 6. In the next chapter. we assigned the result of the MsgBox function to the variable myChoice. you will learn how to make your procedure carry out a task depending on a button’s selection (see Hands-On 6. Run the MsgYesNo3 procedure. Notice that the arguments of the MsgBox function are now listed in parentheses: myChoice = MsgBox(question.

This dialog box has two buttons—OK and Cancel. context]) The first argument. One twip is equivalent to approximately 0. The xpos argument determines the horizontal position of the dialog box from the left edge of the screen. All of the remaining InputBox arguments are optional. ypos] [. the empty edit box is displayed. The default value is “Microsoft Excel. the function returns the empty string (“”). prompt. title.0007 inches. Now that you know the meaning of the InputBox function’s arguments. The last two arguments. The second argument. Both xpos a nd ypos are measured in special units called twips. let you specify the exact position where the dialog box should appear on the screen. If you omit these arguments. The ypos argument determines the vertical position from the top of the screen. is the text message that you want to display in the dialog box. title] [. If you omit this argument. are used in the same way as the corresponding arguments of the MsgBox function discussed earlier in this chapter. helpfile. When you select Cancel. Long text strings can be entered on several lines by using the Chr(13) or Chr(10) functions (see examples of using the MsgBox function earlier in this chapter). When you click OK.” The third argument of the InputBox function. the dialog box is centered horizontally. Using the InputBox Function The InputBox function displays a dialog box with a message that prompts the user to enter data. the InputBox function returns the information entered in the text box. you will want to use the function’s result when the MsgBox contains more than one button. helpfile and context. If you omit this argument. Most likely. xpos] [. The syntax of the InputBox function is as follows: InputBox(prompt [.result. allows you to change the default title of the dialog box. the dialog box is positioned vertically approximately one-third of the way down the screen. . allows the display of a default value in the text box. let’s look at some examples of using this function. xpos and ypos. When omitted. default] [. the box appears in the middle of the current window. default. The following two arguments.

As with the MsgBox function. etc. if you plan on using the data entered by the user in the dialog box. A dialog box generated by the Informant subroutine. Type the Informant2 procedure shown below to assign the result of the InputBox function to the variable town: . Writing a Procedure with the Built-in InputBox Function (Example 1) 1. FIGURE 5. The input prompt is displayed on two lines. 3.Hands-On 5..9. 2. as shown in Figure 5. Boston. Great Falls.g. Add a new module to the ProcAndFunctions (Practice_Excel05. you should store the result of the InputBox function in a variable.9.)" End Sub The above procedure displays a dialog box with two buttons.xlsm) project and change the module’s name to Sample8.13. Activate the Sample8 module and enter the Informant subroutine shown below: Sub Informant() InputBox prompt:= "Enter your place of birth:" &Chr(13) _ &" (e.

". 4. What will happen if you enter a number instead of the name of a town? . etc."Your response" End Sub Notice that this time the arguments of the InputBox function are listed within parentheses. modify the InputBox function in the Informant2 procedure as follows: town = InputBox(myPrompt. the dialog box generated by this function always appears in the same area of the screen. you can declare the input box title as a constant. you won’t have to remember to place a comma in the place of each omitted argument. When you run a procedure using the InputBox function. Great Falls.. . Visual Basic will use the number 1 as the value of the default argument. as explained earlier. myTitle) MsgBox"You were born in"& town &". The Informant2 subroutine uses a constant to specify the text to appear in the title bar of the dialog box. myTitle. ypos:=200). 1. you must supply the xpos and ypos arguments. . To display the dialog box in the top left-hand corner of the screen. Boston. To change the location of the dialog box. if you’d rather use a variable. title:=myTitle. However. The next two arguments determine the horizontal and vertical position of the dialog box. If you omit the second comma after the myTitle argument. Because the constant value remains the same throughout the execution of your procedure. Parentheses are required if you want to use the result of the InputBox function later in your procedure. If you precede the values of arguments by their names (for example. The second comma marks the position of the omitted default argument.g. xpos:=1.Sub Informant2() Dim myPrompt As String Dim town As String ConstmyTitle = "Enter data" myPrompt = "Enter your place of birth:" &Chr(13) _ &"(e.)" town = InputBox(myPrompt. prompt:=myPrompt. 200) Notice that the argument myTitle is followed by two commas. you still can.

Visual Basic is capable of converting values from one data type to another. The InputBox function itself does not provide a facility for data validation. If the user enters a number.14. Activate the Sample8 module in the ProcAndFunctions(Practice_Excel05. Determining and Converting Data Types The result of the InputBox function is always a string.Because users often supply incorrect data in an input dialog box. To validate user input. Let’s try out a procedure that suggests what type of data the user should enter by supplying a default value in the InputBox dialog.xlsm) project and enter the following AddTwoNums procedure: Sub AddTwoNums() Dim myPrompt As String Dim value1 As String Dim value2 As Integer . Hands-On 5. your procedure must verify that the data the user entered can be used in further data manipulations. the string value the user entered should be converted to a numeric value before your procedure can use this number in mathematical computations. Refer to Chapter 4 for more information about using the VarType function to determine the data type of a variable and common data type conversion functions. you must learn additional VBA instructions that are presented in the next chapter. Writing a Procedure with the Built-in InputBox Function (Example 2) 1.

you . To suggest that the user enter a specific type of data.” the dialog box displays a text string defined by the contents of the myTitle constant. 0) value2 = 2 mySum = value1 + value2 MsgBox "The result is "&mySum& _ " (" & value1 &" +" &CStr(value2) +")".Dim mySum As Single ConstmyTitle = "Enter data" myPrompt = "Enter a number:" value1 = InputBox(myPrompt. supply any number when prompted.Notice that this dialog box has two special features that are obtained by using the InputBox function’s optional title and default arguments."Total" End Sub The AddTwoNums procedure displays the dialog box shown in Figure 5. value1 = InputBox(myPrompt. Once the user provides the data and clicks OK.10. FIGURE 5. 0) 2. The zero entered as the default value in the edit box suggests that the user enter a number instead of text. the user’s input is assigned to the variable value1. Run the AddTwoNums procedure.10. myTitle. Instead of the default title"Microsoft Excel. and then click OK. _ vbInformation. myTitle.

By doing this you will save you time by not having to type the title text more than once.may want to provide a default value in the edit box. Visual Basic understands the need for conversion. Notice that the value2 variable has to be converted from Integer to String data type using the CStr function in order to display it in the message box: MsgBox"The result is "&mySum& _ " (" & value1 &" +" &CStr(value2) +")". Visual Basic goes to work behind the scenes to perform the data type conversion. Because the value1variable’s data type is String. Avoid the Type Mismatch Error . 3. prior to using this variable’s data in the computation. Recall from Chapter 4 that this number represents the String data type. You can check the data type easily if you follow the above instruction in the procedure code with this statement: MsgBoxVarType(value1) When Visual Basic runs the above line. Without it. The data type of the variable value1 is String. The statement mySum = value1 + value2 adds the value stored in the value2 variable to the user’s input and assigns the result of the calculation to the variable mySum."Total" Define a Constant To ensure that all the title bars in a particular VBA procedure display the same text. the two incompatible data types (String and Integer) would generate a Type mismatch error. assign the title text to a constant. it will display a message box with the number 8. The procedure ends with the MsgBox function displaying the result of the calculation and showing the user how the total was derived. _ vbInformation.

as shown in Figure 5. you will get the Type mismatch error when Visual Basic tries to execute the following line of code: mysum = value1 + value2 To avoid the Type mismatch error.11.If you attempt to run the AddTwoNums procedure in previous versions of Microsoft Excel (prior to version 2000). Visual Basic will display two occurrences of InputBox—one in the Excel library and the other one in the VBA library. use the built-in CSng function to convert a string stored in the value1 variable to a Single type number. there is also the Excel InputBox method. . If you activate the Object Browser window and type “inputbox” in the search box and then press Enter. Write the following statement: mysum = CSng(value1) + value2 Using the InputBox Method In addition to the built-in InputBox VBA function.

11.FIGURE 5. . Don’t forget to use the Object Browser when researching Visual Basic functions and methods. The InputBox method available in the Microsoft Excel library has a slightly different syntax than the InputBox function that was covered earlier in this chapter.

Its syntax is: expression. Note that one point equals 1/72 inch. Writing a VBA Procedure with the Excel InputBox Method . [default]. Hands-On 5. This value is obtained by adding up the values for a number (1) and a string (2). The InputBox method is quite useful for VBA procedures that require a user to select a range of cells in a worksheet. Let’s look at an example procedure that uses the Excel InputBox method. and default is a value that will appear in the text box when the dialog box is initially displayed.3. as shown in Table 5. the InputBox method will return text.3. [type]) All bracketed arguments are optional. Table 5.3. type. [left]. The last argument of the InputBox method. The arguments helpfile and helpcontextID identify the name of the help file and the specific number of the help topic to be displayed when the user clicks the Help button. If you omit this argument. [helpcontextID]. [title]. The left and top arguments specify the position of the dialog box on the screen.15. Data types returned by the InputBox method You can allow the user to enter a number or text in the edit box if you use 3 for the type argument. The values for these arguments are entered in points. The prompt argument is the message to be displayed in the dialog box. The values of the type argument are shown in Table 5.InputBox(prompt. _ [helpfile]. specifies the return data type. title is the title for the dialog box. [top].

Notice the keyword Set before the name of the variable: Set newRange = Application.00" newRange.NumberFormat = "0. In the Sample8 module.InputBox(prompt:=tellMe. When the user highlights the cells.NumberFormat = "0. enter the following WhatRange procedure: Sub WhatRange() Dim newRange As Range Dim tellMe As String tellMe = "Use the mouse to select a range:" Set newRange = Application.InputBox(prompt:=tellMe. . The last instruction selects the range of cells that the user highlighted.00" changes the format of the selected cells. Visual Basic displays a dialog box prompting the user to select a range of cells in the worksheet.Select End Sub The WhatRange procedure begins with a declaration of an object variable —newRange.1. _ Title:= "Range to format". 3. Run the WhatRange procedure. Close the Object Browser window if you opened it before. The range of cells that the user selects is assigned to the object variable newRange. object variables point to the location of the data.Type:=8) newRange. Type:=8) The Type argument (Type:=8) enables the user to select any range of cells. As you recall from Chapter 4. the next instruction: newRange. 2. _ Title:= "Range to format".

Because you don’t want to select anything when you cancel . The selected range is now formatted.12. Visual Basic displays an error message—"Object Required. 5. click OK in the dialog box. Rerun the procedure.” When you click the Debug button in the error dialog box. Using Excel’s InputBox method. FIGURE 5. when you click the Cancel button or press Esc. The number should appear formatted with two decimal places.4. Figure 5. When you’re done selecting cells. you can get the range address from the user.12 shows how Visual Basic enters the selected range reference in the edit box as you drag the mouse to select the cells. The WhatRange procedure works fine if you click OK after selecting a cell or a range of cells. To check this out. click Cancel. Use the mouse to select any cells you want. enter a whole number in any of the selected cells. and when the dialog box appears. 6. Visual Basic will highlight the line of code that caused the error. Unfortunately.

NumberFormat = "0. 7. and click Cancel as soon as the input .the dialog box. you will find other examples of trapping errors in your VBA procedures. Type:=8) newRange. Using a special statement. The statements placed between On Error GotoVeryEnd and the VeryEnd labels are ignored. as shown in Step 8 below.InputBox(prompt:=tellMe. 8. On Error GoTolabelname. _ Title:= "Range to format". you must find a way to ignore the error that Visual Basic displays. Run the modified WhatRange2 procedure. In Chapter 11. you can take a detour when an error occurs.00" newRange. except for a Visual Basic keyword. Choose Run | Reset to cancel the procedure you were running. Labelname can be any word you want. When Visual Basic encounters the error. Modify the WhatRange procedure so it looks like the WhatRange2 procedure shown below: Sub WhatRange2() Dim newRange As Range Dim tellMe As String On Error GoToVeryEnd tellMe = "Use the mouse to select a range:" Set newRange = Application. Visual Basic will jump to the specified label. it jumps to the VeryEnd label placed at the end of the procedure.Select VeryEnd: End Sub Notice that this time the procedure does not generate the error when you cancel the dialog box. If an error occurs. This instruction has the following syntax: On Error GoTolabelname This instruction should be placed just below the variable declaration lines. 9.

you should use a structured approach. you do this by creating a master procedure and one or more subordinate procedures. It may also call functions. it may be difficult to maintain its many lines of code. The master procedure can call the required subroutines and pass arguments to them. and functions. In VBA. Sub AboutUser() Dim fullName As String Dim firstName As String Dim lastName As String Dim space As Integer . The last statement displays the user’s last name followed by a comma and the first name. and modify. this procedure will be broken down into several tasks to demonstrate the concept of using master procedures. subprocedures. you declare them with the Sub keyword. you simply break a large problem into small problems that can be solved one at a time. Subroutines and Functions: Which Should You Use? USING MASTER PROCEDURES AND SUBPROCEDURES When your VBA procedure gets larger. As you read further. The following example shows the AboutUser procedure.box appears. which requests the user’s first and last names and then extracts the first and last names from the full name string. understand. When you create a structured program. To make your program easier to write. Because both master procedures and subordinate procedures are subroutines.

Len(fullName) space) ' display last name. Add a new module to your current VBA project and rename it Sample9. let’s see how you can accomplish each task. first name MsgBoxlastName&". full As String . Enter the following AboutUserMaster procedure in the Sample9 module window: Sub AboutUserMaster() Dim first As String." &firstName End Sub The AboutUser procedure can be divided into the following smaller tasks: Now that you know what tasks you should focus on."") firstName = Left(fullName. Hands-On 5. Writing a Master VBA Procedure 1. last As String. space .1) lastName = Right(fullName. 2.' get input from user fullName = InputBox("Enter first and last name:") ' get first and last name strings space = InStr(fullName.16.

last) End Sub The master procedure shown above controls the general flow of your program by calling appropriate subprocedures and functions.Call GetUserName(full) first = GetFirst(full) last = GetLast(full) Call DisplayLastFirst(first. The first statement. the fullName parameter receives the same value—an empty string (“”). Enter the following GetUserName subroutine: Sub GetUserName(fullName As String) fullName = InputBox("Enter first and last name:") End Sub The procedure GetUserName demonstrates two very important Visual Basic programming concepts: how to pass arguments to a subprocedure and how to pass values back from a subprocedure to a calling procedure. Although you are not required to use the Call keyword when calling a procedure. Notice that the name of the subprocedure is preceded by the Call statement. Because the variable full is not assigned any value prior to the execution of the Call statement. . A value assigned to a parameter is passed back to the matching argument after the subprocedure is executed. when Visual Basic returns to the master procedure. In the master procedure (see Step 2). The argument list must be enclosed in parentheses. The procedure begins with the declaration of variables. Therefore. When Visual Basic displays the dialog box and gets the user’s last name. you called the GetUserName procedure and passed it one argument: the variable full. the full variable will contain the user’s last name. it has the value of an empty string (“”). calls the GetUserName subroutine (see Step 3) and passes it an argument—the contents of the full variable. Call GetUserName(full). you must use it when the call to the procedure requires arguments. this name is assigned to the fullName parameter. Because at the time Visual Basic called the GetUserName subprocedure the variable full contained an empty string. This variable is received by a fullName parameter declared in the GetUserName subprocedure’s Sub statement. 3.

The next statement uses the VBA built-in function InStr to return the position of a space character (“”) in the fullName string. it places the result in the variable first. space . passes the value of the full variable to the GetFirst function."") GetLast = Right(fullName. Finally. the function begins with a declaration of a local variable—space. The result of the function (user’s first name) is then assigned to the function’s name."") GetFirst = Left(fullName. This value is received by the function’s parameter—fullName. 5.1) End Function The second statement in the master procedure (see Step 2). When Visual Basic returns to the master procedure. last = . the Left function is used to extract the specified number of characters (space – 1) from the left side of the fullName string. you must find the location of the space separating the first name and last name. Therefore. The length of the first name is one character less than the value stored in the variable space.Arguments passed to a subprocedure are received by parameters. Enter the following GetLast function procedure: Function GetLast(fullName As String) Dim space As Integer space = InStr(fullName. The obtained number is then assigned to the variable space. different names may be used for an argument and its corresponding parameter. To extract the first name from the user-provided full name string. first = GetFirst(full). 4. Enter the following GetFirst function procedure: Function GetFirst(fullName As String) Dim space As Integer space = InStr(fullName. Len(fullName) space) End Function The third statement in the master procedure (see Step 2). Although the parameter’s data type must agree with the data type of the matching argument. Notice that the parameter name (fullName) is followed by the declaration of the data type (As String).

and upon returning to the master procedure. or expression that is passed to a subprocedure. Enter the following DisplayLastFirst subroutine: Sub DisplayLastFirst(firstName As String. passes the value of the full variable to the GetLast function. Arguments versus Parameters An argument is a variable. last). 6. A parameter is simply a variable that receives a value passed to a subprocedure. This function’s purpose is to extract the user’s last name from the usersupplied fullName string. lastName As String) MsgBoxlastName & ". The GetLast function uses the built-in Len function to calculate the total number of characters in the fullName string. The Right function extracts the specified number of characters (Len(fullName) – space) from the right side of the fullName string. constant. calls the DisplayLastFirst subroutine and passes two arguments to it: first and last. 7. Call DisplayLastFirst(first. the DisplayLastFirstsubprocedure is declared with two matching parameters—firstName and lastName. Advantages of Using Subprocedures . it is stored in the variable last. Run the AboutUserMaster procedure.GetLast(full). The DisplayLastFirstsubprocedure then displays the message box showing the user’s last name followed by the comma and the first name. Recall that different names can be used for arguments and their corresponding parameters. To receive these arguments. The obtained string is then assigned to the function name." & firstName End Sub The fourth statement in the master procedure (see Step 2).

Chapter 6 introduces you to decision-making. with the help of parameters. you should be able to create some custom functions of your own that are suited to your specific needs. . While you can create subroutines by recording or typing code directly into the Visual Basic module. You learned how to pass arguments to functions and determine the data type of a function’s result. subprocedures can pass values back to the calling procedures. CHAPTER SUMMARY In this chapter. function procedures cannot be recorded because they can take arguments. You should also be able to interact easily with your procedure users by employing the MsgBox and InputBox functions as well as the Excel InputBox method. You must write them manually. Several people can work on individual subprocedures that constitute a larger procedure. Finally. A task performed by a subprocedure can be used by other procedures. After working through this chapter. You will learn how to change the course of your VBA procedure based on the results of the conditions that you supply. you learned how. and Optional keywords. ByRef. Each subprocedure can be tested individually before being placed in the main program. You also saw how problems can be broken into simpler and smaller tasks to make your programs easier to understand. you learned the difference between subroutine procedures that perform actions and function procedures that return values.It’s easier to maintain several subprocedures than one large procedure. You increased your repertoire of VBA keywords with the ByVal. You saw examples of function procedures called from a worksheet and from another Visual Basic procedure.

In this part of the book. . it does not allow you to incorporate complex logic into your program.Part 2 Controlling Program Execution Chapter 6 Decision Making with VBA Chapter 7 Repeating Actions in VBA While the Excel macro recorder can get you started with VBA. you’ll find out how decisions and looping enable you to control program flow and create useful VBA procedures and functions.

Relational operators in VBA .1. offers special statements that allow you to include decision points in your own procedures.” In programming. Table 6.1. all decisions are based on supplied answers. Conditional statements are often referred to as “control structures. or a combination of both. Only “yes” or “no” answers are allowed. it evaluates the expression to determine whether it is true or false. you will learn how to use VBA conditional statements to alter the flow of your program. Other decisions require that we weigh two or more options or even plan several tasks ahead. you might answer “maybe” or “perhaps. In programming.” as they give you the ability to control the flow of your VBA procedure by skipping over certain statements and “branching” to another part of the procedure. But what is decision making? Suppose someone approaches you with the question.” If you’re undecided or simply don’t care.Chapter 6 DECISION MAKING WITH VBA We make thousands of decisions every day. “Do you like the color red?” After giving this question some thought. Some decisions are spontaneous: We make them automatically without having to stop and think. you’ll answer “yes” or “no. one of the logical operators listed in Table 6.2. like other programming languages. If the answer is negative. A conditional expression is an expression that uses one of the relational operators listed in Table 6. If the answer is positive. RELATIONAL AND LOGICAL OPERATORS You make decisions in your VBA procedures by using conditional expressions inside the special control structures. the procedure executes another block of instructions or simply doesn’t do anything. Visual Basic for Applications. When Visual Basic encounters a conditional expression in your program. the procedure executes a specified block of instructions. In this chapter. you must be decisive.

EntireRow. as shown below: . Visual Basic will ignore the statement following the Then keyword. Logical operators in VBA IF . first check if the active cell is blank. You can use the following structure: If condition Then statement For example. Suppose you want to choose an action depending on a condition. Although you could add other statements on the same line by separating them with colons.2. Sometimes you may want to perform several actions when the condition is true.Delete If the active cell is not blank. . your code will look clearer if you use the multiline version of the If…Then statement. . go ahead and delete the entire row that contains that cell: If ActiveCell = "" Then Selection. If the result of the test is true.Table 6. THEN STATEMENT The simplest way to get some decision making into your VBA procedure is to use the If…Then statement. to delete a blank row from a worksheet.

Value > 50 Then MsgBox "The exact value is " & ActiveCell.Address & ": " & ActiveCell. Please note files for the “Hands-On” project may be found on the companion CDROM. Evaluating Conditions in the Immediate Window 1. Notice that the block If…Then statement must end with the keywords End If.1.Value > 50. the statements between the Then and the End If keywords are not executed if the value of the active cell is less than or equal to 50. Hands-On 6. 3. Open a new Microsoft Excel workbook. Select any cell in a blank worksheet and enter 50.Value Debug. Let’s try to evaluate the following condition:ActiveCell.If condition Then statement1 statement2 statementN End If For example.Print ActiveCell. . How does Visual Basic make a decision? It evaluates the condition it finds between the If…Then keywords. 2.Value End If In this example. Switch to the Visual Basic Editor window. to perform some actions when the value of the active cell is greater than 50. you can write the following block of instructions: If ActiveCell.

Insert a new module in the Decisions (Practice_Excel06. Hands-On 6. if there is one. let’s try the If… Then statement in a VBA procedure. 5. the test returns true. and press Enter when you’re done: ? ActiveCell. In the IfThen module. When the result of the test is false. 6. Now change the operator to less than or equal to.4. Activate the Immediate window. Open a new workbook and C:\Excel2013_ByExample\Practice_Excel06. Writing a VBA Procedure with a Simple If…Then Statement 1. 3. enter the following procedure: Sub SimpleIfThen() Dim weeks As String . 4. Close the Immediate window.Value < = 50 This time.Value > 50 When you press Enter.xlsm) project and rename this module IfThen. It will simply go on to read the next line of your procedure. Enter the following statement. Switch to the Visual Basic Editor screen and rename the VBA project Decisions. 7.2. Now that you know how Visual Basic evaluates conditions. the procedure will end. and Visual Basic will jump to whatever statement or statements it finds after the Then keyword. Visual Basic will not bother to read the statement following the Then keyword in your code. and have Visual Basic evaluate the following condition: ? ActiveCell.xlsm. If there are no more lines to read. save it as 2. Visual Basic writes the result of this test—false.

Let’s see whether it can also call itself. If the result of the comparison is true (that is. and as soon as he clicks the OK button in the message box.” 5. The user will be able to keep on guessing for a long time. In fact. 7. If he clicks Cancel.” When the procedure is executed. Rerun the SimpleIfThen procedure and enter the number 52. When you enter the correct answer. Enter the following instruction on a separate line before the End Sub keywords: If weeks = 52 Then MsgBox "Congratulations!" 8. The variable’s value is then compared to the number 52. Visual Basic does nothing. Run the SimpleIfThen procedure again and enter 52. if the value stored in the variable weeks is not equal to 52). a VBA procedure can call another procedure. Visual Basic does not execute the statement MsgBox “Try Again. When you enter the correct number of weeks. he won’t be able to exit the procedure gracefully until he supplies the correct answer. It would be nice to display a message when the user guesses right. he will have to deal with the unfriendly error message “Type mismatch. the input box will appear again and he will get another chance to supply the correct answer. the statement to the right of the Then keyword is ignored if the result from evaluating the supplied condition is false. 6. If the user enters the incorrect answer. Run the SimpleIfThen procedure and enter a number other than 52. Modify the first If statement in the SimpleIfThen procedure as follows: If weeks < > 52 Then MsgBox "Try Again": SimpleIfThen We added a colon and the name of the SimpleIfThen procedure to the end of the existing If…Then statement. The procedure simply ends. he will see a message. "Quiz") If weeks < > 52 Then MsgBox "Try Again" End Sub The SimpleIfThen procedure stores the user’s answer in the variable named weeks. 9. Visual Basic will display the message “Try Again.” You saw in the previous chapter how to use the On . As you recall.weeks = InputBox("How many weeks are in a year?".

Run the SimpleIfThen procedure a few times by supplying incorrect answers. In the first example. Visual Basic sets the value of alpha to true and beta to false when the secretCode variable is equal to 01W01. at least temporarily until you learn more about error handling in Part IV. The single-line format is good for short or simple statements like: If secretCode < > 01W01 Then MsgBox "Access denied" Or If secretCode = 01W01 Then alpha = True : beta = False Here. you may want to revise your SimpleIfThen procedure as follows: Sub SimpleIfThen() Dim weeks As String On Error GoTo VeryEnd weeks = InputBox("How many weeks are in a year:". and beta are the names of variables. In the second example. The multiline If…Then statement is clearer when there are more statements to be executed when the condition is true or when the statement to be executed is extremely long. as in the following example: . "Quiz") If weeks < > 52 Then MsgBox "Try Again": SimpleIfThen If weeks = 52 Then MsgBox "Congratulations!" VeryEnd: End Sub 10. alpha. secretCode. Notice that the second statement to be executed is separated from the first by a colon. Two Formats for the If…Then Statement The If…Then statement has two formats—single line and multiline. The error trap that you added to your procedure allows the user to quit guessing without having to deal with the ugly error message. For now.Error GoTo labelname statement to go around the error. Visual Basic displays the message “Access denied” if the value of secretCode is not equal to 01W01.

Move after:= Sheets(Worksheets. . This statement. can take more than one condition. Here’s the syntax: If condition1 OR condition2 Then statement The OR operator is more flexible. Here’s the syntax with the AND operator: If condition1 AND condition2 Then statement In the above syntax. both condition1 and condition2 must be true for Visual Basic to execute the statement to the right of the Then keyword. Visual Basic examines the active sheet name. For example: If sales = 10000 AND salary < 45000 Then SlsCom = Sales * 0.Count) End If Here. both conditions must be true before Visual Basic can calculate the sales commission (SlsCom). however. the active sheet is moved to the last position in the workbook.Name = "Sheet1" is true. If it is Sheet1. To specify multiple conditions in an If…Then statement. If either of these conditions is false. use the logical operators AND and OR (listed in Table 6.If ActiveSheet. and Visual Basic proceeds to execute the line following the Then keyword. As a result. the condition ActiveSheet. you should use the OR operator. When it’s good enough to meet only one of the conditions. or both are false. Only one of the conditions has to be true before Visual Basic can execute the statement following the Then keyword.07 In this example: Condition1 sales = 10000 Condition2 salary < 45000 When AND is used in the conditional expression.2 at the beginning of this chapter). DECISIONS BASED ON MORE THAN ONE CONDITION The SimpleIfThen procedure that you worked with earlier evaluated only a single condition in the If…Then statement.Name = "Sheet1" Then ActiveSheet. Visual Basic ignores the statement after Then.

Let’s look at this example: If dept = "S" OR dept = "M" Then bonus = 500 In the above example.00.Value = strmsg1 & 50 units & " unit(s). Writing a VBA Procedure with Multiple Conditions 1. Enter the following procedure in the IfThen module of the Decisions (Practice_Excel06." .Value price = Range("B2").00" units = Range("B1"). Visual Basic assigns 500 to the bonus variable. The IfThenAnd procedure demonstrates the use of the AND operator.Value = "The rebate is: $" & rebate End If If price = 7 AND units < 50 Then Range("A4"). Now let’s look at a complete procedure example.xlsm) project: Sub IfThenAnd() Dim price As Single Dim units As Integer Dim rebate As Single Const strmsg1 = " To get a rebate you must " &_ "buy an additional " Const strmsg2 = "Price must equal $7. Suppose you can get a 10% discount if you purchase 50 units of a product. if at least one condition is true. each priced at $7. If both conditions are false.1 Range("A4"). Visual Basic ignores the rest of the line.Value If price = 7 AND units >= 50 Then rebate = (price * units) * 0. Hands-On 6.3.

5. ." End If End Sub The IfThenAnd procedure shown above has four If…Then statements that are used to evaluate the contents of two variables: price and units. Because the IfThenAnd procedure is based on the data entered in worksheet cells.End If If price < > 7 AND units >= 50 Then Range("A4"). press Shift+I to assign the shortcut key Ctrl+Shift+I to your macro. and then click OK to exit the Macro Options dialog box. select the IfThenAnd macro and click the Options button. Enter the following data in a worksheet: 7. In the Macro dialog box. 2. it’s more convenient to run it from the Microsoft Excel window.Value = strmsg2 End If If price < > 7 AND units < 50 Then Range("A4"). 4.Value = "You didn’t meet the criteria. 3. 6. The AND operator between the keywords If…Then allows more than one condition to be tested. Press Ctrl+Shift+I to run the IfThenAnd procedure. and choose Developer | Macros. Click Cancel to close the Macro dialog box. all conditions must be true for Visual Basic to run the statements between the Then…End If keywords. With the AND operator. While the cursor is blinking in the Shortcut key box. Switch to the Microsoft Excel application window.

IF BLOCK INSTRUCTIONS AND INDENTING To make the If blocks easier to read and understand. if your procedure needs to take one action when the condition is true and another action when the condition is false? By adding the Else clause to the simple If…Then statement. and the statement following the Else clause is executed if the condition is false. The If…Then…Else statement has two formats—single line and multiline. For example: If Sales > 5000 Then Bonus = Sales * 0. you can direct your procedure to the appropriate statement depending on the result of the test. The single-line format is as follows: If condition Then statement1 Else statement2 The statement following the Then keyword is executed if the condition is true. Compare the following: In the If…Then block statement on the right. you can easily see where the block begins and where it ends.05 Else MsgBox "No Bonus" End If If the value stored in the variable Sales is greater than 5000. however. Visual Basic will calculate the bonus using the following formula: Sales * 0.05. use indentation. if the . However. IF…THEN…ELSE STATEMENT Now you know how to display a message or take an action when one or more conditions are true or false. a different If…Then statement is true.8. Change the values of cells B1 and B2 so that every time you run the procedure. What should you do.

variable Sales is not greater than 5000.4. If the condition is false. Let’s look at the complete procedure example.Name = "Sheet1" Then ActiveSheet. Writing a VBA Procedure with an If…Then…Else Statement ." Else MsgBox "This sheet name is not default. Here’s a code example that uses the above syntax: If ActiveSheet. it’s better to use the multiline format of the If…Then…Else statement: If condition Then statements to be executed if condition is True Else statements to be executed if condition is False End If Notice that the multiline (block) If…Then…Else statement ends with the End If keywords. Visual Basic will display the message “No Bonus. Visual Basic will execute the statements between Then and Else and ignore the statement between Else and End If.” The If…Then…Else statement should be used to decide which of the two actions to perform.Name = "My Sheet" MsgBox "This sheet has been renamed. When you need to execute more statements when the condition is true or false. Use the indentation shown in the previous section to make this block structure easier to read. Visual Basic will omit the statements between Then and Else and execute the statement between Else and End If." End If If the condition (ActiveSheet.Name = "Sheet1") is true. Hands-On 6.

xlsm) project. If the result of the test is true. 11/22/2013)" strmsg1 = "weekday" strmsg2 = "weekend" response = InputBox(question) myDate = Weekday(CDate(response)) If myDate >= 2 And myDate < = 6 Then MsgBox strmsg1 Else MsgBox strmsg2 End If End Sub The above procedure asks the user to enter any date.g. The day of the week constants are listed in Table 6. otherwise. The conditional test is performed to check whether the value of the variable myDate is greater than or equal to 2 ( >=2) and less than or equal to 6 (< =6). Finally. strmsg2 As String Dim myDate As Date question = "Enter any date in the format mm/dd/yyyy:" _ & Chr(13)& " (e. Enter the following WhatTypeOfDay procedure and then run it: Sub WhatTypeOfDay() Dim response As String Dim question As String Dim strmsg1 As String. .3. the program announces that it’s a weekend. 3.. The user-supplied string is then converted to the Date data type with the built-in CDate function. Change the module name to IfThenElse. the user is told that the supplied date is a weekday. Insert a new module into the Decisions (Practice_Excel06. 2.1. the Weekday function converts the date into an integer that indicates the day of the week. The integer is stored in the variable myDate.

In structured programming. Check the Visual Basic answers against your desktop or wall calendar. and loops. such as GoTo. Values returned by the built-in Weekday function 4. Loops are the subject of the next chapter. each time supplying a different date. decisions.3. Decisions allow you to execute specific statements based on a test of some condition. other logical statements. What Is Structured Programming? Structured programming requires that all programs have a modular design and use only three types of logical structures: sequences. Below are examples of structured and unstructured programs: . Loops make it possible to execute one or more statements repeatedly. Run the procedure from the Visual Basic window. as long as a specified condition is true. are not allowed. The code of a structured program is easy to follow—it flows smoothly from top to bottom without jumping around to specified labels. Run it a few times.Table 6. Sequences are statements that are executed one after another.

you may be tempted to use the GoTo statement.When you write your VBA procedure from scratch and your VBA procedure needs to jump from one line of a program to another. Don’t jump around.Formula = InputBox("Enter text or number:") Else .InputBox(prompt:=strmsg. You can easily arrive at the required destination in your procedure by using structured programming.Select If IsEmpty(ActiveCell) Then ActiveCell. Type:=8) cell. Here’s another practice procedure to demonstrate the use of the If…Then…Else statement: Sub EnterData() Dim cell As Object Dim strmsg As String On Error GoTo VeryEnd strmsg = "Select any cell:" Set cell = Application. Relying on GoTo statements for changing the course of your procedure leads to confusing code that is referred to as spaghetti code.

Visual Basic will jump to the instruction following the Else clause. The cell address is then assigned to the cell object variable.Offset(1. When you run this procedure and the input box prompts you to select a cell. IF…THEN…ELSEIF STATEMENT Quite often you will need to check the results of several different conditions. The selected cell address will appear in the edit box. and once the input is provided. Visual Basic will check the contents of the selected cell and jump to the true or false section of your procedure (the true section follows Then and the false section follows Else). Instead of: If IsEmpty(ActiveCell) Then you can use the following instruction: If ActiveCell. Recall that a variable is said to be initialized when it is assigned an initial value. To join a set of If conditions together. IsEmpty returns true if the variable is uninitialized. click any cell in the worksheet. Using the If… Then…ElseIf statement. Visual Basic treats it as a zero-length string (“”). 0).Value = "" Then If the active cell is empty. The IsEmpty is a built-in function that is used to determine whether a variable has been initialized. This statement prompts the user to enter text or number data. Here’s the syntax of the If…Then…Else statement: If condition1 Then . In this procedure. the statement following Then is executed.Select End If VeryEnd: End Sub The EnterData subroutine shown above prompts the user to select any cell. if the active cell is empty. the data is entered in the active cell. The If…Then…Else structure checks if the selected cell is empty.ActiveCell. you can supply more conditions to evaluate than is possible with the If…Then…Else statement discussed earlier. If the active cell is not empty. Click OK to exit the input box. you can use the ElseIf clause. This instruction will cause Visual Basic to select the next cell in the same column.

1). positive. Notice that the Else clause is not used. 1).Value = 0) is false. Let’s look at the following code example: If ActiveCell.Value = "positive" ElseIf ActiveCell.Offset(0.Value > 0 Then ActiveCell. negative) in the adjoining column.Value = 0 Then ActiveCell. The statements in the ElseIf clause are executed only if the condition in this clause is true. 1). If the result of the first condition (ActiveCell. The ElseIf clause always comes before the Else clause.Value = "zero" ElseIf ActiveCell. you can omit it if there are no actions to be executed when all conditions are false.Value < 0 Then ActiveCell. Visual Basic jumps to the next ElseIf statement and evaluates its condition .Offset(0.Offset(0.Value = "negative" End if This example checks the value of the active cell and enters the appropriate label (zero. Your procedure can include any number of ElseIf statements and conditions.statements to be executed if condition1 is True ElseIf condition2 Then statements to be executed if condition2 is True ElseIf condition3 Then statements to be executed if condition3 is True ElseIf conditionN Then statements to be executed if conditionN is True Else statements to be executed if all conditions are False End If The Else clause is optional.

Offset(0.Value = "zero" ElseIf ActiveCell. Insert a new module into the current VBA project.Offset(0. This keyboard shortcut .Value > 0). Open the Immediate window and type the following statement: Application. 1). Enter the following WhatValue procedure: Sub WhatValue() Range("A1"). Writing a VBA Procedure with an If…Then…ElseIf Statement 1.Value < 0 is evaluated. Hands-On 6. Visual Basic skips to the next ElseIf and the condition ActiveCell. Visual Basic runs the OnKey method that assigns the WhatValue procedure to the key sequence Ctrl+Shift+Y.Value > 0 Then ActiveCell.Value = "positive" ElseIf ActiveCell. Rename the module IfThenElseIf. "WhatValue" When you press Enter. 1). Let’s see how the If…Then…ElseIf statement works in a complete procedure. 3. 1).Value = 0 Then ActiveCell.(ActiveCell.Value = "negative" End If End Sub Because you need to run the WhatValue procedure several times to test each condition.Value < 0 Then ActiveCell. 2. let’s have Visual Basic assign a temporary keyboard shortcut to this procedure.5.Select If ActiveCell.Offset(0. 4. If the value is not greater than zero.OnKey "^+y".

” 9. Enter any text in cell A1 and press Ctrl+Shift+Y. Structures in which an If statement is contained inside another If block are referred to as nested If statements. Then press Ctrl+Shift+Y. Enter any number greater than zero in cell A1 and press Ctrl+Shift+Y. Because there are no more statements following the End If. Enter any number less than zero in cell A1 and press Ctrl+Shift+Y. this is not a satisfactory answer. Because this test returns true. Cell B1 now displays the word “positive. Visual Basic enters the word “negative” in cell B1. You may want to differentiate between positive numbers and text by displaying the word “text. NESTED IF…THEN STATEMENTS You can make more complex decisions in your VBA procedures by placing an If…Then or If…Then…Else statement inside another If…Then or If…Then… Else statement. To assign the shortcut key to a procedure. The following TestConditions procedure is a revised version of the WhatValue procedure created in the previous section. The second condition is true. so Visual Basic goes to examine the third condition. Type 0 (zero) in cell A1 and press Enter. This time. the first two conditions return false. 10.is only temporary—it will not work when you restart Microsoft Excel. 7.” However. use the Options button in the Macro dialog box accessed from Developer | Macros in the Microsoft Excel window.” To make the WhatValue procedure smarter. 8. the procedure ends. 5. Visual Basic calls the WhatValue procedure and enters “zero” in cell B1. Now switch to the Microsoft Excel window and activate Sheet2. 6. and because the result of this test is false. Visual Basic again calls the WhatValue procedure. Visual Basic’s response is “positive. you need to learn how to make more complex decisions by using nested If…Then statements. it jumps to the ElseIf statement. Visual Basic evaluates the first condition. so Visual Basic executes the statement following Then and skips over the next statements to the End If. The WhatValue procedure has been modified to illustrate how nested If…Then .

You can now clearly see that the procedure uses three If…Then blocks.Value = "positive" ElseIf ActiveCell.Value) Then If ActiveCell. the IsEmpty(ActiveCell) condition returns false. The first If block (in bold) checks whether the active cell is empty. 1). Notice that this is done .Value = "text" End If End If End Sub To make the TestConditions procedure easier to understand. 1).Value = 0 Then ActiveCell." Else If IsNumeric(ActiveCell. This statement is located just before the End Sub keywords.Offset(0.Offset(0.Select If IsEmpty(ActiveCell) Then MsgBox "The cell is empty.statements work. This (underlined) If… Then…Else statement is said to be nested inside the first If block (in bold).Offset(0. the message is displayed.Value > 0 Then ActiveCell. If this is true. each If…Then statement is shown with different formatting. 1).Value = "zero" ElseIf ActiveCell.Value < 0 Then ActiveCell. 1).Value = "negative" End If Else ActiveCell. Sub TestConditions() Range("A1"). This statement checks if the value of the active cell is a number.Offset(0. and Visual Basic skips over the Else part until it finds the matching End If. If the active cell is not empty. and Visual Basic runs the single underlined If block following the Else formatted in bold.

This outer statement contains two inner If statements (single and double underlined). it makes note of the value of testexpression. you can use the Select Case statement instead. However. The Case Else clause is optional. so Visual Basic jumps to the statement following the underlined Else and enters “text” in cell B1. the condition is false. Use it when you expect that there may be conditional expressions that return false. The first If block (in bold) is called the outer If statement. Here’s the logic behind the Select Case statement. When Visual Basic encounters the Select Case clause. In the Select Case statement. evaluating each condition and making the appropriate decision.with the help of another built-in function—IsNumeric. if the active cell contains a number. Visual Basic runs the double-underlined If block. Then it proceeds to test the expression following the first Case . If the value of the active cell is not a number. Visual Basic compares each expressionlist with the value of testexpression. The syntax of this statement is as follows: Select Case testexpression Case expressionlist1 statements if expressionlist1 matches testexpression Case expressionlist2 statements if expressionlist2 matches testexpression Case expressionlistN statements if expressionlistN matches testexpression Case Else statements to be executed if no values match testexpression End Select You can place any number of Case clauses to test between the keywords Select Case and End Select. SELECT CASE STATEMENT To avoid complex nested If statements that are difficult to follow.

Visual Basic jumps to the Case Else clause and executes the statements until it encounters the End Select keywords. 3. Visual Basic jumps to the statements following End Select and continues executing your procedure. Visual Basic executes the statements until another Case clause is encountered and then jumps to the End Select statement. 2. Insert a new module into the current VBA project. If the value of this expression (expressionlist1) matches the value stored in testexpression. Hands-On 6.6. Enter the following TestButtons procedure: Sub TestButtons() Dim question As String Dim bts As Integer Dim myTitle As String Dim myButton As Integer question = "Do you want to open a new workbook?" . In Chapter 5. however.clause. If none of the Case clauses contain the expression that matches the value stored in testexpression. the expression tested in the first Case clause does not match testexpression. If your procedure does not use Case Else and none of the Case clauses contain a value matching the value of testexpression. Notice that the Case Else clause is optional. You also learned that the result of the MsgBox function can be assigned to a variable. which allows you to display a message with one or more buttons. Let’s look at an example of a procedure that uses the Select Case statement. Rename the new module SelectCase. Using the Select Case statement. you can now decide which action to take based on the button the user pressed in the message box. Writing a VBA Procedure with a Select Case Statement 1. Visual Basic checks the value of each Case clause until it finds a match. you learned quite a few details about the MsgBox function. If.

The TestButtons procedure will work the same if you use the constants instead of button values: Select Case myButton Case vbYes Workbooks. _ title:=myTitle) Select Case myButton Case 6 Workbooks. Lastly. If the user clicks Yes. the variable myButton is assigned the vbYes constant or its corresponding value—6. If the user selects No. The value of the button selected by the user is assigned to the variable myButton. the appropriate Case statement is executed. or 2. and Cancel." End Select End Sub The first part of the TestButtons procedure displays a message with three buttons: Yes. _ buttons:=bts." Case Else MsgBox "You pressed Cancel.Add Case vbNo MsgBox "You can open a new book manually .Add Case 7 MsgBox "You can open a new book manually later. if Cancel is pressed. The Select Case statement checks the values supplied after the Case clause against the value stored in the variable myButton.bts = vbYesNoCancel + vbQuestion + vbDefaultButton1 myTitle = "New Workbook" myButton = MsgBox(prompt:=question. the variable myButton is assigned the constant vbNo or its corresponding value—7. No. the contents of the variable myButton will equal vbCancel. When there is a match.

Add Case vbNo MsgBox "You can open a new book manually later. such as whether the test expression is greater than.later." End Select 4. less than. The Is keyword lets you use a conditional expression in a Case clause." Case Else MsgBox "You pressed Cancel. listed in Table 6. The syntax for the Select Case clause using the Is keyword is shown below: Select Case testexpression Case Is condition1 statements if condition1 is True Case Is condition2 statements if condition2 is True Case Is conditionN statements if conditionN is True . each time selecting a different button.1. Using Is with the Case Clause Sometimes a decision is made based on a relational operator. or equal to. Simply revise the Select Case statement as follows: Select Case myButton Case vbYes Workbooks. Run the TestButtons procedure three times." Case vbCancel MsgBox "You pressed Cancel." End Select You can omit the Else clause.

just in case the variable you are testing has an unexpected value. Do this by using the To keyword between the values of expressions. Specifying a Range of Values in a Case Clause In the preceding example.End Select Although using Case Else in the Select Case statement isn’t required. the third Case clause is true. as in the following example: Select Case unitsSold Case 1 To 100 Discount = 0. let’s compare some numbers: Select Case myNumber Case Is < =10 MsgBox "The number is less than or equal to 10" Case 11 MsgBox "You entered eleven. and the only statement executed is the one between the Case Is >=100 and the Case Else clause.1 . you may want to specify a range of values in a Case clause. it’s always a good idea to include one. For example. The Case Else statement is a good place to put an error message." Case Is >=100 MsgBox "The number is greater than or equal to 100. you saw a simple Select Case statement that uses one expression in each Case clause." End Select Assuming that the variable myNumber holds 120. Many times.05 Case Is < = 500 Discount = 0." Case Else MsgBox "The number is between 12 and 99. however.

Visual Basic compares the value of the variable unitsSold with the conditional expression in the Case clauses.05 to the variable Discount. As you recall from Chapter 5. Visual Basic assigns the value 0. Visual Basic does not execute the associated statement Discount = 0.15 Case Is > 1000 Discount = 0.1. let’s use it in a function procedure. Writing a Function Procedure with a Select Case Statement 1. thus. Suppose a subroutine has to display a discount based on the number of units sold. Enter the following subroutine in the SelectCase module: Sub DisplayDiscount() Dim unitsSold As Integer Dim myDiscount As Single unitsSold = InputBox("Enter the number of units sold:") myDiscount = GetDiscount(unitsSold) . How about the second Case clause. Hands-On 6. The reason for this is that once Visual Basic locates a Case clause with a true condition. To get more practice with the Select Case statement. the condition in the first Case clause is true. Because unitsSold equals 99.Case 501 To 1000 Discount = 0.2 End Select Let’s analyze the above Select Case block with the assumption that the variable unitsSold currently holds the value 99. it doesn’t bother to look at the remaining Case clauses. You can get the number of units from the user and then run a function to figure out which discount applies. which is also true? Although it’s obvious that 99 is less than or equal to 500.7. The first and third Case clauses illustrate how to use a range of values in a conditional expression by using the To keyword. It jumps over them and continues to execute the procedure with the instructions that may be following the End Select statement. function procedures allow you to return a result to a subroutine.

Place the cursor anywhere within the code of the DisplayDiscount procedure and press F5 to run it.05) to the function name. as shown in the following code example: . The last statement displays the value of the retrieved discount in a message box.15 Case Is > 1000 GetDiscount = 0. entering values to test each Case statement. Because there are no more statements to execute inside the function procedure. Visual Basic assigns a 5% discount (0. it checks whether the value of the first Case clause expression matches the value stored in the unitsSold parameter.1 Case 501 To 1000 GetDiscount = 0. and then jumps to the End Select keywords. Enter the following function procedure: Function GetDiscount(unitsSold As Integer) Select Case unitsSold Case 1 To 200 GetDiscount = 0. Specifying Multiple Expressions in a Case Clause You may specify multiple conditions within a single Case clause by separating each condition with a comma. Run the procedure several times.05 Case Is < = 500 GetDiscount = 0.2 End Select End Function 3. When Visual Basic encounters the Select Case statement. The DisplayDiscount procedure passes the value stored in the variable unitsSold to the GetDiscount function. Visual Basic returns to the calling procedure—DisplayDiscount. If there is a match.MsgBox myDiscount End Sub 2. Here it assigns the function’s result to the variable myDiscount.

"June" Debug. "December" Debug. here are a few guidelines: If you want to supply only one condition." Case "July".Print myMonth & ": 1st Qtr. "February". If you need to decide which of two actions to perform. which were introduced in this chapter." Case "April". By testing the truth of a condition. the simple If…Then statement is the best choice.Print myMonth & ": 3rd Qtr. If you are wondering what kind of conditional statement you should use. "September" Debug. In other words. "May"." End Select Multiple Conditions with the Case Clause The commas used to separate conditions within a Case clause have the same meaning as the OR operator used in the If statement. You will see more nesting examples with the looping structures discussed in Chapter 7. CHAPTER SUMMARY Conditional statements. "November". The Case clause is true if at least one of the conditions is true.Select Case myMonth Case "January".Print myMonth & ": 2nd Qtr. Nesting means placing one type of control structure inside another control structure." Case "October". you can execute only certain lines. let you control the flow of your procedure. "March" Debug. line by line. instead of running your procedure from top to bottom.Print myMonth & ": 4th Qtr. . use the If…Then…Else statement. you can decide which statements should be run and which should be skipped over. "August".

This statement is more flexible and easier to comprehend than the If… Then…ElseIf statement. The next chapter teaches you how to perform the same steps over and over again.If your procedure requires two or more conditions. use the If…Then…ElseIf or Select Case statements. you may want to repeat the same actions for each cell in a worksheet or each sheet in a workbook. . If your procedure has a great number of conditions. use the Select Case statement. Some decisions have to be repeated. For example.

In programming. performing repetitive tasks is called looping. DO LOOPS: DO…WHILE AND DO…UNTIL Visual Basic has two types of Do loop statements that repeat a sequence of statements either as long as or until a certain condition is true. What Is a Loop? A loop is a programming structure that causes a section of program code to execute repeatedly. you may need to run the specified statements as long as a condition is true or until a condition becomes true. Not all decisions are easy. it’s time to get more complex. Sometimes you will need to perform a number of statements several times to arrive at a certain condition. VBA provides several structures to implement loops in your procedures: Do…While. Do…Until.Chapter 7 Repeating Actions in VBA Now ow that you’ve learned how conditional statements can give your VBA procedures decision-making capabilities. after you’ve reached the decision. For…Next. and While… Wend. you will learn how to loop through your code. On other occasions. This loop has the following syntax: Do While condition statement1 . The Do…While loop lets you repeat an action as long as a condition is true. In this chapter. however. For…Each. VBA has various looping structures that allow you to repeat a sequence of statements a number of times.

the statements inside the loop are run one by one until the Loop statement is encountered. Visual Basic will continue to execute the program with the first statement after the Loop keyword. The Loop statement tells Visual Basic to repeat the entire process again. Enter the following procedure in the DoLoops module: Sub ApplyBold() . it first checks the truth value of the condition. The decision is to apply bold formatting to any cell in a column. as long as the testing of the condition in the Do While statement is true. If the condition is true. 3. Please note files for the “Hands-On” project may be found on the companion CDROM. If the condition is false. save it as 2. Hands-On 7. In Chapter 6. you learned how to make a decision based on the contents of a cell. Let’s take it a step further and see how you can repeat the same decision for a number of cells.xlsm.statement2 statementN Loop When Visual Basic encounters this loop. as long as it’s not empty. Let’s now see how you can put the Do…While loop to good use in Microsoft Excel. Writing a VBA Procedure with a Do…While Statement (Example 1) 1. Insert a new module into the Repetition project and change its name to DoLoops. Open a new workbook and C:\Excel2013_ByExample\Practice_Excel07. the statements inside the loop are not executed. Switch to the Visual Basic Editor screen.1. and change the name of the new project to Repetition. 4.

the first test returns true. This process continues until the contents of cell A8 are examined.Do While ActiveCell. Because you have entered data in cell A1 and made this cell active (see Steps 5 to 6).Font.Offset(1. Visual Basic first evaluates the condition in the Do While statement—ActiveCell.2. So Visual Basic executes the statement ActiveCell. If the newly selected active cell is not empty. When you run the ApplyBold procedure. Hands-On 7. 0). so Visual Basic skips the statements inside the loop.Bold = True. Press Alt+F11 to switch to the Microsoft Excel application window. In the Macro dialog box. double-click the ApplyBold procedure (or highlight the procedure name and click Run). Visual Basic selects the cell in the next row (the Offset property is discussed in Chapter 3).Value < >"". Visual Basic returns to the Do While statement and again checks the condition. the procedure ends. Let’s look at another Do…While loop example. Writing a VBA Procedure with a Do…While Statement (Example 2) .Select Loop End Sub 5. 6. Choose Developer | Macros. Because there are no more statements to execute after the Loop keyword. then enter any data (text or numbers) in cells A1:A7. Because the statement that follows is the Loop keyword. 7.Font.Bold = True ActiveCell.Value < > "" ActiveCell. Next. The next example procedure demonstrates how to display today’s date and time in Microsoft Excel’s status bar for 10 seconds. activate Sheet1. The condition says: Perform the following statements as long as the value of the active cell is not an empty string (“”). select cell A1. When finished with the data entry. the condition is false. Visual Basic repeats the statements inside the loop. Because this cell is empty. which applies the bold formatting to the active cell.

DisplayStatusBar tells Visual Basic to turn on the status bar display. when the condition Now < stopme evaluates to true).StatusBar = False End Sub In the above procedure. Enter the following procedure in the DoLoops module: Sub TenSeconds() Dim stopme stopme = Now + TimeValue("00:00:10") Do While Now < stopme Application.StatusBar = Now Loop Application. (See the online help for other examples of using the built-in TimeValue function. Observe the date and time display in the status bar. the statements inside the Do…While loop will be executed as long as the time returned by the Now function is less than the value of the variable called stopme.1. While the time is displayed for 10 seconds. The status bar should return to “Ready” after 10 seconds. the user cannot work with the system (the mouse pointer turns into the hourglass). double-click the TenSeconds macro name (or highlight the macro name and click Run). Choose Developer | Macros. This statement returns the default status bar message “Ready. The variable stopme holds the current time plus 10 seconds. In the Macro dialog box.) The statement Application. After the 10 seconds are over (that is.DisplayStatusBar = True Application. Visual Basic leaves the loop and executes the statement after the Loop keyword.” 2. Press Alt+F11 to switch to the Microsoft Excel application window. The next statement places the current date and time in the status bar. The Do…While loop has an alternative syntax that lets you test the condition at the bottom of the loop in the following way: Do . 3.

you must press Ctrl+Break. the SignIn procedure shows how to exit the loop when a condition is reached. the loop ends immediately. Avoid Infinite Loops If you don’t design your loop correctly. you get an infinite loop—a loop that never ends. When the Exit Do statement is encountered. Visual Basic has already executed the statements one time. The following procedure causes the loop to execute endlessly because the programmer forgot to include the test condition: Sub SayHello() Do MsgBox "Hello. Let’s take a look at an example: Sub SignIn() Dim secretCode As String Do secretCode = InputBox("Enter your secret code:") If secretCode = "sp1045" Then Exit Do Loop While secretCode < > "sp1045" End Sub Notice that by the time the condition is evaluated. In addition to placing the condition at the end of the loop. You will not be able to stop the procedure by using the Esc key. the statements inside the loop are executed at least once.statement1 statement2 statementN Loop While condition When you test the condition at the bottom of the loop." Loop End Sub To stop the execution of the infinite loop. When Visual Basic displays the message box that says “Code execution has been .

This process continues as long as the condition IsEmpty(ActiveCell) evaluates to false. Another handy loop. 0). In other words.Bold = True ActiveCell. Because the ApplyBold2 procedure tests the condition at the beginning of the loop. As a result. if the active cell is not empty. Here’s the syntax: Do Until condition statement1 statement2 statementN Loop Using the above syntax. allows you to repeat one or more statements until a condition becomes true.Font. Like the Do…While loop. the Do…Until loop has a second syntax that lets you test the condition at the bottom of the loop: Do statement1 statement2 statementN Loop Until condition . Visual Basic executes the two statements inside the loop. Do…Until repeats a block of code as long as something is false.interrupted.Select Loop End Sub The first line of this procedure says to perform the following statements until the first empty cell is reached. Do…Until.” click End to end the procedure.Offset(1. the statements inside the loop will not run if the first cell is empty. You will get the chance to try out this procedure in the next section. you can now rewrite the previous ApplyBold procedure in the following way: Sub ApplyBold2() Do Until IsEmpty(ActiveCell) ActiveCell.

Press Alt+F11 to switch to the Microsoft Excel window and manually insert three new worksheets into the current workbook. Let’s try out an example procedure that deletes empty sheets from a workbook.Address = "$A$1" And _ Range("A1"). in the DoLoops module that you created earlier.Select Set myRange = ActiveSheet.UsedRange If myRange. Writing a VBA Procedure with a Do…Until Statement 1. Enter the DeleteBlankSheets procedure.DisplayAlerts = False Worksheets(shcount).Value = "" Then Application. Hands-On 7. enter text or number in cell A1. Do not enter any data on the third inserted sheet. . enter some data in cells B2 and C10.3. as shown below. place the condition on the line with the Loop statement no matter what the value of the condition. Sub DeleteBlankSheets() Dim myRange As Range Dim shcount As Integer shcount = Worksheets.DisplayAlerts = True End If shcount = shcount .Delete Application.Count Do Worksheets(shcount). On another sheet.1 Loop Until shcount = 1 End Sub 2. In one of the sheets.If you want the statements to execute at least once.

See other examples of using counters with the For…Next loop later in this chapter. as well as all the empty cells that are among them. The DeleteBlankSheets procedure shown above declares the variable shcount to keep track of sheets that have been processed. When you run this procedure. turn the system messages back on with the following statement: Application. If you’d rather not be prompted to confirm the deletion. Because the workbook must contain at least one worksheet. the UsedRange will be $A$1:$C$10. For example. This ensures that you always know the exact value of the counter before you begin using it. Run the DeleteBlankSheets procedure.3.Count Notice also that when deleting sheets. The value of shcount is initialized at the beginning of the procedure with the following statement: Worksheets.DisplayAlerts = False When you are finished. the code is executed until the variable shcount equals one. The UsedRange property applies to the Worksheet object and contains every nonempty cell on the worksheet. If you later enter data in cell A1. if you enter something in cells B2 and C10. The used range is bounded by the farthest upper-left and farthest lower-right nonempty cell on a worksheet. the used range is $B$2:$C$10. A counter can be incremented or decremented by a specified value. Excel normally displays the confirmation dialog box.DisplayAlerts = True Counters A counter is a numeric variable that keeps track of the number of items that have been processed. WATCHING A PROCEDURE EXECUTE . Visual Basic deletes the selected sheet whenever two conditions are true—the UsedRange property address returns cell A1 and cell A1 is empty. A counter variable should be initialized (assigned a value) at the beginning of the program. The statement shcount = shcount – 1 makes sure that the shcount variable is reduced by one each time the statements in the loop are executed. use the following statement: Application.

as shown in Figure 7. Notice the yellow arrow in the margin indicator bar of the Code window. Hands-On 7. Let’s examine how Visual Basic allows you to execute a procedure line by line. Select cell A1 and choose Developer | Macros. select the ApplyBold2 procedure and click the Step Into button. In the Macro dialog box. . you’d like to watch the procedure execute in slow motion so that you can check the logic of the program. it’s sometimes hard to see whether the procedure works as expected.1. The Visual Basic Editor screen will appear with the name of the procedure highlighted in yellow. Insert a new sheet into the current workbook and enter any data in cells A1:A5. 2.4. 3. Executing a Procedure Line by Line 1. Occasionally.When you run procedures that use looping structures.

6.1.Figure 7. 4. Make the Visual Basic window smaller. Watching the procedure code execute line by line.1. then press F8. 5. To do this. The yellow highlight in the Code window jumps to this line: Do Until IsEmpty(ActiveCell) 7. Make sure cell A1 is selected and that it contains data. Continue pressing F8 while watching both the Code window and the worksheet . Click the title bar in the Visual Basic window to move the focus to this window. click the Restore button in the Visual Basic title bar and arrange the screen as shown in Figure 7.

The loop begins with the keyword While and ends with the keyword Wend. Hands-On 7.5. Once the condition is false. Insert a new module into the current VBA project. Enter the following procedure in the WhileLoop module. Here’s the syntax: While condition statement1 statement2 statementN Wend The condition is tested at the top of the loop. Sub ChangeRHeight() . Rename the module WhileLoop. WHILE…WEND LOOP The While…Wend loop is functionally equivalent to the Do…While loop.window. This statement is a carryover from earlier versions of Microsoft Basic and is included in VBA for backward compatibility. Let’s look at an example of a procedure that uses the While…Wend looping structure. We will change the row height of all nonempty cells in a worksheet. Writing a VBA Procedure with a While…Wend Statement 1. Visual Basic exits the loop. You will find more information related to stepping through VBA procedures in Chapter 10. The statements are executed as long as the given condition is true. 2.

Start is the number at which you want to begin counting. The ChangeRHeight procedure sets the row height to 28 when the active cell is not empty. 4. use the following For statement syntax: For counter = 1 To 5 . and end indicates how many times the loop should be executed. select the ChangeRHeight procedure and click Run. Select cell B1 and choose Developer | Macros. Switch to the Microsoft Excel window and enter some data in cells B1:B4 of any worksheet. The syntax of a For…Next loop looks like this: For counter = start To end [Step increment] statement1 statement2 statementN Next [counter] The code in the brackets is optional. The statement ActiveCell.RowHeight = 28 ActiveCell. For example. Counter is a numeric variable that stores the number of iterations.Select Wend End Sub 3. In the Macro dialog. 0).Offset(1. 5.Select tells Visual Basic to select the cell that is located one row below (1) the active cell and in the same column (0). if you want to repeat the statements inside the loop five times.While ActiveCell < > "" ActiveCell. 0).Offset(1. FOR…NEXT LOOP The For…Next loop is used when you know how many times you want to repeat a group of statements. The next cell is selected by using the Offset property of the Range object.

6. the value of the variable counter is increased by one. The second time in the loop. By default. The first time in the loop. Visual Basic exits the loop. When you imported data from a Microsoft Access table. The name of the variable (counter) after the Next keyword is also optional. use the following statement: For counter = 1 To 5 Step 3 Your statements go here Next counter When Visual Basic encounters the above instruction. as long as counter hasn’t reached the value in end. Writing a VBA Procedure with a For…Next Statement . You can change this default setting by using the Step clause. This causes Visual Basic to exit the loop. it executes the statements inside the loop twice. As soon as the value of counter is greater than the number entered after the To keyword. to increase the variable counter by three. sooner or later the value stored in counter exceeds the value specified. However. Hands-On 7. it’s good programming practice to make your Next keywords explicit by including counter. For example. How can you use the For…Next loop in a Microsoft Excel spreadsheet? Suppose in your sales report you’d like to include only products that were sold in a particular month. Note that the Step increment is optional. let’s see how you can handle it with a For…Next loop. you also got rows with the sold amount equal to zero. it will go back to the beginning of the loop and execute the statements inside the loop again. counter equals 7 (4 + 3).Your statements go here Next When Visual Basic encounters the Next keyword. counter equals 1. Because the variable counter automatically changes after each execution of the loop. Visual Basic will then decrement this value from counter each time it encounters the Next keyword. every time Visual Basic executes the statements inside the loop. How can you quickly eliminate those “zero” rows? Although there are many ways to solve this problem. and isn’t specified unless it’s a value other than 1. After the second time inside the loop. You can also place a negative number after Step. counter equals 4 (3 + 1).

so Visual Basic selects the next cell. Otherwise. Next.1 Else ActiveCell. insert a new module into the current project and rename it ForNextLoop. Because the first row of the spreadsheet contains the column headings. 0).Select For r = 1 To totalR . Enter the following procedure in the ForNextLoop module: Sub DeleteZeroRows() Dim totalR As Integer Dim r As Integer Range("A1"). 2.Offset(1.Select End If Next r End Sub Let’s examine the DeleteZeroRows procedure line by line. Visual Basic selects cell B2 and encounters the For keyword.EntireRow. The conditional statement (If…Then…Else) nested inside the loop tells Visual Basic to make a decision based on the value of the active cell. the condition is false.Delete totalR = totalR . If the value is equal to zero. Visual Basic deletes the current row and reduces the value of totalR by one.1.1 If ActiveCell = 0 Then Selection. . decrease the total number of rows by one (totalR – 1).Count Range("B2"). Visual Basic will need to execute the instructions inside the loop six times.Rows.CurrentRegion. it jumps to the For keyword to compare the value of r with the value of totalR – 1. The first two statements calculate the total number of rows in the current range and store this number in the variable totalR. Each time Visual Basic completes the loop.Select totalR = Selection. In the Visual Basic window.

you have to use the same command several times. Because each worksheet is an object in a collection of worksheets. Enter the data shown below: 4. Choose Developer | Macros. Visual Basic generates the following error message: “For without Next. for example. Visual Basic can figure out on its own how many times the loop should execute. 5. This loop looks like the following: . select the DeleteZeroRows procedure and click Run. This loop does not require a counter variable. a collection of worksheets. depending on the total number of worksheets. When the procedure ends. “Working with Arrays”).” FOR EACH…NEXT LOOP When your procedure needs to loop through all of the objects of a collection or all of the elements in an array (arrays are covered in Chapter 8. If one is missing. the For Each…Next loop should be used.3. you have to first select it and then choose Home | Cells | Delete | Delete Sheet. To leave only one worksheet in a workbook. Paired Statements For and Next must be paired. In the Macro dialog. Let’s take. To remove a worksheet from a workbook. you can speed up the process of deleting worksheets by using the For Each…Next loop. Switch to the Microsoft Excel window and insert a new worksheet. the sales spreadsheet does not include products that were not sold.

DisplayAlerts = True End Sub . Group is the name of a collection or an array. Insert a new module into the current project and rename it ForEachNextLoop. Writing a VBA Procedure with a For Each… Next Statement 1.Add After:=ActiveSheet. Count:=3 For Each mySheet In Worksheets If mySheet. 2. Type the following procedure in the ForEachNextLoop module: Sub RemoveSheets() Dim mySheet As Worksheet Application.Name < > "Sheet1" Then ActiveWindow. This variable has to be of the Variant data type for an array and an Object data type for a collection.Add Sheets. Hands-On 7. Let’s now see how to use the For Each…Next loop to remove some worksheets.SelectedSheets.7.DisplayAlerts = False Workbooks.Delete End If Next mySheet Application. element is a variable to which all the elements of an array or collection will be assigned.For Each element In Group statement1 statement2 statementN Next [element] In the above syntax.

Name = strSheetName Then counter = counter + 1 Exit For End If Next mySheet If counter = 1 Then MsgBox strSheetName & " exists." End If . makes sure that Microsoft Excel does not display alerts and messages while the procedure is running. The first instruction. Therefore. 3. Here’s another example that checks whether a certain sheet is part of a workbook: Sub IsSuchSheet(strSheetName As String) Dim mySheet As Worksheet Dim counter As Integer counter = 0 Workbooks. Notice that the variable mySheet represents an object in a collection of worksheets. add three new sheets after the default Sheet1 (ActiveSheet).DisplayAlerts = False. Application.Add Sheets. and proceed to delete all the sheets except for Sheet1. the workbook has only one sheet—Sheet1. Position the insertion point anywhere within the RemoveSheets procedure code and press F5 to run it. When the procedure ends. this variable has been declared of the specific object data type Worksheet. Count:=3 For Each mySheet In Worksheets If mySheet." Else MsgBox strSheetName & " was not found.Add After:=ActiveSheet. The For Each…Next loop steps through each worksheet and deletes it as long as it is not Sheet1.Visual Basic will open a new workbook.

The Exit Do statement immediately exits any of the VBA Do loops. The Exit statements are covered in the next section. Writing a VBA Procedure with an Early Exit from a For Each…Next Statement 4. To execute the IsSuchSheet procedure. It’s possible that a user has entered the wrong data. The following procedure demonstrates how to use the Exit For statement to leave the For Each…Next loop early.8. run the FindSheet procedure.End Sub Sub FindSheet() Call IsSuchSheet("Sheet4") End Sub The IsSuchSheet procedure uses the Exit For statement to ensure that we exit the loop as soon as the sheet name passed in the procedure argument is found in the workbook. Hands-On 7. Visual Basic has two types of Exit statements: The Exit For statement is used to end either a For…Next or a For Each…Next loop early. or perhaps the task has been completed and there’s no need to do additional looping. EXITING LOOPS EARLY Sometimes you may not want to wait until the loop ends on its own. a procedure has encountered an error. You can leave the loop early without reaching the condition that normally terminates it. Enter the following procedure in the ForEachNextLoop module: Sub EarlyExit() Dim myCell As Variant Dim myRange As Range Set myRange = Range("A1:H10") .

Also.Value = "empty" Else Exit For End If Next myCell End Sub The EarlyExit procedure examines the contents of each cell in the specified range —A1:H10. 5.9. Choose Developer | Macros. 6. Each procedure demonstrated the use of each individual looping structure. In programming practice. Hands-On 7. however. 7. Open a new workbook and enter a value in any cell within the specified range —A1:H10. Visual Basic allows you to “nest” various types of loops (For and Do loops) within the same procedure. it exits the loop. When you use nesting loops. The following ColorLoop procedure illustrates how one For…Next loop is nested within another For…Next loop. In the Macro dialog. When writing nested loops. Visual Basic enters the text “empty” in the active cell. you must make sure that each inner loop is completely contained inside the outer loop.For Each myCell In myRange If myCell. If the active cell is empty. you can often execute a specific task more effectively. each loop has to have a unique counter variable.Value = "" Then myCell. select the EarlyExit procedure and click Run. When Visual Basic encounters the first nonempty cell. NESTED LOOPS So far in this chapter you have tried out various loops. one loop is often placed inside another. Writing a VBA Procedure with a Nested For…Next Statement .

Visual Basic jumps back to the outer loop to increment the variable myRow by one and returns to the inner loop to color the next set of cells in the second row. and then applies the color to the selected cell. C1. is formatted as white (color index number 2).Select myColor = myColor + 1 With Selection. When the variable myCol is greater than 7. F1. The first cell.1. While the outer loop keeps track of the row number. The second cell. When the procedure ends. A1. B1. Each time the cell . 56 cells (8*7) are formatted with all the colors available in the current color palette. The inner For…Next loop applies a different color to seven cells in the first worksheet row (A1. the inner loop does more than one thing. selects the appropriate cell based on the current row and column index. myCol). is formatted with a black color (color index number 1). D1. B1. Enter the following procedure in the ForEachNextLoop module: Sub ColorLoop() Dim myRow As Integer Dim myCol As Integer Dim myColor As Integer myColor = 0 For myRow = 1 To 8 For myCol = 1 To 7 Cells(myRow. and G1). It determines the current column number.ColorIndex = myColor . keeps track of the color index. E1.Pattern = xlSolid End With Next myCol Next myRow End Sub The ColorLoop procedure uses two For…Next loops to change the color of each cell located in the first eight rows and seven columns of a worksheet.Interior .

for instance. Exiting Procedures If you want to exit a subroutine earlier than normal. While working with several types of looping statements. learned how to repeat certain groups of statements using procedure loops. use the Exit Function statement instead. In the following chapters of this book. 2. use the Exit Sub statement. myCol). there are many additional examples of using loops. you will see how arrays and nested loops are used in a VBA procedure that picks lottery numbers. you’ll find it easier to choose the appropriate flow control structure for your task. CHAPTER SUMMARY In this chapter you. Open a new workbook and choose Developer | Macros. As you gain experience. you saw how each loop performs repetitions in a slightly different way.address changes—Cells(myRow. . In the Macro dialog. select the ColorLoop procedure and click Run. In the next chapter. 3.Select—the contents of the variable myColor change as well—myColor = myColor + 1. If the procedure is a function. Chapter 8 will show you how arrays are used to work with larger sets of data.

many advanced VBA procedures will require that you implement more efficient methods of keeping track of multiple values.Part 3 Keeping Track of Multiple Values Chapter 8 Working with Arrays Chapter 9 Working with Collections and Class Modules Although you can use individual variables to store data while your VBA code is executing. In this part of the book. you’ll learn about working with groups of variables .

and an employee list are examples of one-dimensional arrays or. The two most common types of arrays are one-dimensional arrays (lists) and twodimensional arrays (tables). a list of the days of the week. For each single value that you wanted your procedure to manipulate. your VBA procedures can manage a large amount of data with ease. simply. in the following illustration we have a one-dimensional array of six elements indexed from 0 to 5 You can access the third element of this array by specifying index (2). But what if you have a series of values? If you had to write a VBA procedure to deal with larger amounts of data. By default. or value. currency name. Visual Basic has a way to get around this problem. property. Integer. In this chapter. Currency. WHAT IS AN ARRAY? In Visual Basic an array is a special type of variable that represents a group of similar values that are of the same data type (String.). you’d need at least three variables for each country: country name. By clustering the related variables together. A shopping list. you declared a variable. A one-dimensional array is sometimes referred to as a list. Date. you’ll learn how to manipulate lists and tables of data with arrays. and exchange rate. Fortunately. For example. you worked with many VBA procedures that used variables to hold specific information about an object. . you would have to create enough variables to handle all of the data. etc.Chapter 8 Working with Arrays In previous chapters. Each element in the list has an index value that allows accessing that element. Can you imagine the nightmare of storing in your program currency exchange rates for all the countries in the world? To create a table to hold the necessary data. numbered lists.

an array that holds the yearly sales for each product your company sells has two dimensions (the product name and the year). 0). The position of each element in a table is determined by its row and column numbers. You can change this behavior by using the Option Base 1 statement or by explicitly coding the lower bound of your array as explained further in this chapter. Following are two examples of a two-dimensional array: an array named yearlyProductSales@ that stores yearly product sales using the Currency data type (@) and an array named exchange (of Variant data type) that stores . Following are two examples of onedimensional arrays: a one-dimensional array called cities that is populated with text (String data type—$) and a one-dimensional array called lotto that contains six lottery numbers stored as integers (Integer data type—%) As you can see. In other words. The following is a diagram of an empty two-dimensional array You can access the first element in the second row of this two-dimensional array by specifying indexes (1. All elements of the array must be of the same data type. If you want to store values of different data types in the same array. you must declare the array as Variant. For example. one array cannot store both strings and integers. You will learn how to declare arrays in the next section. the contents assigned to each array element match the Array type. A two-dimensional array may be thought of as a table or matrix.the first element of an array is indexed zero.

and the U. its currency. dollar exchange rate. In these examples. array is being declared. and column. the yearlyProductSales@ array can hold a maximum of 8 elements (4 rows * 2 columns = 8) and the exchange array will allow a maximum of 15 elements (5 rows * 3 columns = 15). or Public). DECLARING ARRAYS Because an array is a variable. the variable name is . you must declare it in a similar way that you declare other variables (by using the keywords Dim.the name of the country. Private. most people find it difficult to picture dimensions beyond 3D.S. A three-dimensional array is identified by three indexes: table. Although VBA arrays can have up to 60 dimensions. 0). For fixed-length arrays. If a variable-length. A three-dimensional array is an array of twodimensional arrays (tables) where each table has the same number of rows and columns. row. the array bounds are listed in parentheses following the variable name. The first element of a three-dimensional array is indexed (0. or dynamic. 0.

Visual Basic sets aside 12 bytes—2 bytes for each element of the array (recall that the size of the Integer data type is 2 bytes. Currency. The larger the array. String. Because arrays can eat up a lot of memory and impact your computer’s performance. Byte. it’s recommended that you declare arrays . When you declare a one-dimensional array named lotto with six elements. Long.followed by an empty pair of parentheses. the more memory space is required to store the data. Single. Visual Basic automatically reserves enough memory space. The amount of the memory allocated depends on the array’s size and data type. hence 2 * 6 = 12). Variant. The last part of the array declaration is the definition of the data type that the array will hold. Let’s look at some examples When you declare an array. An array can hold any of the following data types: Integer. Boolean. or Date. Double.

Notice the keyword To between the lower and the upper indexes. Subscripted Variables The numbers inside the parentheses of the array variables are called subscripts. you can explicitly specify a lower bound of the array by using an Option Base 1 statement. The bounds of an array are its lowest and highest indices. With numeric indexing starting at 0. and so on. The numbers enclosed in parentheses after the array name specify the lower (3) and upper (6) bounds of the array. Let’s take a look at the following example: Dim cities(3 To 6) As Integer The above statement declares a one-dimensional array with four elements. If you’d rather start counting your array’s elements at 1. Therefore. and each individual variable is called a subscripted variable or element. If you don’t specify Option Base 1 in a procedure that uses arrays. This instruction must be placed in the declaration section at the top of a VBA module before any Sub statements. If you’d rather not use the Option Base 1 statement and still have the array indexing start at a number other than 0. the one-dimensional array cities(5) contains six elements numbered from 0 to 5. VBA assumes that the statement Option Base 0 is to be used and begins indexing your array’s elements at 0.with only as many elements as you think you’ll use. For example. number 2 represents the third. you must specify the bounds of an array when declaring the array variable. number 1 represents the second element of the array. cities(5) is the sixth subscripted variable (element) of the array cities(). ARRAY UPPER AND LOWER BOUNDS By default VBA assigns zero (0) to the first element of the array. While a typical variable can hold only one value. the third 5. What Is an Array Variable? An array is a group of variables that have a common name. and the fourth 6. an array variable can store a large number of individual values. The first element of this array is indexed 3. You refer to a specific value in the array by using the array name and an index number. . the second 4.

” or “populating an array.” The three methods you can use to load data into an array are discussed in this section. Next.” “filling an array. the As Variant clause is optional in the array variable declaration: Dim cities() as Variant or Dim cities() Notice that you don’t specify the number of elements between the parentheses.INITIALIZING AN ARRAY After you declare an array. Because Variant is the default data type. This is often referred to as “initializing an array. Filling an Array Using Individual Assignment Statements Assume you want to store the names of your six favorite cities in a onedimensional array named cities. you must assign values to its elements. After declaring the array with the Dim statement: Dim cities(5) as String or Dim cities$(5) you can assign values to the array variable like this: cities(0) = "Baltimore" cities(1) = "Atlanta" cities(2) = "Boston" cities(3) = "San Diego" cities(4) = "New York" cities(5) = "Denver" Filling an Array Using the Array Function VBA’s built-in function Array returns an array of Variants. use the Array function as shown below to assign values to your cities array: .

The second loop is used to print out the values from the array. _ "San Diego". the lower bound of an array is 0 or 1 and the upper bound is 5 or 6. "Denver") When using the Array function for array population. depending on the setting of Option Base (see the previous section titled “Array Upper and Lower Bounds”). Filling an Array Using For…Next Loop The easiest way to learn how to use loops to populate an array is by writing a procedure that fills an array with a specific number of integer values. Notice that the procedure uses the Rnd function to generate a random .cities = Array("Baltimore". "Atlanta". "New York".Print myIntArray(i) Next End Sub The above procedure uses a For…Next loop to fill myIntArray with 10 random numbers between 1 and 100. Let’s look at the example procedure below: Sub LoadArrayWithIntegers() Dim myIntArray(1 To 10) As Integer Dim i As Integer 'Initialize random number generator Randomize 'Fill the array with 10 random numbers between 1 and 100 For i = 1 To 10 myIntArray(i) = Int((100 * Rnd) + 1) Next 'Print array values to the Immediate window For i = 1 To 10 Debug. "Boston".

7). Randomize and Rnd. let’s write a couple of VBA procedures to make arrays a part of your new skill set.1.xlsm. To become more familiar with the Randomize statement and Rnd function. 3.1 uses a one-dimensional array to programmatically display a list of six North American cities. save it as 2. Insert a new module into the Arrays (Practice_Excel08. The procedure in Hands-On 8. you can use the For…Next loop to load it into your array variable (see Hands-On 8. You can try it out in the Immediate window by entering: x=rnd ?x Before calling the Rnd function. and rename this module StaticArrays. Hands-On 8. Using a One-Dimensional Array 1. This function returns a value less than 1 but greater than or equal to 0. If the data you’d like to store in an array is located in an external file or in an Excel spreadsheet. . the LoadArrayWithIntegers procedure uses the Randomize statement to initialize the random-number generator. be sure to follow up with the Excel online help. USING ARRAYS IN VBA PROCEDURES Having learned the basics of array variables. Please note files for the “Hands-On” project may be found on the companion CDROM. see Hands-On 8.xlsm) project. For an additional example of using loops. Switch to the Microsoft Visual Basic Editor window and rename the VBA project Arrays.number. Open a new workbook and C:\Excel2013_ByExample\Practice_Excel08.4.

. the default indexing for an array is changed.1. The last statement uses the MsgBox function to display the list of cities. the city names will appear on separate lines in the message box. The array cities() of String data type is declared with six elements. This statement tells Visual Basic to assign the number 1 instead of the default 0 to the first element of the array. Notice that the position of the Option Base 1 statement is at the top of the module window before the Sub statement. enter the following FavoriteCities procedure: ' start indexing array elements at 1 Option Base 1 Sub FavoriteCities() 'now declare the array Dim cities(6) As String 'assign the values to array elements cities(1) = "Baltimore" cities(2) = "Atlanta" cities(3) = "Boston" cities(4) = "San Diego" cities(5) = "New York" cities(6) = "Denver" 'display the list of cities MsgBox cities(1) & Chr(13) & cities(2) & Chr(13) _ & cities(3) & Chr(13) & cities(4) & Chr(13) _ & cities(5) & Chr(13) & cities(6) End Sub Before the FavoriteCities procedure begins.4. In the StaticArrays module. as shown in Figure 8. You can change the order of the displayed data by switching the index values. Each element of the array is then assigned a value. When you run this procedure in Step 5.

1.Figure 8. You can display the elements of a one-dimensional array with the MsgBox function. .

In the StaticArrays module. The Range of the Array The spread of the subscripts specified by the Dim statement is called the range of the array (for example: Dim mktgCodes(5 To 15)). It’s time to combine the skills you’ve learned so far. On your own. enter the following procedure: Sub FavoriteCities2() 'now declare the array Dim cities(6) As String Dim city As Variant 'assign the values to array elements cities(1) = "Baltimore" .2. modify the FavoriteCities procedure so that it displays the names of the cities in the reverse order (from 6 to 1). Hands-On 8. Position the insertion point anywhere within the procedure code and press F5 to run the FavoriteCities procedure. ARRAYS AND LOOPING STATEMENTS Several looping statements that you learned in Chapter 7 (For…Next and For Each…Next) will come in handy now that you’re ready to perform tasks such as populating an array or displaying the elements of an array.5. Using the For Each…Next Statement to Enumerate the Array Elements 1. 6. How can you rewrite the FavoriteCities procedure so that it shows the name of each city in a separate message box? The FavoriteCities2 procedure shown below replaces the last statement of the original procedure with the For Each…Next loop.

enter the two procedures as shown below: Sub FavoriteCities3() 'now declare the array Dim cities(6) As String . For Each…Next allows you to loop through all of the objects in a collection or all of the elements of an array and perform the same action on each object or element. In the StaticArrays module. 2. the loop will execute as many times as there are elements in the array. As you recall from the previous chapter.cities(2) = "Atlanta" cities(3) = "Boston" cities(4) = "San Diego" cities(5) = "New York" cities(6) = "Denver" 'display the list of cities in separate messages For Each city In cities MsgBox city Next End Sub Notice that the For Each…Next loop uses the variable city of Variant data type. The FavoriteCities3 procedure demonstrates how you can pass elements of an array to another procedure. When you run the FavoriteCities2 procedure.3. Passing an Array to Another Procedure 1. Run the FavoriteCities2 procedure. In Chapter 5. Let’s take a look at yet another variation of the FavoriteCities procedure. Hands-On 8. you practiced passing arguments as variables to subroutines and functions.

These functions are discussed later in this chapter. In order to iterate through the elements of an array. Therefore.'assign the values to array elements cities(1) = "Baltimore" cities(2) = "Atlanta" cities(3) = "Boston" cities(4) = "San Diego" cities(5) = "New York" cities(6) = "Denver" 'call another procedure and pass the array as argument Hello cities() End Sub Sub Hello(cities() As String) Dim counter As Integer For counter = LBound(cities()) To UBound(cities()) MsgBox "Hello. . LBound(cities()) will return 1 as the first element of the array. and UBound(cities()) will return 6 as the last element of the cities() array. Also notice that the declaration of the Hello procedure includes an array type argument—cities()—passed to this procedure as String. " & cities(counter) & "!" Next End Sub Notice that the last statement in the FavoriteCities3 procedure calls the Hello procedure and passes to it the array cities() that holds the names of our favorite cities. In this procedure example. you need to know how many elements the passed array contains. the statement For counter = LBound(cities()) To UBound(cities()) will boil down to For counter = 1 To 6. You can easily retrieve this information via two array functions—LBound and UBound.

If you’re an avid lotto player who is getting tired of picking your own lucky numbers. In the StaticArrays module. Practical Application of an Array 1. Hands-On 8. Passing array elements from a subroutine to a subroutine or function procedure allows you to reuse the same array in many procedures without duplicating the program code. The Lotto procedure below populates an array with six numbers from 1 to 54. Here’s how you can put to work your newly acquired knowledge about arrays and loops in real life.minNum + 1) * Rnd) + minNum . have Visual Basic do the picking.2. You can adjust this procedure to pick numbers from any range. Run the FavoriteCities3 procedure. enter the following procedure: Sub Lotto() Const spins = 6 Const minNum = 1 Const maxNum = 54 Dim t As Integer ' looping variable in outer loop Dim i As Integer ' looping variable in inner loop Dim myNumbers As String ' string to hold all picks Dim lucky(spins) As String ' array to hold generated picks myNumbers = "" For t = 1 To spins Randomize lucky(t) = Int((maxNum .4.

and String variables have a default value of the empty string (“”). 2. Numeric variables have a default value of zero (0). Initial Value of an Array Element Until a value is assigned to an element of an array.' see if this number was drawn before For i = 1 To (t . If you omit the inner loop and run this procedure multiple times. Instead of assigning constant values for minNum and maxNum.1) If lucky(t) = lucky(i) Then lucky(t) = Int((maxNum . you’ll likely see some occurrences of duplicate numbers pop up. you can use the InputBox function to get these values from the user. Run the Lotto procedure. The inner For…Next loop ensures that each picked number is unique—it may not be any one of the previously picked numbers. the element has its default value. The instruction Int((maxNum – minNum + 1) * Rnd) + minNum uses the Rnd function to generate a random value between the specified minNum and maxNum.minNum + 1) * Rnd) + minNum i = 0 End If Next i MsgBox "Lucky number is " & lucky(t) myNumbers = myNumbers & " . Passing Arrays between Procedures . The Int function converts the resulting random number to an integer." & lucky(t) Next t MsgBox "Lucky numbers are " & myNumbers End Sub T h e Randomize statement initializes the random-number generator.

2) = "Peso" Ex(2. it’s time to take a closer look at how you can work with tables of data. 1) = "Canada" Ex(3. 2) = "Yen" Ex(1. In the StaticArrays module.57 Ex(2.2085 Ex(3. it is local to this procedure and unknown to other procedures. currency name. However.When an array is declared in a procedure. enter the following procedure: Sub Exchange() Dim t As String Dim r As String Dim Ex(3. Hands-On 8. 1) = "Japan" Ex(1. 1) = "Mexico" Ex(2. USING A TWO-DIMENSIONAL ARRAY Now that you know how to programmatically produce a list (a one-dimensional array). 2) = "Dollar" . 3) = 11. Storing Data in a Two-Dimensional Array 1. you can pass the local array to another procedure by using the array’s name followed by an empty set of parentheses as an argument in the calling statement.5. 3) = 104. The following procedure creates a two-dimensional array that will hold the country name. and exchange rate for three countries. 3) As Variant t = Chr(9) ' tab r = Chr(13) ' Enter Ex(1. the statement Hello cities() calls the procedure named Hello and passes to it the array cities(). For example.

. 3) = 1. 2) & t & Ex(3. 1) & t & t & Ex(1. _ "Exchange" End Sub 2. 1) & t & t & Ex(2. 3) & r _ & Ex(2. .2028 MsgBox "Country " & t & t & "Currency" & t & "per US$" _ & r & r _ & Ex(1. 2) & t & Ex(1. 3) & r _ & Ex(3. 2) & t & Ex(2.Ex(3. 1) & t & t & Ex(3. Run the Exchange procedure. 3) & r & r _ & "* Sample Exchange Rates for Demonstration Only".

A static array is an array of a specific size. When you run the Exchange procedure. The text displayed in a message box can be custom formatted. STATIC AND DYNAMIC ARRAYS The arrays introduced thus far in this chapter were static. For example. Use a static array when you know in advance how big the array should be.Figure 8. the number of user- . But what if you’re not sure how many elements your array will contain? If your procedure depends on user input. The size of the static array is specified in the array’s declaration statement. the statement Dim Fruits(9) As String declares a static array called Fruits that is made up of 10 elements (assuming you have not changed the default indexing to 1).2. as shown in Figure 8.2. you will see a message box with the exchange information presented in three columns.

supplied elements might vary every time the procedure is executed. initially you may want to hold five fruits in the array: Redim Fruits(1 To 5) T he ReDim statement redimensions arrays as the code of your procedure executes and informs Visual Basic about the new size of the array.6. A dynamic array is an array whose size can change. Using a Dynamic Array 1. 2. You use a dynamic array when the array size is determined each time the procedure is run. If you declare an array to hold more elements than what you need. Now let’s write a procedure that demonstrates the use of a dynamic array. How can you ensure that the array you declare is not wasting memory? After you declare an array. The solution to this problem is making your arrays dynamic. VBA sets aside enough memory to accommodate the array. you’ll end up wasting valuable computer resources. This statement can be used several times in the same procedure. Hands-On 8.Add 'populate myArray with values . A dynamic array is declared by placing empty parentheses after the array name: Dim Fruits() As String Before you use a dynamic array in your procedure. For example. Enter the following DynArray procedure: Sub DynArray() Dim counter As Integer 'declare a dynamic array Dim myArray() As Integer 'specify the initial size of the array ReDim myArray(1 To 5) Workbooks. you must use the ReDim statement to dynamically set the lower and upper bounds of the array. Insert a new module into the current project and rename it DynamicArrays.

the statement Dim myArray() As Integer declares a dynamic array called myArray. 0) .Add opens a new workbook. 0). The first ReDim statement specifies the initial size of myArray and reserves 10 bytes of memory for it to hold its five elements.1. it does not allocate any memory to the array.Offset(counter .For counter = 1 To 5 myArray(counter) = counter + 1 ActiveCell. Although this statement declares the array. 0).Bold = True End With Next counter End Sub In the DynArray procedure. and the For…Next loop populates myArray with data and writes the array’s elements to a worksheet. The value of the variable counter equals 1 at the beginning of the loop.Value = myArray(counter) Next 'change the size of myArray to hold 10 elements ReDim Preserve myArray(1 To 10) 'add new values to myArray For counter = 6 To 10 myArray(counter) = counter * counter With ActiveCell.Font. every Integer value requires 2 bytes of memory. As you know. The second statement ActiveCell. The first statement in the loop: myArray(counter) = counter + 1 assigns the value 2 to the first element of myArray.1.Offset(counter .Value = myArray(counter) . The statement Workbooks.Value = myArray(counter) .Offset(counter-1.

Value = myArray(1) The above instruction enters data in cell A1. To do this. the values of the array’s elements are obtained by multiplication: counter * counter. 3. Because the variable counter equals 1. Set your screen so that the Microsoft Excel application and Visual Basic Editor windows are positioned side by side. 4. 0). This time. The ReDim statement alone reinitializes the array. Run the DynArray procedure step by step.enters the current value of myArray’s element in the active cell. the new array will be empty. you can append new elements to an existing array by following the ReDim statement with the Preserve keyword.Offset(1-1. you lose all the values that were in that array. place the mouse pointer inside the code of this procedure and press F8 to execute each statement. the Preserve keyword guarantees that the redimensioned array will not lose its existing data. 7th. 9th. Visual Basic enters data in the appropriate worksheet cells and proceeds to the next statement: ReDim Preserve myArray(10) Normally when you change the size of the array.Value = myArray(1) Or ActiveCell. . The statements inside the loop are executed five times. The result of the DynArray procedure is shown in Figure 8. the statement above results in the following: ActiveCell. However.3.0). The active cell is A1. If you omit it.Offset(0. 8th. and 10th elements of myArray. Visual Basic enters the additional array’s values in the appropriate spreadsheet cells using the bold font style. The second For…Next loop assigns values to the 6th. In other words.

The example procedure in Hands-On 8. In the DynamicArrays module. The number of elements in a static array isn’t going to change once it has been declared.Figure 8.3.7.7 will dynamically load data entered in a worksheet into a one-dimensional array. Fixed-Dimension Arrays A static array contains a fixed number of elements. Hands-On 8. An array showing 10 values. Loading Worksheet Data into an Array 1. enter the following procedure: Sub LoadArrayFromWorksheet() Dim myDataRng As Range Dim myArray() As Variant Dim cnt As Integer Dim i As Integer Dim cell As Variant Dim r As Integer .

"$#.UsedRange 'get the count of nonempty cells (text and numbers only) last = myDataRng.00") Else myArray(i) = cell. 3).SpecialCells(xlCellTypeConstants.Value.Value) Then myArray(i) = Format(cell.Value End If i = i + 1 End If .Dim last As Integer Set myDataRng = ActiveSheet.#00." Exit Sub End If ReDim myArray(1 To last) i = 1 'fill the array from worksheet data 'reformat all numeric values For Each cell In myDataRng If cell.Value < > "" Then If IsNumeric(cell.Count If IsEmpty(myDataRng) Then MsgBox "Sheet is empty.

xlsm workbook and enter some data in Sheet2. C h o o s e Developer | Macros. IsArray. 3. Hands-On 8. The numeric data should appear formatted with the currency format. LBound. The following sections demonstrate the use of each of these functions in VBA procedures. Erase. You should see the entries you typed in the worksheet. When the procedure completes.Next 'print array values to the Immediate window For i = 1 To last Debug. choose LoadArrayFromWorksheet. check the data in the Immediate window. Using the Array function. three-element array called auto. Switch to the Microsoft Excel application window of the Practice_Excel08. The CarInfo procedure shown below creates a fixed-size. and UBound. Using the Array Function . one-dimensional. and click Run.Print myArray(i) Next Debug. ARRAY FUNCTIONS You can manipulate arrays with five built-in VBA functions: Array. In the Macro dialog box. you can quickly place a series of values in a list. For example. The Array Function The Array function allows you to create an array during code execution without having to dimension it first.8.Print "Items in the array: " & UBound(myArray) End Sub 2. This function always returns an array of Variants. enter your favorite fruits in cells A1:B6 and numbers in cells D1:D9.

"Black".Formula = heading(i) i = i + 1 . The following procedure example demonstrates how to use the Array function to enter column headings in a worksheet: Sub ColumnHeads() Dim heading As Variant Dim cell As Range Dim i As Integer i = 1 heading = Array("First Name".1. "Last Name". _ "Salary") Workbooks. Insert a new module into the current project and rename it Array_Function. "1999") MsgBox auto(2) & " " & auto(1) & ".Add For Each cell In Range("A1:D1") cell. "Position". Run the CarInfo procedure. " & auto(3) auto(2) = "4-door" MsgBox auto(2) & " " & auto(1) & ". Enter the following CarInfo procedure: Option Base 1 Sub CarInfo() Dim auto As Variant auto = Array("Ford". 2. " & auto(3) End Sub 3.

Select Selection. "/") For i = LBound(illegal) To UBound(illegal) Do While InStr(strInput. "|". InStr(strInput. The following function procedure declares a variant of characters that should be treated as illegal: Function ReplaceIllegalChars(strInput As String) As String Dim illegal As Variant Dim i As Integer illegal = Array("~".Select End Sub You can use the Array function to replace illegal characters in a string. " >". _ "*".Columns. "[". illegal(i)). "?". "!". illegal(i)) Mid(strInput. illegal(i)) . we check whether the character is contained within the string that was passed to the function: Do While InStr(strInput. 1) = "_" Loop Next i ReplaceIllegalChars = strInput End Function For each character in the illegal array.AutoFit Range("A1").Next Columns("A:D"). ":". "< ". "]".

The second argument is the position where you want to begin the replacement. enter: returnString = ReplaceIllegalChars("il!le]g< al te*xt") ? returnString Visual Basic will return the following string: il_le_g_al te_xt To test the function from the worksheet. if the variable is an array. InStr(strInput. and then use the cell reference as the function argument. You can try out the above function procedure by calling the function from the Immediate window or from a worksheet. Visual Basic will replace that string with the underscore character (“_”) or whatever other character you specify in this function: Mid(strInput. in cell B1. The IsArray Function Using the IsArray function. For example. illegal(i)). if it’s not an array. The IsArray function returns either true. type in any cell text that contains illegal characters that were listed in the function’s array variable. enter: =ReplaceIllegalChars(A1) Dimensioning Arrays Arrays must be dimensioned in a Dim or ReDim statement before they are used. Then. For example. The first argument in this function is the string from which characters are returned. or false. We use the third argument. . Here’s an example. you can test whether a variable is an array. This means that you can’t assign a value to an array element until you have declared the array with the Dim or ReDim statement.The InStr function will return the position of the first occurrence of the illegal character within the strInput variable. While the condition is true (the string was found). in the Immediate window. enter text in cell A1. which is optional. 1) = "_" The Mid function returns a specified number of characters from a string. to specify that we want to replace only one character. In this case it is the expression used in the previous statement.

as shown below: Sub IsThisArray() ' declare a dynamic array Dim sheetNames() As String Dim totalSheets As Integer Dim counter As Integer ' count the sheets in the current workbook totalSheets = ActiveWorkbook. Enter the code of the IsThisArray procedure. Using the IsArray Function 1.Count ' specify the size of the array ReDim sheetNames(1 To totalSheets) ' enter and show the names of sheets For counter = 1 to totalSheets sheetNames(counter) = ActiveWorkbook. Run the IsThisArray procedure. Insert a new module into the current project and rename it IsArray_Function.Name MsgBox sheetNames(counter) Next counter ' check if this is indeed an array If IsArray(sheetNames) Then MsgBox "The sheetNames variable is an array. . 2.Sheets(counter).Hands-On 8." End If End Sub 3.9.Sheets.

The following example shows how to erase the data from the array cities. the Erase function reallocates all of the memory assigned to a dynamic array. Using the Erase Function 1. you should use the Erase function.The Erase Function When you want to remove the data from an array. Enter the code of the FunCities procedure shown below: ' start indexing array elements at 1 Option Base 1 Sub FunCities() ' declare the array Dim cities(1 To 5) As String ' assign the values to array elements cities(1) = "Las Vegas" cities(2) = "Orlando" cities(3) = "Atlantic City" cities(4) = "New York" cities(5) = "San Francisco" ' display the list of cities MsgBox cities(1) & Chr(13) & cities(2) & Chr(13) _ & cities(3) & Chr(13) & cities(4) & Chr(13) _ . In addition. This function deletes all the data held by static or dynamic arrays. you must use the ReDim statement to specify the size of the array. 2.10. Insert a new module into the current project and rename it Erase_Function. Hands-On 8. If a procedure has to use the dynamic array again.

3. into the current project and 2. Run the FunCities procedure. Enter the code of the FunCities2 procedure shown below: Sub FunCities2() ' declare the array Dim cities(1 To 5) As String ' assign the values to array elements cities(1) = "Las Vegas" cities(2) = "Orlando" rename it .11.& cities(5) Erase cities ' show all that were erased MsgBox cities(1) & Chr(13) & cities(2) & Chr(13) _ & cities(3) & Chr(13) & cities(4) & Chr(13) _ & cities(5) End Sub After the Erase function deletes the values from the array. Hands-On 8. the MsgBox function displays an empty message box. Insert a new module L_and_UBound_Function. Using the LBound and UBound Functions 1. The LBound and UBound Functions The LBound and UBound functions return whole numbers that indicate the lower bound and upper bound of an array.

cities(3) = "Atlantic City" cities(4) = "New York" cities(5) = "San Francisco" ' display the list of cities MsgBox cities(1) & Chr(13) & cities(2) & Chr(13) _ & cities(3) & Chr(13) & cities(4) & Chr(13) _ & cities (5) ' display the array bounds MsgBox "The lower bound: " & LBound(cities) & Chr(13) _ & "The upper bound: " & UBound(cities) End Sub 3." MsgBox "The lower bound (second dimension) is " _ & LBound(Ex.5: MsgBox "The lower bound (first dimension) is " _ & LBound(Ex. 2) & ". 2) & ". add the following statements just above the End Sub keywords at the end of the Exchange procedure that was prepared in Hands-On 8." MsgBox " The upper bound(first dimension) is " _ & UBound(Ex. 1) & ". To determine the upper and lower indices in a two-dimensional array. Run the FunCities2 procedure." MsgBox " The upper bound(second dimension) is " _ & UBound(Ex." . 4. 1) & ".

When you run the procedure. Figure 8.When determining the lower and upper bound indices of a twodimensional array.4. ERRORS IN ARRAYS When working with arrays. VBA will display the error message “Subscript out of range. so it displays the error message. When you click the Debug button. you must specify the dimension number: 1 for the first dimension and 2 for the second dimension. This error was caused by an attempt to access a nonexistent array element. If you try to assign more values than there are elements in the declared array. Visual Basic can’t find the seventh element. .” as shown in Figure 8. Suppose you declare a one-dimensional array that consists of six elements and you are trying to assign a value to the seventh element.4. it’s easy to make a mistake. Visual Basic will highlight the line of code that caused the error.

Figure 8. Triggering an Error in an Array .5. In the example shown in Figure 8. you should begin by looking at the array’s declaration statement. it’s easy to figure out that the culprit is the index number that appears in the parentheses in the highlighted line of code. once we replace the line of code cities(7) = "Denver" with cities(6) = "Trenton" and press F5 to resume the procedure.12. When you click the Debug button in the error message. the procedure will run as intended.To fix this type of error. The procedure Zoo1 shown below serves as an example of such a situation. Once you know how many elements the array should hold. Hands-On 8. The error “Subscript out of range” is often triggered in procedures using loops.5. Visual Basic highlights the statement that triggered the error.

While executing this procedure. Sub Zoo2() ' this procedure avoids the error "Subscript out of range" Dim zoo(1 To 3) As String Dim i As Integer . 3. 2. The modified procedure Zoo2 demonstrates how using the LBound and UBound functions introduced in the preceding section can avoid errors caused by an attempt to access a nonexistent array element. enter the following procedure: Sub Zoo1() ' this procedure triggers an error "Subscript out of range" Dim zoo(1 To 3) As String Dim i As Integer Dim response As String i = 1 Do response = InputBox("Enter a name of animal:") zoo(i) = response i = i + 1 Loop Until response = "" End Sub Notice that the statements in the loop will be executed until the user cancels out from the input box. Insert a new module into the current project and rename it Errors_In_Arrays.1. Run the Zoo1 procedure. so the error message will appear. In the Errors_In_Arrays module. Visual Basic will not be able to find the fourth element in a three-element array when the variable i equals 4.

you learned that values can be passed between subroutines or functions as required or optional arguments. you’ll obtain the Type mismatch error during code execution. The following AddMultipleArgs function will add up as many numbers as you . PARAMETER ARRAYS In Chapter 5. declare the array as Variant. Later. however. keep in mind that each element of an array must be of the same data type. 10. To avoid this error. you don’t know in advance how many arguments you want to pass. To hold values of different data types in an array. Using the keyword ParamArray. or 15 numbers. the argument’s name is preceded by the keyword Optional. you can pass an array consisting of any number of elements to your subroutines and function procedures. Sometimes.Dim response As String i = 1 Do While i >= LBound(zoo) And i < = UBound(zoo) response = InputBox("Enter a name of animal:") If response = "" Then Exit Sub zoo(i) = response i = i + 1 Loop i = 0 For i = LBound(zoo) To UBound(zoo) MsgBox zoo(i) Next End Sub Another frequent error you may encounter while working with arrays is Type mismatch. A classic example is addition. If the passed argument is not absolutely required for the procedure to execute. you may use 3. You may want to add together two numbers. If you attempt to assign to an element of an array a value that conflicts with the data type of the array declared in the Dim statement.

24. Insert a new module into the current project and rename it ParameterArrays. The array must be declared as an array of type Variant. Passing an Array to Procedures Using the ParamArray Keyword 1. Some operations on arrays. In the ParameterArrays module. enter additional values inside the parentheses and press Enter. enter the following AddMultipleArgs function procedure: Function AddMultipleArgs(ParamArray myNumbers() As Variant) Dim mySum As Single Dim myValue As Variant For Each myValue in myNumbers mySum=mySum+myValue Next AddMultipleArgs = mySum End Function 3. Notice the use of the ParamArray keyword. activate the Immediate window and type the following instruction: ?AddMultipleArgs(1. Hands-On 8.13. 23. SORTING AN ARRAY We all find it easier to work with sorted data. 34) When you press Enter. 8. 3. You can supply an unlimited number of arguments. Notice that each function argument must be separated by a comma. To add more values. This function begins with the declaration of an array.24. myNumbers. 24. 2. Visual Basic returns the total of all the numbers in the parentheses: 93. To try out the above function. and it must be the last argument in the procedure definition. like .require.

And. the values entered in the worksheet are sorted in ascending order using the Excel Sort object. The sort statements have been generated by the macro recorder and then modified for this procedure’s needs. as in the following: y = myIntArray(UBound(myIntArray)) The minimum value can be obtained by reading the first value of the sorted array: x = myIntArray(1) So. Sub SortArrayWithExcel() Dim myIntArray() As Integer Dim i As Integer Dim x As Integer Dim y As Integer Dim r As Integer Dim myDataRng As Range 'initialize random number generator Randomize . you can load your sorted values back into a VBA array. and then using the built-in Sort function in Excel. After completing the sort.finding maximum and minimum values. Next. The following procedure populates a dynamic array with 10 random Integer values and prints out this array to an Immediate window and a new worksheet. An easy way to sort an array is copying your array values to a new worksheet. Once sorted. it is also faster than the classic bubble sort routine (demonstrated in Hands-On 8. Once it is sorted. the procedure redeclares the array variable using the ReDim statement. with a large array. The last statements in the procedure demonstrate how to retrieve the minimum and maximum values from the array variable. This technique is the simplest since you can use a macro recorder to get your sort statement started for you. require that the array is sorted.14). how can you sort an array? This section demonstrates two methods of getting your array data into the sorted order. you can find the maximum value by assigning the upper bound index to the sorted array. Before reloading the array with the sorted values. the Erase statement is used to free the memory used by the dynamic array.

SetRange myDataRng .UsedRange With ActiveSheet.Sort .Clear .Print "aValue" & i & ":" & vbTab & myIntArray(i) Next 'write array to a worksheet Worksheets. 1).SortFields.ReDim myIntArray(1 To 10) ' Fill the array with 10 random numbers between 1 and 100 For i = 1 To 10 myIntArray(i) = Int((100 * Rnd) + 1) Debug. _ DataOption:=xlSortNormal .Add r = 1 'row counter With ActiveSheet For i = 1 To 10 Cells(r. _ SortOn:=xlSortOnValues.Add Key:=Range("A1").SortFields.Value = myIntArray(i) r = r + 1 Next i End With 'Use Excel Sort to order values in the worksheet Set myDataRng = ActiveSheet. Order:=xlAscending.

Cells(i.Apply End With 'free the memory used by array by using Erase statement Erase myIntArray ReDim myIntArray(1 To 10) 'load sorted values back into an array For i = 1 To 10 myIntArray(i) = ActiveSheet.Header = xlNo .Print "aValueSorted: " & myIntArray(i) Next 'find minimum and maximum values stored in the array x = myIntArray(1) y = myIntArray(UBound(myIntArray)) .. 1).MatchCase = False .Value Next 'write out sorted array to the Immediate Window i = 1 For i = 1 To 10 Debug.

14. To create a sorted set.Print "Min value=" & x & vbTab. and swap them if they are in the wrong order. it may be more desirable to sort your data without moving it into a worksheet. Hands-On 8. A bubble sort is a comparison sort.6.14 demonstrates how to delegate the sorting task to a classic bubble sort routine. As a result of this sorting algorithm. Hands-On 8. compare each pair of adjacent items. Figure 8. In the Sorting module. sort it and load it back into a VBA array. you step through the list to be sorted. Insert a new worksheet in the Practice_Excel08. the smaller values “bubble” to the top of the list. Insert a new module into the current project and rename it Sorting. Sorting an Array 1. "Max value=" & y End Sub It takes time to write the array to a worksheet.6. 2. Example data used in Hands-On 8.14. 3.Debug. enter the two procedures (ResortedArray and .xlsm workbook and enter example data as shown in Figure 8. Depending on your needs.

UsedRange 'get the count of nonempty cells (text and numbers only) last = myDataRng.SpecialCells(xlCellTypeConstants. 3).Count If IsEmpty(myDataRng) Then MsgBox "Sheet is empty.Value < > "" Then . Sub ResortedArray() Dim myDataRng As Range Dim myArray() As Variant Dim cnt As Integer Dim i As Integer Dim cell As Variant Dim r As Integer Dim last As Integer Set myDataRng = ActiveSheet.BubbleSort) shown below." Exit Sub End If ReDim myArray(1 To last) i = 1 'fill the array from worksheet data 'reformat all numeric values as currency For Each cell In myDataRng If cell.

#00.If IsNumeric(cell.Value = myArray(i) r = r + 1 Next i End With End Sub Sub BubbleSort(myArray As Variant) Dim i As Integer Dim j As Integer Dim uBnd As Integer Dim Temp As Variant uBnd = UBound(myArray) .Add r = 1 'row counter With ActiveSheet For i = 1 To UBound(myArray) Cells(r.Value.Value) Then myArray(i) = Format(cell. "$#.00") Else myArray(i) = cell.Value End If i = i + 1 End If Next 'call the procedure to sort array BubbleSort myArray 'empty the sorted array into a new worksheet Worksheets. 1).

When the Visual Basic code window appears. then items are swapped using the following assignment statements: Temp = myArray(j) myArray(j) = myArray(i) myArray(i) = Temp To understand how the BubbleSort routine accomplishes the sort. press F8 to execute each statement.1 For j = i + 1 To uBnd If UCase(myArray(i)) > UCase(myArray(j)) Then Temp = myArray(j) myArray(j) = myArray(i) myArray(i) = Temp End If Next j Next i End Sub Notice that after populating the myArray variable with the worksheet data. see Chapter 10 for more information on various methods of testing and debugging VBA procedures.For i = LBound(myArray) To uBnd . array values are converted to uppercase using the VBA UCase function. The sort results are shown in Figure 8. Also. If the test result is true. Use the Immediate window to query Visual Basic for the values of the variables. The inner loop begins by using the greater-than comparison operator to determine whether the value stored in the first element of the array is greater than the value stored in the array’s second element. the procedure passes the filled array to the BubbleSort routine. . 4.7. For comparison. run the ResortedArray procedure in Debug mode (see Step 4). select ResortedArray and click Step Into. Switch to the sheet where you entered the data and choose Developer | Macros. which contains two For…Each loops. 5. In the Macro dialog box.

When the array is passed using the ByVal keyword. Therefore. Sub ManipulateArray() Dim countries(1 To 6) As Variant Dim countriesUCase As Variant . Here is the calling procedure and the function. let’s assume you have a list of countries.7. You want to convert the country names stored in your array to uppercase and keep the original array intact. Any modifications performed within the function will only affect the copy. the array in the calling procedure will not be modified.14. For example. Data entered in Figure 8.6 has been resorted using the procedures in Hands-On 8. PASSING ARRAYS TO FUNCTION PROCEDURES You can pass an array to a function procedure and return an array from a function. You can delegate the conversion process to a function procedure. the function will work with the copy of the original array.Figure 8.

Value = countriesUCase(i) Cells(r. 2).Dim i As Integer Dim r As Integer ' assign the values to array elements countries(1) = "Bulgaria" countries(2) = "Argentina" countries(3) = "Brazil" countries(4) = "Sweden" countries(5) = "New Zealand" countries(6) = "Denmark" countriesUCase = ArrayToUCase(countries) r = 1 'row counter With ActiveSheet For i = 1 To 6 Cells(r. 1).Value = countries(i) r = r + 1 Next i End With End Sub Public Function ArrayToUCase(ByVal myValues As Variant) _ As String() Dim i As Integer Dim Temp() As String If IsArray(myValues) Then ReDim Temp(LBound(myValues) To .

You also learned how to use a new keyword—ParamArray—and performed sorting of arrays using two methods. Erase. you will learn how to use collections instead of arrays to manipulate large amounts of data. you can write procedures that require a large number of variables. LBound. . and UBound. You now know all the control structures that can make your code more intelligent: conditional statements. IsArray. This chapter ended by introducing you to five built-in VBA functions that are frequently used with arrays: Array. You worked with examples of procedures that demonstrated how to declare and use a one-dimensional array (list) and a twodimensional array (table). loops. Finally. you learned that by creating an array. You also learned the difference between static and dynamic arrays. and arrays.UBound(myValues)) For i = LBound(myValues) To UBound(myValues) Temp(i) = CStr(UCase(myValues(i))) Next i ArrayToUCase = Temp End If End Function CHAPTER SUMMARY In this chapter. you saw how to pass one array and return another array from a function procedure. In the next chapter.

and count their elements. In this chapter.Chapter 9 Working with Collections and Class Modules Microsoft Excel 2013 offers a large number of built-in objects that you can access from your VBA procedures to automate many aspects of your worksheets. The usage of class modules to create user-defined objects will also be discussed. including its . you create a new object that has the properties and methods defined by the class. You are not by any means limited to using these built-in objects. Because collections have built-in properties and methods that allow you to add. Class—A definition of an object that includes its name. The solution is to create a custom collection object. Before diving into the theory and hands-on examples in this chapter. including how to declare a custom collection object. VBA allows you to create your own objects and collections of objects. and events. methods. Instance—A specific object that belongs to a class is referred to as an instance of the class. The class acts as a sort of object template from which an instance of an object is created at runtime. remove. you should become familiar with several terms: Collection—An object that contains a set of related objects. When you create an instance. they are much easier to work with. You already know from the previous chapter how to work with multiple items of data by using dynamic or static arrays. Class module—A module that contains the definition of a class. you will learn how to work with collections. you may come across a situation where there’s no built-in collection to handle the task at hand. properties. complete with their own methods and properties. While writing your own VBA procedures.

and each paragraph in a document is a member of the Paragraphs collection. for which you can define a response. A form module is a type of class module. For example. all open workbooks belong to the collection of Workbooks.Count VBA will return the total number of worksheets in the current workbook. for example. Event—An action recognized by an object. Form module—A module that contains the VBA code for all event procedures triggered by events occurring in a user form or its controls. For example. to refer to the second object in the collection of Worksheets.Select Worksheets("Sheet2"). WORKING WITH COLLECTIONS A set of similar objects is known as a collection. Event procedure—A procedure that is automatically executed in response to an event initiated by the user or program code or triggered by the system. Events can be caused by a user action or a VBA statement or can be triggered by the system. when . you can do the following: Refer to a specific object in a collection by using an index value. and all the sheets in a particular workbook are members of the Worksheets collection.property and method definitions. all open documents belong to the Documents collection. In Microsoft Word. Insert new items into the collection by using the Add method. when you enter in the Immediate window the statement: ?Worksheets. Collections are objects that contain other objects.Select Determine the number of items in the collection by using the Count property. such as a mouse click or a keypress. In Microsoft Excel. use either of the following statements: Worksheets(2). For example. Module—A module containing sub and function procedures that are available to other VBA procedures and are not related to any object in particular. No matter what collection you want to work with.

you could write the following procedure: Sub DeleteSheets() Dim ws As Worksheet Application. This variable is declared with the New keyword in the Dim statement.” “Weekly wages.Delete End If Next End Sub Declaring a Custom Collection To create a user-defined collection.Add VBA will insert to the current workbook a new worksheet. you should begin by declaring an object variable of the Collection type. after] .DisplayAlerts = False For Each ws In Worksheets If InStr(ws. The Worksheets collection now contains one more item.” To delete the worksheets that contain the word “wages” in the name. Suppose that you opened a workbook containing five worksheets with the following names: “Daily wages.” “Monthly wages. Cycle through every object in the collection by using the For Each… Next loop. before.Name. key. "wages") Then ws.Add item[.you enter in the Immediate window the statement: Worksheets. you can insert new items into the collection by using the Add method. as shown below: Dim collection_name As New Collection Adding Objects to a Custom Collection After you’ve declared the Collection object with the Dim keyword.” “Yearly salary.” “Bonuses. The Add method looks like this: object.

If you want to specify the position of the object in the collection. Click outside the comment frame to exit the comment edit mode. The before argument is the object before which the new object is added. For instance. you should use either a before or after argument (do not use both). if you are creating a collection of custom sheets. The objects with which you populate your collection do not have to be of the same data type. Instead of accessing a specific item with an index (1. Please note files for the “Hands-On” project may be found on the companion CDROM. The object is the collection name. The after argument is the object after which the new object is added. Open a new workbook and C:\Excel2013_ByExample\Practice_Excel09.1. However. you can assign a key for that object. It’s important to understand that the items in a collection are automatically assigned numbers starting with 1.You are only required to specify the object and the item. you could use a sheet name as a key. you could use Social Security numbers as a key. This is the same name that was used in the declaration of the Collection object. You should now have four comments in . they can also be assigned a unique key value.xlsm. Use the same technique to enter two comments in Sheet2. Right-click any cell in Sheet1 and choose Insert Comment from the shortcut menu. Hands-On 9. Although other arguments are optional. and so on) at the time an object is added to a collection. Enter different text for each comment. Type any text you want. 3. The GetComments procedure shown below declares the custom collection object called colNotes. save it as 2. To identify an individual in a collection of students or employees. The item is the object that you want to add to the collection. Using a Custom Collection Object 1. Add a comment in any cell on Sheet3. they are quite useful. 2. Add two new sheets to the workbook.

When you’re done entering the comment text. Click the File tab and choose Options. enter one comment anywhere on Sheet2 and one comment anywhere on Sheet3.Add Item:=myNote. Add a new module to the current project and rename it MyCollection. key:="first" . as shown below: Sub GetComments() Dim sht As Worksheet Dim colNotes As New Collection Dim myNote As Comment Dim i As Integer Dim t As Integer Dim strName As String strName = InputBox("Enter author’s name:") For Each sht In ThisWorkbook. Now. enter the GetComments procedure. return to the Excel Options window and change the User name text box entry back to the way it was (your name). In the Excel Options window’s General section. In the MyCollection module.Select i = ActiveSheet.Comments If myNote. Switch to the Visual Basic Editor and rename the VBA project ObjColClass. Delete your name and enter Joan Smith.Comments. 3. in the area named “Personalize your copy of Microsoft Office.” you should see a text box with your name. then click OK.Count For Each myNote In ActiveSheet.Count = 0 Then colNotes. 6. 4.Text If colNotes. These comments should be automatically stamped with Joan Smith’s name.three worksheets. 5.Author = strName Then MsgBox myNote.Worksheets sht.

Else colNotes. Only comments entered by the specified author are added to the custom collection. Notice how the key argument is used in referencing an item in a collection. Text functions (Mid and Len) are used to get only the text of the comment . the procedure prompts for an author’s name and then loops through all the worksheets in the active workbook to locate this author’s comments.Count < > 0 Then MsgBox colNotes("first"). the procedure displays a message box with the text of the comment that was identified with the special key argument.Print "Comments by " & strName For Each myNote In colNotes Debug.Author) + 2. The procedure then prints the text of all the comments included in the collection to the Immediate window.Count Debug.Text MsgBox "Total comments in workbook: " & t & Chr(13) & _ "Total comments in collection: " & colNotes.Text. _ Len(myNote. If the collection includes at least one comment.Print Mid(myNote. The procedure assigns a key to the first comment and then adds the remaining comments to the collection by placing them before the comment that was added last (notice the use of the before argument). Len(myNote.Add Item:=myNote.Text)) Next End Sub The above procedure begins by declaring the custom collection object called colNotes. Next. Before:=1 End If End If Next t = t + i Next If colNotes.

Run the GetComments procedure twice each time supplying a different name of the commenting author. Removing Items from a Custom Collection 1. Next.Remove item The object is the name of the custom collection that contains the object you want to remove. The second statement declares the variable myID to store the index number of the Collection object. To remove an object. At the end of this procedure. The item is the object you want to remove from the collection.without the author’s name. To demonstrate the process of removing an item from a collection. 7.2. You will use this variable to store the result of the MsgBox function. Add the following lines to the declaration section of the GetComments procedure: Dim response Dim myID As Integer The first statement declares the variable called response. Removing Objects from a Custom Collection Removing an item from a custom collection is as easy as adding an item. let’s modify the GetComments procedure that you prepared in the preceding section. Locate the following statement in the GetComments procedure: For Each myNote In colNotes Precede the above statement with the following line of code: . and ask the user whether the item should be removed from the collection. Check the procedure results in the Immediate window. the total number of comments in a workbook and the total number of comments in the custom collection are returned by the Count property. 2. use the Remove method in the following format: object. we’ll display the contents of the items that are currently in the colNotes collection one by one. Hands-On 9.

is shown below. Enter the following statements at the end of the procedure before the End Sub keywords: Debug. _ Len(myNote.Remove Index:=myID Else myId = myID + 1 End If 4. vbYesNo + vbQuestion) If response = 6 Then colNotes.Text)) Enter the following block of instructions below that statement: response = MsgBox("Remove this comment?" & Chr(13) _ & Chr(13) & myNote. It does not delete the comments from the worksheets. _ Len(myNote.Author) + 2.Text)) Next The revised GetComments procedure.Print Mid(myNote. Len(myNote.Print "The following comments remain in the collection:" For Each myNote in colNotes Debug.Text. named GetComments2.Print Mid(myNote.myID = 1 3. Note that this procedure removes the specified comments from the custom collection. Sub GetComments2() Dim sht As Worksheet Dim colNotes As New Collection .Author) + 2.Text.Text. Len(myNote. Locate the following statement in the GetComments procedure: Debug.

Select i = ActiveSheet.Dim myNote As Comment Dim i As Integer Dim t As Integer Dim strName As String Dim response Dim myID As Integer strName = InputBox("Enter author’s name:") For Each sht In ThisWorkbook.Text If colNotes.Count < > 0 Then MsgBox colNotes("first").Text MsgBox "Total comments in workbook: " & t & Chr(13) & _ .Count = 0 Then colNotes.Worksheets sht.Comments. key:="first" Else colNotes.Comments If myNote.Add Item:=myNote.Count For Each myNote In ActiveSheet.Author = strName Then MsgBox myNote.Add Item:=myNote. Before:=1 End If End If Next t = t + i Next If colNotes.

Len(myNote.Count Debug.Author) + 2.Count Debug.Print "Comments by " & strName myID = 1 For Each myNote In colNotes Debug.Author) + 2. _ Len(myNote. vbYesNo + vbQuestion) If response = 6 Then colNotes."Total comments in collection:" & colNotes.Text)) response = MsgBox("Remove this comment?" & Chr(13) _ & Chr(13) & myNote.Text.Print "The following comments remain in the collection:" For Each myNote In colNotes Debug. Len(myNote.Text.Remove index:=myID Else myID = myID + 1 End If Next MsgBox "Total notes in workbook: " & t & Chr(13) & _ "Total notes in collection: " & colNotes.Text.Print Mid(myNote.Print Mid(myNote. _ Len(myNote.Text)) Next .

To delete all comments from the workbook. as in the following example: Do While myCollection. you’ve used standard modules to create subroutine and function procedures.Comments myComment.Remove Index:=1 Loop Creating Custom Objects Notice that there are two module commands available in the Visual Basic Editor’s Insert menu: Module and Class Module. Run the GetComments2 procedure and remove one of the comments displayed in the message box. You’ll use the class module for the first . to remove all objects from a custom collection. the comments will still be present in the workbook.Worksheets For Each myComment In sht. you can use 1 for the Index argument. Therefore.Delete Next Next End Sub Reindexing Collections Collections are reindexed automatically when an object is removed.End Sub 5. So far. Therefore.Count > 0 myCollection. Keep in mind that this procedure only manipulates the custom collection of comments and not the actual comments you entered in the workbook. after deleting the comments via the above code. run the following code: Sub DeleteWorkbookComments() Dim myComment As Comment Dim sht As Worksheet For Each sht In ThisWorkbook.

If you refer back to the beginning of this chapter. title. and Salary.xlsm) in the Project Explorer window . You can also change the properties of each instance of a class independently of any other instance of the same class. You can create the properties for your custom objects by writing property procedures in a class module. However. The object methods are also created in a class module by writing the sub or function procedures. you must first create a new instance of that class. We will start by creating a class module. position. Just as you can cut out many cookies using the same cookie cutter. complete with custom properties and methods.1a. The CEmployee object will have properties such as ID. A method is an action that the object can perform. you can use it in the same way you use other built-in objects. before you do so. you can create multiple instances of a class. A class module lets you define your own custom classes. Custom Project 9. Creating a Class Module 1. Select ObjColClass (Practice_Excel09. and so on. A frequently used analogy is comparing an object class to a cookie cutter. After building your object in the class module. Object instances are the cookies. Each object instance has the characteristics (properties and methods) defined by its class. the definition of the class determines how a particular object should look and behave. Before you can actually use an object class. Recall that a property is an attribute of an object that defines one of its characteristics. It will also have a method for modifying the current salary. you will see that we described a class as a sort of object template. Creating a new. You can also export the object class outside the VBA project to other VBAcapable applications CREATING A CLASS The remaining sections of this chapter demonstrate the process of creating and working with a custom object called CEmployee. Be sure to perform all the exercises.time in this chapter to create a custom object and define its properties and methods. Just as a cookie cutter defines what a particular cookie will look like. FirstName. This object will represent an employee. such as shape. nonstandard VBA object involves inserting a class module into your VBA project and adding code to that module. you need a basic understanding of what a class is. LastName. color.

Custom Project 9. Variables in a class module are called data members and are declared with the Private keyword. The name you choose for your class should be easily understood and identify the “thing” the object class represents. the next step is to declare the variables that will hold the data you want to store in the object. Because the name of a variable also serves as a property name.and choose Insert | Class Module.” Variable Declarations After adding and renaming the class module. Naming a Class Module Every time you create a new class module. This keyword ensures that the variables will be available only within the class module.1b. Type the following declaration lines at the top of the CEmployee class module: ' declarations . Set the name of the class module to the name you want to use in your VBA procedures that use the class. As a rule. Highlight the Class 1 module in the Project Explorer window and use the Properties window to rename the class module CEmployee. Using the Private keyword instead of the familiar Dim statement hides the data members and prevents other parts of the application from referencing them. Each item of data you want to store in an object should be assigned a variable. Only the procedures within the class module in which the variables were defined can modify the value of these variables. use meaningful names for your object’s data members. It’s traditional to preface the variable names with m_ to indicate that they are data members of a class. Let’s continue with our project by declaring data members for our CEmployee class. 2. Declaring Members of the CEmployee Class 1. the object class name is prefaced with an uppercase “C. give it a meaningful name.

the property procedures contain the following parts: A procedure declaration line that specifies the name of the property and the data type: Property Get LastName() As String LastName is the name of the property and As String determines the data type . The Property Get procedure can have the same name as the Property Let procedure. Property procedures are executed when an object property needs to be set or retrieved. There are three types of property procedures: Property Let allows other parts of the application to set the value of a property. You should create property procedures for each property of the object that can be accessed by another part of your VBA application. you must add special property procedures to the CEmployee class module. This means that the VBA procedures from outside the class module will not be able to set or read data stored in those variables. The easiest of the three types of property statements to understand is the Property Get procedure. To enable other parts of your VBA application to set or retrieve the employee data. Defining the Properties for the Class Declaring the variables with the Private keyword guarantees that the variables cannot be directly accessed from outside the object. Property Set is used instead of Property Let when setting the reference to an object. As a rule. Let’s examine the syntax of the property procedures by taking a closer look at the Property Get LastName procedure. Property Get allows other parts of the application to get or read the value of a property.Private m_LastName As String Private m_FirstName As String Private m_Salary As Currency Private m_ID As String Notice that the name of each data member variable begins with the prefix m_.

first and last names. just below the declaration section. If the retrieved value is obtained as a result of a calculation. you would certainly like to get information about the employee ID.of the property’s return value. Writing Property Get Procedures for the CEmployee Class 1. Custom Project 9. and current salary. An assignment statement similar to the one used in a function procedure: LastName = m_LastName LastName is the name of the property. Type the following Property Get procedures in the CEmployee class module. and m_LastName is the data member variable that holds the value of the property you want to retrieve or set.1c. Let’s continue with our project by writing the necessary Property Get procedures. Property Get ID() As String Id = m_ID End Property Property Get LastName() As String . The m_LastName variable should be defined with the Private keyword at the top of the class module. When working with the CEmployee object. Creating the Property Get Procedures The CEmployee class object has four properties that need to be exposed to VBA procedures that reside in other modules in the current VBA project. you can include the appropriate VBA statement: Property Get Royalty() Royalty = (Sales * Percent) .Advance End Property The End Property keywords that specify the end of the property procedure.

the CEmployee class will only have three properties (LastName. Hence.LastName = m_LastName End Property Property Get FirstName() As String FirstName = m_FirstName End Property Property Get Salary() As Currency Salary = m_Salary End Property Notice that each type of the needed employee information requires a separate Property Get procedure. the Exit Property keywords give you a way to immediately exit from a property procedure. Property Let. or Property Set procedure. Suppose you don’t want the user to change the employee ID. you simply don’t write a Property Let procedure for it. Let’s continue with our project and write the required Property Let procedures . Like function procedures. you must assign it to the function’s name. Immediate Exit from Property Procedures Just like the Exit Sub and Exit Function keywords allow you to exit early from a subroutine or a function procedure. Creating the Property Let Procedures In addition to retrieving values stored in data members (private variables) with Property Get procedures. As you recall from Chapter 5. you must prepare corresponding Property Let procedures to allow other procedures to change the values of these variables as needed. and Salary). to return a value from a function procedure. Each of these properties will require a separate Property Let procedure. The Property Get procedure is similar to a function procedure. Program execution will continue with the statements following the statement that called the Property Get. However. FirstName. Each of the above Property Get procedures returns the current value of the property. To make the ID read-only. you don’t need to define a Property Let procedure if the value stored in a private variable is meant to be read-only. the Property Get procedures contain an assignment statement.

to indicate that . This parameter can be passed by value (see the ByVal keyword in the Property Let Salary procedure shown above) or by reference (ByRef is the default). you created a read-only ID property that can be retrieved but not set. Writing Property Let Procedures for the CEmployee Class 1. or Static keyword before the name of a property procedure to define its scope. Defining the Scope of Property Procedures You can place the Public. Private. By skipping the Property Let procedure for the ID property.1d. If you need a refresher on the meaning of these keywords. The data type of the parameter passed to the Property Let procedure must have exactly the same data type as the value returned from the Property Get or Set procedure with the same name.for our custom CEmployee object. Custom Project 9. Type the following Property Let procedures in the CEmployee class module: Property Let LastName(L As String) m_LastName = L End Property Property Let FirstName(F As String) m_FirstName = F End Property Property Let Salary(ByVal dollar As Currency) m_Salary = dollar End Property The Property Let procedures require at least one parameter that specifies the value you want to assign to the property. Notice that the Property Let procedures have the same name as the Property Get procedures prepared in the preceding section. see the section titled “Passing Arguments by Reference and Value” in Chapter 5. For example.

use the following statement format: Public Property Get FirstName() As String To make the Property Get procedure accessible only to other procedures in the module where it is declared. Also. property procedures are public by default. Methods allow you to manipulate the data stored in a class object. Creating the Class Methods Apart from properties. _ . Methods are created with the sub or function procedures. To make a method available outside the class module. Type the following CalcNewSalary function procedure in the CEmployee class module: Public Function CalcNewSalary(choice As Integer. The CEmployee object that you create in this chapter has one method that allows you to calculate the new salary. Assume that the employee salary can be increased or decreased by a specific percentage or amount. use the following statement format: Private Property Get FirstName() As String To preserve the Property Get procedure’s local variables between procedure calls. A method is an action that the object can perform. Let’s continue with our project by writing a class method that calculates the employee salary. the values of local variables are not preserved between the procedure calls.the Property Get procedure is accessible to other procedures in all modules. objects usually have one or more methods. use the following statement format: Static Property Get FirstName() As String If not explicitly specified using either Public or Private. use the Public keyword in front of the sub or function definition. Writing Methods for the CEmployee Class 1. if the Static keyword is not used.1e. Custom Project 9.

The curSalary argument is the current salary figure for an employee. Property Let.curSalary As Currency. which is called an object. a VBA procedure from outside the class module must pass three arguments: choice. you are ready to create a new instance of a class. Before an object can be created. however. an object variable must be declared in a standard module to store the reference to the object. and amount. If the name of the class module is CEmployee. Creating an Instance of a Class After typing all the necessary Property Get. Suppose you want to increase the employee salary by 5% or by $5. the object isn’t instanced until you refer to it in your procedure code by assigning a value to its property or running one of its methods. a new instance of this class can be created with the following statement: Dim emp As New CEmployee The emp variable will represent a reference to an object of the CEmployee class. To calculate a new salary. and function procedures for your VBA application in the class module. When you declare the object variable with the New keyword. The choice argument specifies the type of the calculation. and the second option will add the specified amount to the current salary. sub. The first option will increase the salary by the specified percentage. You can also create an instance of the object by declaring an object variable with . and amount determines the value by which the salary should be changed. VBA creates the object and allocates memory for it. amount As Long) As Currency Select Case choice Case 1 ' by percent CalcNewSalary = curSalary + ((curSalary + amount)/100) Case 2 ' by amount CalcNewSalary = curSalary + amount End Select End Function The CalcNewSalary function defined with the Public keyword in a class module serves as a method for the CEmployee class. curSalary.

The Initialize event is generated when an object is created from a class (see the preceding section on creating an instance of a class).1f. Writing the Initialize Event Procedure for the CEmployee Class 1. These events are triggered when an instance of the class is created and destroyed. Because the statements included inside the Initialize event are the first ones to be executed for the object before any properties are set or any methods are executed. respectively. the Initialize event is a good place to perform initialization of the objects created from the class. In the CEmployee class example. You can use the Initialize event to assign a unique five-digit number to the m_ID variable. Let’s continue with our project by adding the Initialize event procedure to our CEmployee class. Custom Project 9.the data type defined to be the class of the object as in the following: Dim emp As CEmployee Set emp = New CEmployee You will create an instance of the class CEmployee later in this chapter when we proceed to write our application code in a form class module. Event Procedures in the Class Module An event is basically an action recognized by an object. enter the following Class_Initialize procedure: Private Sub Class_Initialize() Randomize m_ID = Int((99999 . the ID is read-only in the CEmployee class. the Initialize event will also fire the first time that you use the emp variable in code. In the CEmployee class module. Custom classes recognize only two events: Initialize and Terminate.10000) * Rnd + 10000) End Sub . As you recall.

as well as the Randomize statement. This is a good place to perform any necessary cleanup tasks. We will create the form shown in Figure 9. .beginning_number) * Rnd + beginning_number) The Class_Initialize procedure also uses the Randomize statement to reinitialize the random number generator. If you have written a Terminate event procedure.1 and later hook it up with our custom CEmployee object. For more information on using the Rnd and Int functions. To generate a random integer between two given integers where ending_number = 99999 and beginning_number = 10000. any code in this event is executed then. T he Terminate event occurs when all references to an object have been released. Creating a Form for Data Collection Implementing your custom CEmployee object requires that you design a custom form.T he Class_Initialize procedure initializes the CEmployee object by assigning a unique five-digit number to the variable m_ID. the following formula is used: =Int((ending_number . use the following syntax: Set objectVariable = Nothing When you set the object variable to Nothing. search the online help. the Terminate event is generated. The Class_Terminate procedure uses the following syntax: Private Sub Class_Terminate() [cleanup code goes here] End Sub To release an object variable from an object.

Custom Project 9. While creating custom forms is covered in detail in Chapter 19. 2. Make the form larger by positioning the mouse on the selection handle in the bottom right-hand corner and dragging it to the right and down.” use the following guidelines for a quick introduction to this subject.1g. Creating a User Form for the CEmployee Object 1.Figure 9.1. .1. “Creating Custom Forms. Make the form big enough to hold all the controls and labels shown in Figure 9. Highlight the current VBA project in the Project Explorer window and choose Insert | UserForm. This form demonstrates the use of the CEmployee custom object. A blank form should appear with UserForm1 in its title bar.

1. In the VBE Properties window. Find out how to place toolbox controls on the user form by reading the section titled “Placing Controls on a Form” in Chapter 19. A small toolbox should appear on the screen with standard Visual Basic buttons that can be placed on the user form. 6. Now that all the controls and labels are placed on the form. Familiarize yourself with the controls in the toolbox by reading the section titled “Tools for Creating User Forms” in Chapter 19.1.1.3. Now that you’ve got some background information on working with user forms. Use the same technique to add all the remaining controls and labels to the form. you need to set the form and control properties listed in Table 9. Drop it at a position shown in Figure 9. To set each of these properties: On the form. click on the object listed in the Object column in Table 9. Table 9.1. 4.1. replace the property setting in the second column with the value stated in the Setting column in Table 9. locate the object’s property name listed in the Property column in Table 9. Choose View | Toolbox. Setting the properties for the custom form . 5. click the Text Box control in the toolbox and drag it to the form.1. In the VBE Properties window. 7.

2. the next step requires the preparation of the data entry worksheet shown in Figure 9. .Creating a Worksheet for Data Output Now that the user form is ready.

We also need to write a function to locate employee data in a worksheet.2. Writing Code behind the User Form With the form and worksheet ready. Writing Code for the UserForm . Custom Project 9. Custom Project 9. Prepare a Salaries data entry worksheet as shown in Figure 9. Data entered on the Employees and Salaries form will be transferred to the worksheet.Figure 9. We will need an event procedure to initialize the controls on the form and several click event procedures that will run when users click the form’s buttons.1h. 2. all that is left to do for the CEmployee class implementation is writing the necessary procedures in the form class module.2.1i. Creating a Worksheet for Data Transfer 1. Insert a new worksheet to the current workbook and rename it Salaries.

Switch back to the Visual Basic Editor window and double-click the form background to activate the form module. You can also click the View Code button in the Project Explorer window when the form is selected. ' Global declarations Dim emp As New CEmployee Dim CEmployees As New Collection Dim index As Integer Dim ws As Worksheet Dim extract As String Dim cell As Range Dim lastRow As Integer Dim empLoc As Integer Dim startRow As Integer Dim endRow As Integer Dim choice As Integer Dim amount As Long The first statement declares the variable emp as a new instance of the CEmployee class.Enabled = False .SetFocus cmdEmployeeList.1. Enter the following variable declarations at the top of the Code window of the Salaries form just below the Option Explicit statement. The CEmployees collection will be used to store employee data. Type the following UserForm_Initialize procedure to enable or disable controls on the form: Private Sub UserForm_Initialize() ' enable or disable firm controls txtLastName. The second statement declares a custom collection. 3. Other variables declared here will be used by VBA procedures assigned to various controls on the form. 2.Visible = False lboxPeople.

Enabled = False optHighlighted.Enabled = False Frame2.Value = "" optPercent.Value = False optAmount.Enabled = False optPercent.Enabled = False optAll.Enabled = False txtRaise.Enabled = False End Sub .Enabled = False cmdUpdate.Frame1.Enabled = False cmdDelete.Enabled = False optAmount.Value = False txtRaise.

Figure 9.Value = "" Then MsgBox "Enter Last Name.Value = "" Or txtFirstName.Figure 9. First Name and . The UserForm_Initialize procedure disables certain controls so they cannot be used when the form is first loaded.Value = "" Or _ txtSalary.3.3 shows the result of the statements inside the UserForm_Initialize procedure that enable only the desired controls when the form is first loaded. 4. Enter the following cmdSave_Click procedure to transfer the data entered on the form to the spreadsheet: Private Sub cmdSave_Click() 'transfer form data to spreadsheet If txtLastName.

" Exit Sub End If Worksheets("Salaries").Rows.ID . 4).UsedRange.FirstName = txtFirstName Cells(index.Formula = emp.Salary." txtLastName.Formula = emp." txtSalary.Count + 1 lboxPeople.FirstName .Salary CEmployees.Add emp .LastName = txtLastName Cells(index.SetFocus Exit Sub End If If Not IsNumeric(txtSalary) Then MsgBox "You must enter a value for the Salary.Enabled = True ' set and enter data into the CEmployees collection With emp Cells(index.Formula = emp. 3).Formula = emp.Salary = CCur(txtSalary) If .SetFocus Exit Sub End If If txtSalary < 0 Then MsgBox "Salary cannot be a negative number. 2). 1).LastName .Salary = 0 Then Exit Sub Cells(index.Select index = ActiveSheet.

Enabled = True txtLastName.Enabled = True optHighlighted. construct.. and Salary properties are set based on the data entered in the corresponding text boxes. Each time VBA sees the reference to the instanced emp object. VBA transfers the employee data to the Employee Salaries worksheet. FirstName.Enabled = True optAmount. . and Salary text boxes.Value = True cmdUpdate. The last section of this chapter demonstrates how to walk through this procedure step by step to see exactly when the property procedures are executed. The LastName.End With ' delete data from text boxes txtLastName = "" txtFirstName = "" txtSalary = "" ' enable hidden controls cmdEmployeeList.. and the ID property is set with the number generated by the Class_Initialize event procedure. The last statement inside the With emp. After setting the object property values..Enabled = True cmdDelete. a new instance of the CEmployee class is created.Enabled = True txtRaise. If the user entered correct data.SetFocus End Sub The cmdSave_Click procedure starts off with validating the user’s input in the Last Name. VBA assigns to the variable index the number of the first empty row on the Employee Salaries worksheet.Enabled = True Frame1..Enabled = True optAll. First Name.Enabled = True optPercent. it will call the appropriate Property Let procedure in the class module. The next statement enables the form’s list box control. When the program reaches the With emp .Enabled = True Frame2.

This statement causes the automatic execution of the cmdEmployeeList_Click procedure attached to the Update List command button. $" & _ Format(emp.FirstName & ".4.00") Next emp End Sub The cmdEmployeeList_Click procedure is attached to the Update List command button. " & _ emp.Clear For Each emp In CEmployees lboxPeople. the cmdEmployeeList_Click procedure begins by clearing the contents of the list box and then populates it with the items stored in the custom collection CEmployees. Visual Basic clears the form’s text boxes and enables command buttons that were turned off by the UserForm_Initialize procedure. Type the cmdEmployeeList_Click procedure. Next. " & emp. this is the only control that the user never sees. "0. as shown in Figure 9. As we will see when we run our project later.ID & ".Salary. 5.AddItem emp. Notice the first instruction in this block: cmdEmployeeList.LastName & ". (By the way.Value = True.) The code for this procedure is shown in Step 21. . as shown here: Private Sub cmdEmployeeList_Click() ' add new employee data to list box lboxPeople. This button is controlled by the cmdSave_Click procedure and causes the new employee data to be added to the list box control.construct adds the user-defined object emp to a custom collection called CEmployees.

Figure 9. 6. the employees you enter will become members of a new CEmployees collection. Type the following cmdClose_Click procedure: Private Sub cmdClose_Click() ' remove the user form from the screen Unload Me End Sub The cmdClose_Click procedure allows you to remove the user form from the screen and finish working with the custom collection of employees. The list box control displays employee data as entered in the custom collection CEmployees. . When you run the form again.4.

Delete (3) MsgBox "There are " & CEmployees.Count & _ " items in the CEmployees collection.ListIndex + 1)." End If End Sub .7.Count = 0 Then Call UserForm_Initialize End If Else MsgBox "Click the item you want to remove. Type the following cmdDelete_Click procedure: Private Sub cmdDelete_Click() ' remove an employee from the CEmployees custom collection ' make sure that an employee is highlighted in the ' list control If lboxPeople.Item(lboxPeople." cmdEmployeeList.Value = True If CEmployees.Count & " items.ListIndex + 1 MsgBox "The CEmployees collection has now " & _ CEmployees.Remove lboxPeople.ListIndex > -1 Then MsgBox "Selected item number: " & lboxPeople.ID MsgBox extract Call FindId MsgBox empLoc Range("A" & empLoc). " CEmployees.ListIndex extract = CEmployees.

The cmdDelete_Click procedure contains several MsgBox statements that allow you to examine the contents of the list box control as you make deletions. _ Cells(endRow. the cmdDelete_Click procedure must also remove the corresponding row of employee information from the worksheet. Locating the employee data in the worksheet is handled by the FindId function.UsedRange. Type the following function procedure: Private Function FindId() ' return number of list box selected row Set ws= ActiveWorkbook.) This function returns to the cmdDelete_Click procedure the row number that has to be deleted.Count For Each cell In ws. The employee is removed from both the collection and the list box.Sheets("Salaries") startRow = ActiveSheet. 8. This procedure makes sure that the list box contents are refreshed. the cmdEmployeeList_Click procedure is automatically executed.UsedRange.Count endRow = ActiveSheet.Row FindId = empLoc Exit Function End If Next .Count + _ 1 . 1)) If cell. When you click a list item.Rows. 1).Value = extract Then empLoc = cell. you must click the appropriate item in the list box.Range(Cells(startRow. (The code of this procedure is in Step 24.The cmdDelete_Click procedure lets you remove an employee from the CEmployees custom collection. In addition to removing the employee from the custom collection.Rows.CEmployees. If the list box contains only one employee. VBA calls the UserForm_Initialize procedure to disable certain form controls after removing the last employee from the collection. To delete an employee.

You don’t want to search the entire used area of the worksheet. The search for the employee ID is limited to the first worksheet column and begins with the row containing the first collection item." Exit Sub End If If lboxPeople.Value = True And _ optAmount.Value = False Then MsgBox "Click the 'Highlighted Employee’ or " _ & " 'All Employees’ option button. The search for the data in the worksheet is based on the contents of the variable extract that stores the unique employee number.ListIndex < > -1 And _ optHighlighted.SetFocus Exit Sub End If If optHighlighted." txtRaise. 9. Type the following cmdUpdate_Click procedure: Private Sub cmdUpdate_Click() If optHighlighted." Exit Sub End If If Not IsNumeric(txtRaise) Then MsgBox "This field requires a number.End Function The FindId function procedure returns to the calling procedure the row number of the employee selected in the form’s list box.Value = False And optAll.Value = True And _ txtRaise.Value = True And _ lboxPeople.Value < > "" Then . This approach makes the search faster.ListIndex = -1 Then MsgBox "Click the name of the employee.

ListIndex + 1).Salary _ + (CEmployees.Item(lboxPeople.Salary cmdEmployeeList.Salary = _ CEmployees. _ CEmployees.ListIndex + _ .Item(lboxPeople. _ Item(lboxPeople.Item(lboxPeople. amount) Range("D" & empLoc).Item(lboxPeople.CalcNewSalary(choice.Value = True And _ txtRaise.ID MsgBox extract Call FindId MsgBox empLoc CEmployees.Value = True ElseIf lboxPeople.ListIndex + 1).extract = CEmployees.ListIndex < > -1 And _ optHighlighted.Salary.ID MsgBox extract Call FindId MsgBox empLoc choice = 2 amount = txtRaise CEmployees.Value = True And _ optPercent.Item(lboxPeople.Formula = CEmployees.ListIndex + 1).Item(lboxPeople.ListIndex + 1).ListIndex + 1).ListIndex + 1).Item(lboxPeople.Value < > "" Then extract = CEmployees.ListIndex + 1).Salary = _ emp.

Value = True And _ optPercent.ListIndex + 1).Value < > "" Then For Each emp In CEmployees emp.ID MsgBox extract Call FindId MsgBox empLoc Range("D" & empLoc).Formula = emp.Value = True And _ optAmount.Salary + txtRaise extract = emp.Salary Next emp cmdEmployeeList.Value = True ElseIf optAll.Formula = CEmployees.Value < > "" Then For Each emp In CEmployees emp.Value = True And _ txtRaise.Salary * txtRaise / 100) Range("D" & empLoc).Value = True And _ txtRaise.Salary * _ txtRaise) / 100) extract = emp.Value = True ElseIf optAll.Formula = .Salary = emp.Salary + ((emp.1).ID MsgBox extract Call FindId MsgBox empLoc Range("D" & empLoc).Salary = emp. _ Item(lboxPeople.Salary cmdEmployeeList.

you can decrease the salary by the specified percentage or dollar amount.Salary Next emp cmdEmployeeList.6. The salary modification is also reflected in the worksheet. . as shown in Figure 9. Figure 9.emp. you can modify the salary by the specified percentage or amount.Value = True Else MsgBox "Enter data or select an option. Updating the employee information in the form also updates the worksheet. By entering a negative number in the text box. Depending on which options are specified. which has been increased by 10%. The cmdUpdate_Click procedure checks whether the user selected the appropriate option buttons and entered the increase value in the text box. The update can be done for the selected employee or all the employees listed in the list box control and collection. either by a percentage or amount. the Salary amount is updated for one employee or all the employees." End If End Sub With the cmdUpdate_Click procedure.5 displays a new value for the salary of Roberta Olsen.

.Figure 9. The employee salary can be increased or decreased by the specified percentage or dollar amount.5.

Show End Sub . Working with the Custom CEmployee Class The application using a custom CEmployee class is now ready. Insert a standard module into the current project by choosing Insert | Module.1j. Type the following procedure in the WorkAndPay module to display the Employees and Salaries form: Sub ClassDemo() Salaries. To make it easy to work with the user form. When you update the employee information in the form.6. 2. the relevant data is also updated in the worksheet.Figure 9. Writing a Procedure to Display the User Form 1. Custom Project 9. Rename this module WorkAndPay. we’ll write a one-line procedure in the standard module that shows the form.

In the next section. Treat this exercise as a brief introduction to the debugging techniques that are covered in detail in Part IV. In the Project Explorer window. 2. you can view your form by clicking the form’s background and pressing F5.1k. as shown in Figure 9. When the Salaries (Code) window appears. Watching the Execution of Your VBA Procedures To help you understand what’s going on when your code runs and how your custom object works. or you can place a button in a worksheet and assign the ClassDemo procedure to it.Value = "" Or _ txtSalary. select the Salaries form and click the View Code button at the top of this window. Until then. Custom Project 9.Value = "" Or txtFirstName. we’ll step through the ClassDemo procedure to see what happens when you run the code. let’s step through the cmdSave_Click procedure. select the cmdSave procedure from the combo box at the top left-hand side of the window. 3. Walking through the CEmployee Application Code 1. Set a breakpoint by clicking in the left margin next to the following line of code.Value = "" Then . If txtLastName.7.

5. First Name. 4. A red circle in the margin indicates a breakpoint. highlight the WorkAndPay module and click the View Code button. 6. Place the cursor anywhere inside the ClassDemo procedure and press F5. and Salary text boxes. or choose Run | Run Sub/UserForm. In the Project Explorer window. When the form appears. enter data in the Last Name.8. it automatically switches to the Code window and displays the text of the line as white on a red background. Visual Basic should now switch to the Code window because it encountered the breakpoint in the first line of the cmdSave_Click procedure. When VBA encounters the statement with a breakpoint.7. . as shown in Figure 9. and click the Save button on the form.Figure 9.

Step through the code one statement at a time by pressing F8. Visual Basic runs the current statement and then automatically advances to the next statement and suspends execution. Keep pressing F8 to execute the procedure step by step. it switches to the Class_Initialize procedure. 7. it switches to the Code window and displays a yellow arrow in the margin to the left of the statement at which the procedure is suspended and highlights the statement in yellow.Figure 9.9.8. When Visual Basic encounters a breakpoint while running a procedure. . The current statement is indicated by a yellow arrow in the margin and a yellow background. as shown in Figure 9. When Visual Basic encounters the With emp statement.

10.9.Figure 9. it goes out to execute the Class_Initialize procedure.ID. VBA returns to the cmdSave_Click procedure. When Visual Basic encounters the reference to the object variable emp. as shown in Figure 9.10. Reading properties of your custom object is accomplished through the Property Get procedures. 1). Figure 9. . When Visual Basic encounters the statement Cells(Index. After executing the statements inside this procedure. it executes the Property Get ID procedure in the CEmployee class module.Formula = emp.

you saw how to make the class module available to the user by building a custom form. You also learned how to write a method for your custom object.8. . Enter data for a new employee and click the Save button. and you saw how to define your custom object’s properties using Property Get and Property Let procedures. 10. you learned how to analyze your VBA application by stepping through its code. as well as locate the source of errors in your procedures. 9. Using the F8 key. 11. This chapter concludes Part III. you learned how to create and use your own objects and collections in VBA procedures. VBA Debugging Tools Visual Basic provides a number of debugging tools to help you analyze how your application operates. Finally. You used a class module to create a user-defined (custom) object. choose Debug | Clear All Breakpoints. See the chapters in Part IV for details on working with these tools. Now press F5 to run the rest of the procedure without stepping through it. trace the execution of the cmdSave_Click procedure to the end. CHAPTER SUMMARY In this chapter. At this time. the yellow highlight is turned off. “Keeping Track of Multiple Values.xlsm button on the Windows taskbar at the bottom of the screen to return to the active form. When VBA encounters the end of the procedure (End Sub).” In the next chapter. either press Alt+F11 or click the Microsoft Excel Practice_Excel09. When Visual Basic displays the Code window. Click the Close button on the Salaries form to exit the application. Next. you will learn how to troubleshoot your VBA procedures.

and testing and debugging VBA procedures. . there is always a chance that incorrectly constructed or typed code. In this part of the book. you’ll learn about various methods of handling errors.Part 4 Error Handling And Debugging Chapter 10 VBE Tools for Testing and Debugging Chapter 11 Conditional Compilation and Error Trapping While you may have planned to write a perfect VBA procedure. will cause your program to fail or produce unexpected results. or perhaps logic errors.

This chapter introduces you to the Visual Basic Editor tools that are available for you to use in the process of analyzing the code of your VBA procedures and locating the source of errors. logic errors. To get to sections of code that interest you. finding errors wasn’t very difficult. and runtime errors. and less frustrating. locating the source of errors in longer and more complex procedures is more tedious and time consuming. add a watch expression. step through your code one line at a time by pressing F8.Chapter 10 VBE Tools for Testing and Debugging It does not take much for an error to creep into your VBA procedure. you learned that there are three types of errors in VBA: syntax errors. To monitor the value of a particular variable or expression used by your procedure. The truth is that no matter how careful you are it is rare that all of your VBA procedures will work correctly the first time. use the following guidelines: To analyze your procedure. Fortunately. In Chapter 3. use a breakpoint. When testing your VBA procedure. However. Debugging is the process of locating and fixing those errors by stepping through the code of your procedure or checking the values of variables. or choose Debug | Step Into. set up a bookmark to jump quickly to . TESTING VBA PROCEDURES Because most of the procedures we wrote earlier were quite short. Bugs are errors in computer programs. faster. Visual Basic Editor provides a set of handy tools that can make the process of tracking down your VBA problems easier. To locate an error in a specific place in your procedure.

1. The error dialog box shown in Figure 10. do one of the following: Press the Ctrl+Break key combination Set one or more breakpoints Insert the Stop statement into your procedure code Add a watch expressionA break occurs when the execution of your VBA procedure is temporarily suspended.the desired location. you enter into what is called break mode. The buttons in this dialog are described in Table 10. This can be done simply by pressing the Esc key. VBA also offers other methods of stopping your procedure. Stopping a Procedure While testing your VBA procedure you may want to halt its execution. Error dialog buttons . Table 10. To enter break mode.1 informs you that the procedure was halted. Visual Basic remembers the values of all variables and the statement from which the execution of the procedure should resume when the user decides to continue by clicking Run Sub/UserForm on the toolbar (or the Run menu option with the same name) or by clicking the Continue button in the dialog box.1. When you stop your procedure. Each of these guidelines is demonstrated in a hands-on scenario in this chapter. which causes Visual Basic to stop your program and display the message shown in Figure 10.1.

At this point. you can step through the procedure code line by line by pressing F8 or choosing Debug | Step Into. Using Breakpoints If you know more or less where you can expect a problem in the code of your procedure. nothing happens. You can prevent application users from halting your procedure by including the following statement in the procedure code: Application.Figure 10. This message appears when you press Esc or Ctrl+Break while your VBA procedure is running. let’s look at the following scenario. To see how this works.1. suspend code execution on a given line by pressing F9 to set a breakpoint on that line. the following line of code could get you in trouble: ActiveCell. When VBA gets to that line while running your procedure.EnableCancelKey = xlDisabled When the user presses Esc or Ctrl+Break while the procedure is running. Assume that during the execution of the ChangeCode procedure in Hands-On 10.FormulaR1C1 . it will immediately display the Code window.1. The Application object’s EnableCancelKey property disables these keys.

Examine the data in both workbooks.xlsx) from the C:\Excel2013_ByExample folder. 3.xlsx!R1C1:R6C2.2. 2.2)" Please note files for the “Hands-On” project may be found on the companion CDROM.xlsm workbook from the C:\Excel2013_HandsOn folder to your C:\Excel2013_ByExample folder. Copy the Practice_Excel10.Codes.2 and 10. Start Microsoft Excel and open both these files (Practice_Excel10. Codes. Figure 10. 4.xlsm. It should look similar to Figures 10. Copy the Codes. The data entered in column D of this spreadsheet will be . Setting Breakpoints in a VBA Procedure 1. Hands-On 10."=VLOOKUP(RC[1].3.1.xlsx workbook from the C:\Excel2013_HandsOn folder to your C:\Excel2013_ByExample folder.

Leave the other file open.Open Filename:="C:\Excel2013_ByExample\Codes. 6. With Practice_Excel10.3.xlsm) project and double-click the Breaks module.FormulaR1C1 = _ .Select ActiveCell. Figure 10. switch to the Visual Basic Editor window.SpecialCells(xlBlanks).xlsm active. In the Project Explorer. 7. 5.xlsx" Windows("Practice_Excel10. The Breaks module Code window lists the following ChangeCode procedure: Sub ChangeCode() Workbooks. open the Modules folder in the Debugging (Practice_Excel10.Insert Shift:=xlToRight Range("D1").xlsm").xlsx workbook.3.replaced by the ChangeCode procedure with the data illustrated in Figure 10. Close the Codes.Activate Columns("D:D").Formula = "Code" Columns("D:D"). The ChangeCode procedure uses this code table for lookup purposes.

Codes.FillDown With Columns("D:D") . The color of the breakpoint can be changed on the Editor Format tab in the Options dialog box (Tools menu). Set a breakpoint by pressing F9 (or choosing Debug | Toggle Breakpoint or clicking in the margin indicator to the left of the line).2)" Selection.Select End With Selection.Copy Selection.AutoFit .xlsx!R1C1:R6C2.xlsx!R1C1:R6C2.Orientation = xlHorizontal End With Workbooks("Codes. .FormulaR1C1 = "=VLookup(RC[1]. the line that has the breakpoint is indicated as white text on a red background as is in Figure 10. At the same time. Visual Basic displays a red circle in the margin.HorizontalAlignment = xlCenter .VerticalAlignment = xlBottom . When you set the breakpoint. In the ChangeCode procedure.4."=VLookup(RC[1]. click anywhere on the line containing the following statement: ActiveCell.Codes.Close End Sub 8.PasteSpecial Paste:=xlValues Rows("1:1").xlsx").Select With Selection .2)" 9.EntireColumn.

When you run the procedure. and the statement inside a box with a yellow background. Visual Basic will execute all the statements until it encounters the breakpoint.4. the margin displays both indicators overlapping one another (the circle and the arrow).5 shows the yellow arrow in the margin to the left of the statement at which the procedure was suspended. Press F5 to run the ChangeCode procedure. Figure 10.Figure 10. 10. . If the current statement also contains a breakpoint. The arrow and the box indicate the current statement or the statement that is about to be executed. The line of code where the breakpoint is set is displayed in the color specified on the Editor Format tab in the Options dialog box.

When the procedure finishes executing. and more. you can change code. If you change certain code while you work in break mode.Figure 10. When Visual Basic is in break mode. Visual Basic does not automatically remove the breakpoint. skip lines. . proceed anyway?” You can click OK to stop the program’s execution and proceed editing your code. Notice that the line of code with the VLookup function is still highlighted in red. When Visual Basic encounters a breakpoint. set the next statement. 11. Press F5 (or choose Run Sub/UserForm) to continue running the procedure. execute the procedure one line at a time. Visual Basic leaves break mode and continues to run the procedure statements until it reaches the end of the procedure. VBA will prompt you to reset the project by displaying the following error message: “This action will reset your project. add new statements. all of the options on the Debug menu are available. While in break mode. use the Immediate window. or click Cancel to delete the new changes and continue running the code from the point at which it was suspended.5. it displays the Code window and indicates the current statement.

If you had set several breakpoints in a given procedure and would like to remove only one or some of them. .6. The breakpoints are automatically removed when you close the file. click on the line containing the breakpoint that you want to remove and press F9 (or choose Debug | Clear Breakpoint or simply click the red dot in the margin). 12.In this example you have set only one breakpoint. This worksheet was modified by the ChangeCode procedure in Hands-On 10. All the breakpoints are removed. like the one in Figure 10. Visual Basic allows you to set any number of breakpoints in a procedure. You can also perform various tests by typing statements in the Immediate window. 13. Figure 10.6. you can suspend and continue the execution of your procedure as you please. When to Use a Breakpoint Consider setting a breakpoint if you suspect that your procedure never executes a certain block of code. This way. You can analyze the code of your procedure and check the values of variables while execution is suspended. Switch to the Microsoft Excel application window and notice that a new column with the looked up codes.1.xlsm workbook. Remove the breakpoint by choosing Debug | Clear All Breakpoints or by pressing Ctrl+Shift+F9 or by clicking on the red circle in the margin area to remove the breakpoint. You should clear the breakpoints when they are no longer needed. was added on Sheet1 of the Practice_Excel10.

In break mode. the Code window (break mode) appears. Because Visual Basic has already executed the statement that stores the name of ActiveWorkbook in the variable strName. For example. you can find out the value of a variable by resting the mouse pointer on that variable . The name of the variable and its current value appear in a tooltip frame. which is discussed later in this chapter. you can quickly find out the value of this variable by resting the mouse pointer over its name. in the VarValue procedure shown in Figure 10. you can quickly find out the contents of the variable at the cursor in the Code window by holding the mouse pointer over it.7. you . you should use the Locals window. Figure 10. When Visual Basic encounters this statement. Using the Immediate Window in Break Mode Once the procedure execution is suspended and the Code window appears. the breakpoint has been set on the Workbooks.Add statement. To show the values of several variables used in a procedure at once.7. In break mode.

you’ll have to begin by setting up breakpoints again. which cell is currently active or the name of the active sheet. for instance. When the code execution is suspended. you can find the values of your variables and execute additional commands by entering appropriate statements in the Immediate window. Figure 10. To postpone the task of testing your procedure until you re-open the .can activate the Immediate window and type VBA instructions to find out. Using the Stop Statement Sometimes you won’t be able to test your procedure right away. Figure 10. If you set up your breakpoints and then close the file. You can also use the Immediate window to change the contents of variables in order to correct values that may be causing errors.8 shows the suspended ChangeCode procedure and the Immediate window with the questions that were asked of Visual Basic while in break mode. Excel will remove your breakpoints.8. and the next time you are ready to test your procedure.

and the Code window will appear with the line highlighted. Figure 10. Visual Basic will suspend the execution of the StopExample procedure when it encounters the Stop statement.Assert statements. The screen will display the Code window in break mode. insert a Stop statement into your code wherever you want to halt a procedure.file. Using the Assert Statement A very powerful and easy to apply debugging technique is utilizing Debug. When you no longer need to stop your procedure.9 shows a Stop statement before the For Each…Next loop. Assertions allow you to write code that checks itself while running. it has one disadvantage—all Stop statements stay in the procedure until you remove them. you must locate and remove all the Stop statements. Assertions give you immediate feedback . Although the Stop statement has exactly the same effect as setting a breakpoint. The procedure will halt when it gets to the Stop statement. Figure 10. You can insert a Stop statement anywhere in the code of your VBA procedure. By including assertions in your programming code you can verify that a particular condition or assumption is true.9.

when an error occurs. Don’t assume anything—always test for validity of expressions and variables in your code.Assert statement takes any expression that evaluates to True or False and activates the break mode when that expression evaluates to False. Debug. After you have debugged and tested your code. The execution simply stops on that line of code and the VBE screen opens with the line containing the false statement highlighted so that you can start debugging your code.Assert does nothing if the condition is False or zero. If condition evaluates to False or 0 (zero). While you can stop the code execution by using the Stop statement (see the previous section). In the Replace With box. They are great for detecting logic errors early in the development phase instead of hearing about them later from your end users. in the Find What box. Conditional breakpoints can also be set by using the Watch window (see the next section).Assert i < > 50 Next End Sub Keep in mind that Debug.Assert condition where condition is a VBA code or expression that returns True or False. For example. The Debug. comment out or remove the Debug.Assert is shown below: Debug. it will only stop your code under specific conditions. Error handling procedures are covered in Chapter 11. You may need to write an error handler to handle the identified error. enter an apostrophe followed by Debug.Assert.Assert differs from the Stop statement in its conditional aspect. the code will stop executing when the variable i equals 50: Sub TestDebugAssert() Dim i As Integer For i = 1 To 100 Debug. enter Debug. The syntax for Debug.Assert. VBA will enter break mode. . when running the following looping structure. Just because your procedure ran on your system without generating an error does not mean that there are no bugs in that procedure. To comment out the statements. The easiest way to do this is to use Edit | Replace in the VBE editor screen.Assert statements from your final code.

perform the following: 1. USING THE WATCH WINDOW Many errors in procedures are caused by variables that assume unexpected values. In the Code window. The Add Watch dialog box contains three sections.2.To remove the Debug. 2. as shown in Figure 10.Assert in the Find What box. select the variable whose value you want to monitor. . Leave the Replace With box empty. Visual Basic offers a special Watch window that allows you to keep an eye on variables or expressions while your procedure is running. enter Debug.Assert statements from your code. To add a watch expression to your procedure. but be sure to mark the Use Pattern Matching check box. If a procedure uses a variable whose value changes in various locations. Choose Debug | Add Watch. you may want to stop the procedure and check the current value of that variable. which are described in Table 10. The screen will display the Add Watch dialog box.10.

The Add Watch dialog box allows you to define conditions that you want to monitor while a VBA procedure is running.2.10. Table 10. Add Watch dialog options .Figure 10.

The Breaks module Code window lists the following WhatDate procedure: Sub WhatDate() Dim curDate As Date Dim newDate As Date Dim x As Integer curDate = Date For x = 1 To 365 . you can simply put a watch expression on the variable and run your procedure as normal. Hands-On 10.2. Watches are extremely useful when you are not sure where the variable is being changed.You can add a watch expression before running a procedure or after execution of your procedure has been suspended. Instead of stepping through many lines of code to find the location where the variable assumes the specified value. Let’s see how this works. The difference between a breakpoint and a watch expression is the breakpoint always stops a procedure in a specified location and the watch stops the procedure only when the specified condition (Break When Value Is True or Break When Value Changes) is met. Watching the Values of VBA Expressions 1.

3. and you’ll be able to check the values of the desired variables. In the Expression text box. In the Watch Type section. select the Break When Value Is True option button. If you add watch expressions to the procedure.newDate = Date + x Next End Sub The WhatDate procedure uses the For…Next loop to calculate the date that is x days in the future. You have now added your first watch expression. What if all you want to do is to stop the program when the value of the variable x reaches 211? In other words. 2. it will be " & NewDate In this example. you won’t get any result unless you insert the following instruction in the code of the procedure: MsgBox "In " & x & " days. you don’t care to display the individual dates. Click OK to close the Add Watch dialog box. Now let’s add another expression to the Watch window that will allow us to track the current date. In the Context section. Visual Basic opens the Watch window and places your expression x = 211 in it. In the Code window. what date will be 211 days from now? To get the answer. however. you could insert the following statement into your procedure: If x = 211 Then MsgBox "In " & x & " days it will be " & NewDate Introducing new statements into your procedure just to get an answer about the value of a certain variable when a specific condition occurs will not always be viable. . enter the following expression: x = 211. 5. Visual Basic will stop the For…Next loop when the specified condition is met. 4. position the insertion point anywhere within the name of the curDate variable. you can use the Watch window and avoid extra code maintenance. Choose Debug | Add Watch. choose WhatDate from the Procedure combo box and Breaks from the Module combo box. day after day. If you run this procedure. Instead of adding MsgBox or other debug statements to your procedure code that you will later need to delete.

Position the insertion point anywhere inside the code of the WhatDate procedure. . Choose Debug | Add Watch and click OK to set up the default watch type with Watch Expression. We will also want to keep track of the newDate variable.6. position the insertion point anywhere within the name of the newDate variable. the WhatDate procedure contains the following three watches: x = 211—Break When Value is True curDate—Watch Expression newDate—Watch Expression 9. 7. Choose Debug | Add Watch and click OK to set up the default watch type with Watch Expression. In the Code window. Notice that newDate now appears in the Expression column of the Watch window. Figure 10. 8. and press F5. After performing the above steps.11 shows the Watch window when Visual Basic stops the procedure when x equals 211. Notice that curDate now appears in the Expression column of the Watch window.

Using the Watch window. 11. however. Click OK to close the Edit Watch dialog box. You can change the value of the expression again or finish running the procedure. You can press F5 to continue or you can ask another question. Notice that the value of the variable x in the Watch window is the same as the value that you specified in the Add Watch dialog. 12.Figure 10. and enter the following expression: x = 277. Choose Debug | Edit Watch. 10.11. The procedure is in break mode. Press F5 to continue running the procedure. such as “What date will be in 277 days?” The next step shows how to do this. In addition. Notice that the Watch window now displays a new value for the expression. . the newDate variable now contains a new value—a date that is 277 days from now. The value of curDate is the same. the Watch window shows the value of both variables—curDate and newDate. The procedure stops again when the value of x equals 277. x is now False.

position the insertion point anywhere inside the name of a . Removing Watch Expressions To remove the watch expressions. click on the expression in the Watch window that you want to remove and press Delete. The Quick Watch dialog box can be accessed in the following ways: While in break mode. when the watch expression is out of context.12. You may now remove all the watch expressions you had defined in the preceding example. Press F5 to finish running the procedure. USING QUICK WATCH In break mode you can check the value of an expression for which you have not defined a watch expression by using the Quick Watch dialog box displayed in Figure 10. it does not have a value.13. the Watch window displays the value of the watch expression. If you open the Watch window after the procedure has finished. The Quick Watch dialog box shows the value of the selected expression in a VBA procedure.12. you will see < out of context > instead of the variable values. In other words. Figure 10. When your procedure is running and a watch expression has a value.

See the section called “Removing Watch Expressions” for instructions on how to remove a watch expression from the Watch window. Choose Debug | Quick Watch Press Shift+F9 The Add button in the Quick Watch dialog box allows you to add the expression to the Watch window. In the Code window. position the mouse pointer inside the newDate variable and press Shift+F9. To check the values of these variables. Enter the following expression: x = 50. Notice that the Watch window does not contain the newDate or the curDate variables. Hands-On 10. The Quick Watch dialog shows the name of the expression and its current value. Choose Debug | Add Watch. . 5. or you can invoke the Quick Watch dialog box. In the WhatDate procedure. 6. Click Cancel to return to the Code window. 8. 2.variable or expression you wish to watch. Let’s find out how to work with this dialog box. Using the Quick Watch Dialog Box 1. Make sure that the WhatDate procedure you entered in the previous Hands-On exercise does not contain any watch expressions. 7. Choose the Break When Value Is True option button and click OK. 4.3. Visual Basic will suspend procedure execution when x equals 50. Run the WhatDate procedure. 3. position the insertion point on the name of the variable x. you can position the mouse pointer over the appropriate variable name in the Code window.

The third column displays the type of each declared variable. For class modules. You can also press Tab. Click Cancel to return to the Code window. The global variables and variables in other projects are not accessible from the Locals window. The second column shows the current values of variables. The Quick Watch dialog now shows the value of the variable curDate. USING THE LOCALS WINDOW AND THE CALL STACK DIALOG BOX If during the execution of a VBA procedure you want to keep an eye on all the declared variables and their current values. 13. you can change the value of a variable by clicking it and typing the new value. the first variable is the name of the current module. make sure you choose View | Locals Window before you run the procedure. Close the Watch window. When you click the plus sign. highlight the line containing the expression x = 50 and press Delete to remove it. 12. position the mouse pointer inside the curDate variable and press Shift+F9. After changing the value. or the up or down arrows. Shift+Tab. The Expression column displays the names of variables that are declared in the current procedure. The first row displays the name of the module preceded by the plus sign. the system variable Me is defined. In the Watch window. Figure 10. In the Code window. Press F5 to continue running the procedure. 11. . For standard modules. press Enter to register the change. The Locals window contains three columns.9.13 shows a list of variables and their corresponding values in the Locals window displayed while Visual Basic is in the break mode. you can check if any variables have been declared at the module level. 10. In this column. or click anywhere within the Locals window after you’ve changed the variable value.

. The Locals window displays the current values of all the declared variables in the current VBA procedure. Click anywhere inside the WhatDate procedure and press F8. perform the following Hands-On exercise.4.13. 2.Figure 10. Hands-On 10. Using the Locals and Call Stack Windows 1. you place the procedure in break mode. The Locals window displays the name of the current module and the local variables and their beginning values. By pressing F8. Choose View | Locals Window. To observe the values of variables in the Locals window.

the procedure name is automatically removed from the Call Stack dialog box. If a procedure calls another. The Call Stack dialog box is especially helpful for tracing nested procedures. Press F8 a few more times while keeping an eye on the Locals window.14. The Call Stack dialog box displays a list of the procedures that are started but not completed. Press F5 to continue running the WhatDate procedure.3. This option is only available in break mode. This allows you . 4. This button opens the Call Stack dialog box shown in Figure 10. You can use the Show button in the Call Stack dialog box to display the statement that calls the next procedure listed in the dialog box. STEPPING THROUGH VBA PROCEDURES Stepping through the code means running one statement at a time. Figure 10. Recall that a nested procedure is a procedure that is being called from within another procedure. 5. You can also activate the Call Stack dialog box by choosing View | Call Stack. the name of the called procedure is automatically added to the Calls list in the Call Stack dialog box. The Locals window also contains a button with three dots. An active procedure call is a procedure that is started but not completed.14. When Visual Basic has finished executing the statements of the called procedure. Close the Locals window. which displays a list of all active procedure calls.

If you don’t want Visual Basic to step through every statement.to check every line in every procedure that is encountered. which contains several options that allow you to execute a procedure in step mode. Visual Basic executes each statement until it encounters the End Sub keywords. you can press F5 at any time to run the rest of the procedure without stepping through it. place the insertion point anywhere inside the code of your procedure and choose Debug | Step Into or press F8.15 shows the Debug menu. . When you run a procedure one statement at a time. Figure 10. To start stepping through a procedure from the beginning.

Let’s step through a procedure line by line.15. The Debug menu offers many commands for stepping through VBA procedures.Figure 10. .

If you choose Debug | Step Over (Shift+F8) instead of Debug | Step Into (F8). Press F8 again to execute the selected statement.Hands-On 10. Watch window. . and the procedure execution will be halted again. Visual Basic will select the next statement. Visual Basic continues to display the Code window with the current procedure. Visual Basic will quickly execute all the statements inside the SpecialMsg procedure and select the next statement in the calling procedure (MyProcedure). Place the insertion point anywhere inside the code of the procedure whose execution you wish to trace. you can activate the Immediate window. 4. Stepping Over a Procedure and Running to Cursor Suppose that the current statement in MyProcedure calls the SpecialMsg procedure. You can also choose Run | Reset to stop the procedure at the current statement without executing the remaining statements. Continue stepping through the procedure by pressing F8. After executing this statement. 2. And. or you want to concentrate only on the new code that has not yet been debugged. if the procedure you are stepping through calls other procedures. Visual Basic executes each procedure as if it were a single statement. 3. During the execution of the SpecialMsg procedure. When you step over procedures (Shift+F8). Stepping through a VBA Procedure 1. Visual Basic executes the current statement and automatically advances to the next statement and suspends execution. Press F8 or choose Debug | Step Into. or press F5 to continue the code execution without stopping.5. or Locals window to see the effect of a particular statement on the values of variables and expressions. This option is particularly useful if a procedure contains calls to other procedures and you don’t want to step into these procedures because they have already been tested and debugged. While in break mode. you can activate the Call Stack window to see which procedures are currently active.

Close End Sub Sub SpecialMsg(n As String) If n = "Book2" Then MsgBox "You must change the name. Place the insertion point anywhere within the code of MyProcedure. Stepping Over a Procedure 1. Visual Basic quickly runs the SpecialMsg procedure and advances to the statement immediately after the call to the SpecialMsg procedure.Add strName = ActiveWorkbook. locate the following procedure: Sub MyProcedure() Dim strName As String Workbooks. Press Shift+F8. Add a breakpoint at the following statement: SpecialMsg strName 3. or choose Debug | Step Over." End If End Sub 2. 4.Name ' choose Step Over to avoid stepping through the ' lines of code in the called procedure SpecialMsg SpecialMsg strName Workbooks(strName). . Visual Basic halts execution when it reaches the breakpoint.Hands-On 10. In the Breaks module Code window.6. and press F5 to run it.

Step Over. Suppose that in MyProcedure (see the code of this procedure in the preceding section) you have set a breakpoint on the statement calling the SpecialMsg procedure. you may want to rerun previous lines of code in the procedure or skip over a section of code that is causing trouble.5.Close and press Ctrl+F9 (or choose Debug | Set Next Statement). 9. is used when you step into a procedure and then decide that you don’t want to step all the way through it. In the process of stepping through a procedure. When you halt execution of a procedure. Suppose you want to execute MyProcedure to the line that calls the SpecialMsg procedure. The option you select depends on which code fragment you wish to analyze at a given moment. 8. 7. you can switch between the Step Into. Visual Basic will skip execution of the statements between the selected statement and the statement where execution was suspended. The Debug menu’s Run To Cursor (Ctrl+F8) command lets you run your procedure until the line you have selected is encountered. you can use the Set Next Statement option on the Debug menu. Step Out (Ctrl+Shift+F8). Choose Debug | Run To Cursor. Another command on the Debug menu. you can resume the procedure from any statement you want. This command is really useful if you want to stop the execution before a large loop or you intend to step over a called procedure. Press Shift+F8 to step over the SpecialMsg procedure. Remove the breakpoint you set in Step 2. you can place the insertion point inside the statement Workbooks (strName). 6. Visual Basic will stop the execution of the MyProcedure code when it reaches the specified line. To skip the execution of the SpecialMsg procedure. When you choose this option. Click inside the statement SpecialMsg strName. In each of these situations. Visual Basic will execute the remaining statements in this procedure in one step and proceed to activate the next statement in the calling procedure. Press F5 to execute the rest of the procedure. Stepping over a procedure is particularly useful when you don’t want to analyze individual statements inside the called procedure. . and Step Out options. Press F5 to finish running the procedure without stepping through its code. 10. Setting the Next Statement At times.

The Show Next Statement option is available only in break mode. variable-length strings are initialized to a zero-length string (“”).You can’t use the Set Next Statement option unless you have suspended the execution of the procedure. Choose Run | Reset to finish the procedure without executing the remaining statements. All lines in between are ignored. you can: Press F5 to execute the remaining instructions without stepping through. all the variables lose their current values. When you use the Next Statement option. Numeric variables assume the initial value of zero. while stepping through the code of a procedure in the Code window. and the value of object variables is set to Nothing. you can choose Debug | Show Next Statement and Visual Basic will place the cursor on the line that will run next. Stopping and Resetting VBA Procedures At any time. This means that certain things that you may have expected to occur don’t happen. it should be done with care. When you reset your procedure. and you found out how the Locals window can help you monitor the values of variables and how the Call Stack dialog box can be helpful in keeping track of where . Variant variables are initialized to Empty. you learned how to test your VBA procedures to make sure they perform as planned. Showing the Next Statement If you are not sure from which statement the execution of the procedure will resume. which can lead to unexpected errors. and fixed-length strings are filled with the character represented by the ASCII character code 0 or Chr(0). While skipping lines of code can be very useful in the process of debugging your VBA procedures. You debugged your code by stepping through it using breakpoints and watches. You learned how to work with the Immediate window in break mode. This is particularly useful when you have been looking at other procedures and are not sure where execution will resume. you tell Visual Basic that this is the line you want to execute next. CHAPTER SUMMARY In this chapter.

Try to spend more time getting acquainted with the Debug menu options and debugging tools discussed in this chapter. Mastering the art of debugging can save you hours of trial and error. you can quickly pinpoint the problem spots in your procedures. .you are in a complex program. In the next chapter. By using the built-in debugging tools. you will learn additional debugging techniques for your VBA procedures.

You can tell Visual Basic to include or ignore certain blocks of code when compiling and running by using so-called conditional compilation. This chapter introduces additional techniques that you will find useful for debugging your Visual Basic applications. You can review the values of variables by using Watch expressions and the Locals and Immediate windows. and how you can add effective error-handling code to your procedures. To enable conditional compilation. Notice that the If and Else keywords are preceded by a number sign (#). And. To do this. with more complex procedures. you can use the Call Stack dialog box to view all active procedure calls and trace the execution of nested procedures. You can also perform the compilation of your entire VBA project manually before you run your procedure. False) constant. simply choose Debug | Compile (your VBA project name) in the Visual Basic Editor window. you can easily set a breakpoint to stop a program while it is running and use step options to run your code one statement at a time. Use the #Const directive to declare a Boolean (True. Next. UNDERSTANDING AND USING CONDITIONAL COMPILATION When you run a procedure for the first time. The portion of code that you want to compile conditionally must be surrounded by these directives. With these tools. check this constant inside the #If…Then…#Else directive. In particular. you will learn how conditional compilation can help you to include or ignore certain blocks of code.Chapter 11 Conditional Compilation and Error Trapping If you’ve worked through Chapter 10. use special expressions called directives. Visual Basic converts the VBA statements you used into the machine code understood by the computer. you should now know how to debug your code using the built-in VBE debugging tools. This process is called compiling. If a portion of code is to .

thus it has no effect on the size or performance of the program. Conditional compilation can be used to compile an application that will be run on different platforms (Windows or Macintosh.xlsm. To compile the program in the English language. 3. Win16-. Start Microsoft Excel and open a new workbook. In the procedure that follows. Win32-. Otherwise. Writing a VBA Procedure Using Conditional Compilation 1. Declare the conditional constant in the declaration section of the module like this: #Const User = True This declares the conditional constant named User. which returns the name of the day based on the supplied date. . In the Project Explorer window. Save the workbook file as C:\Excel2013_ByExample\Practice_Excel11. the value of the conditional constant has to be set to True (–1). all you have to do is change the conditional constant to False and Visual Basic will jump to the block of instructions located after the #Else directive. 4. the value of this constant should be set to False (0). Use the Properties window to rename Module1 Conditional.1. Choose Insert | Module to add a new module to the selected project. data is displayed in the Polish language when the conditional constant named verPolish is True. The WhatDay procedure calls the DayOfWeek function. The program code excluded during the conditional compilation is omitted from the final file. It is also useful in localizing an application for different languages or excluding certain debugging statements before the VBA application is sent off for distribution.xlsm). Switch to the Visual Basic Editor window. 2. In the Properties window. Win64-bit). Hands-On 11. Please note files for the “Hands-On” project may be found on the companion CD-ROM. rename the project Testing.be run. select VBAProject (Practice_Excel11.

5. _ "poniedzialek".g. "wtorek".. 06/04/2013")) MsgBox "To bedzie " & DayOfWeek(dayNr) & ". "piatek". In the Conditional module Code window. _ "czwartek". "sobota") End Function Function WeekdayName() As String Select Case Weekday(InputBox("Enter date. e. 06/04/2013")) Case 1 WeekdayName = "Sunday" Case 2 WeekdayName = "Monday" Case 3 . np. "niedziela". enter the following procedure and functions: ' declare a conditional compiler constant #Const verPolish = True Sub WhatDay() Dim dayNr As Integer #If verPolish = True Then dayNr = Weekday(InputBox("Wpisz date. "sroda"." #Else WeekdayName #End If End Sub Function DayOfWeek(dayNr As Integer) As String DayOfWeek = Choose(dayNr.

Because the conditional compilation constant (verPolish) is set to True at the top of the module. When you use the Project Properties dialog box shown in Figure 11. To run the English version of the code. you can choose Tools | Testing Properties. Instead of declaring the conditional compiler constants at the top of a module. and rerun the procedure. Then run the WhatDay procedure to see how the Else branch of your program is now executed for English-speaking users." End Function 6.1. Run the WhatDay procedure.WeekdayName = "Tuesday" Case 4 WeekdayName = "Wednesday" Case 5 WeekdayName = "Thursday" Case 6 WeekdayName = "Friday" Case 7 WeekdayName = "Saturday" End Select MsgBox "It will be " & WeekdayName & ". 7. It asks for the user’s input in Polish and displays the result in Polish. Visual Basic runs the Polish version of the WhatDay procedure. . use the following syntax in the Conditional Compilation Arguments text box to enable the English version of the WhatDay procedure: verPolish = 0 If there are more conditional compilation constants. 8. Comment out the #Const verPolish directive at the top of the module and enter the conditional compilation constant in the Project Properties dialog box as shown in Figure 11. set the verPolish constant to False. each of the constants must be separated by a colon.1.

. Using the built-in bookmark feature.1. but never in both places. you will often find yourself jumping to certain areas of code. NAVIGATING WITH BOOKMARKS In the process of analyzing or reviewing your VBA procedures. you can easily mark the spots in your code that you want to navigate between. Click anywhere in the statement that you want to define as a bookmark.Figure 11. The conditional compilation constant can be declared either at the top of the module or in the Project Properties dialog box. To set up a bookmark: 1.

you have to determine how your program will respond to errors. For example. Using bookmarks you can quickly jump between often-used sections of your procedures.2. TRAPPING ERRORS No one writes bug-free programs the first time. click anywhere in the bookmarked statement and choose Edit | Bookmarks | Toggle Bookmark or click the Toggle Bookmark button on the Edit toolbar. Visual Basic displays an error message . Many unexpected errors happen during runtime. Once you’ve set up two or more bookmarks. Choose Edit | Bookmarks | Toggle Bookmark. When you create VBA procedures.2. If an error occurs when the procedure is running. Visual Basic will place a blue. or click the Toggle Bookmark button on the Edit toolbar as illustrated in Figure 11. you can jump between the marked locations of your code by choosing Edit | Bookmarks | Next Bookmark or simply by clicking the Next Bookmark button on the Edit toolbar. Runtime errors are often discovered by users who attempt to do something that the programmer has not anticipated. You can remove bookmarks at any time by choosing Edit | Bookmarks | Clear All Bookmarks or by clicking the Clear All Bookmarks button on the Edit toolbar. your procedure may try to give a workbook the same name as an open workbook. rounded rectangle in the left margin beside the statement. To remove a single bookmark. Figure 11.2.

This way. In programming. Exit Property. can be removed from your program through proper testing and debugging. if your VBA procedure accesses a particular file on disk and someone has deleted this file or moved it to another location. Depending on the type of procedure. or End Property. For example. you’ll get an error no matter what. instead of displaying a default error message. On Error statement options . An error is the result of an event or an operation that doesn’t work as expected. mistakes and errors are not the same thing. Exit Function. You can prevent users from seeing many runtime errors by including error-handling code in your VBA procedures. End Function.1 shows how the On Error statement can be used. You should write an error-handling routine for each procedure. End Sub.and the procedure is stopped. A mistake. it will show a much friendlier and more comprehensive error message. Table 11. Table 11.1. such as a misspelled or missing statement. An error prevents the procedure from carrying out a specific task. this does not mean that errors will not occur. or assigning a value of one type to a variable of a different (and incompatible) type. Most often. How should you implement error handling into your VBA procedure? The first step is to place the On Error statement in your procedure. But even though your code may be free of mistakes. This statement tells VBA what to do if an error occurs while your program is running. the error message that VBA displays is quite cryptic to the user. you can exit the error trap by using one of the following statements: Exit Sub. a misplaced quote or comma. when Visual Basic encounters an error. VBA uses the On Error statement to activate an error-handling procedure that will trap runtime errors.

enter the Archive procedure as shown below: Sub Archive() Dim folderName As String Dim MyDrive As String Dim BackupName As String Application. "File Archive" Else With ActiveWorkbook If Not .DisplayAlerts = False On Error GoTo ErrorHandler folderName = ActiveWorkbook.2: Writing a VBA Procedure with Error-Handling Code (Example 1) 1. _ vbInformation.Save . Hands-On 11. Insert a new module into the Testing project and rename it Traps. The procedure uses the built-in SaveCopyAs method to save the copy of the current workbook to a file without modifying the open workbook in memory.". " & Chr(13) _ & "This file has not been saved.Saved Then . In the Traps module Code window.The Archive procedure shown below uses an error-handling routine (see the bottom of the procedure). 2.Path If folderName = "" Then MsgBox "You can’t copy this file.

)". "Disk Drive or " & _ "Folder does not exist" ProcEnd: Application. "D:\") If MyDrive < > "" Then If Right(MyDrive. _ "Archive Location?". . etc.DisplayAlerts = True End Sub After the declaration of variables. 1) < > "\" Then MyDrive = MyDrive & "\" End If BackupName = MyDrive & .MyDrive = InputBox("Enter the Pathname:" & _ Chr(13) & "(for example: D:\.". Please try again. _ vbInformation + vbOKOnly.Name & " was copied to: " _ & MyDrive. "End of Archiving" End If End With End If GoTo ProcEnd ErrorHandler: MsgBox "Visual Basic cannot find the " & _ "specified path (" & MyDrive & ")" & Chr(13) & _ "for the archive.SaveCopyAs Filename:=BackupName MsgBox . " & _ "E:\MyFolder\.DisplayAlerts = False ensures that Visual Basic . the statement Application.Name .

Run the Archive procedure several times. If the active workbook’s path is not an empty string.Save statement to save the active workbook. a specified drive/folder may not exist. the procedure will end. specifies a label to jump to when an error occurs. For example. Visual Basic executes the statement Application. On Error GoTo ErrorHandler. The specified pathname is then stored in the variable MyDrive. USING THE ERR OBJECT Your error-handling code can utilize various properties and methods of the Err . Next. then Visual Basic will append the backslash to the end of the pathname specified in the MyDrive variable. This function returns a specified number of characters from the right side of a string. Saved is a VBA property of the Workbook object. This is done via the Right function. Next. If the user entered a path. If Visual Basic can’t find the workbook’s path. Use various debugging techniques that you learned in Chapter 10. Because there are no more statements to execute. it will copy the active workbook to that location and will notify the user that the copy operation was successful. If the last character of the supplied pathname is not a backslash. or a drive may not have sufficient free space left. Notice that the label name is followed by a colon. the procedure ends. As you know.won’t display its own alerts and messages while the procedure is running. Visual Basic uses the InputBox function to prompt the user for the location of the archive. which directs it to the ProcEnd label located just before the End Sub keywords.DisplayAlerts = True. The pathname where the active workbook was saved is stored in the variable folderName. If they weren’t. which restores the system’s built-in alerts and messages. Visual Basic jumps to the statement following the End If and executes the instruction GoTo ProcEnd. When Visual Basic detects an error. 3. If the user canceled the input box. each time responding differently to the presented options. If VBA can find the specified pathname. it jumps to the line of code beginning with the label ErrorHandler and an appropriate message is displayed. Be sure to test as many possibilities as you can identify. we need to ensure that the specified string ends with the backslash character (\).Saved Then . The content of the MyDrive variable is then combined with the name of the active workbook and stored in the variable named BackupName. all kinds of things can go wrong while copying files. it assumes the file was not saved and displays an appropriate message. VBA uses the If Not . Visual Basic checks whether the recent changes in the workbook have already been saved. The next statement.

to raise the “Disk not ready” error.Clear statement to reset Err.3: Writing a VBA Procedure with Error-Handling Code (Example 2) 1. To test your error-handling code you can use the Raise method of the Err object. use the Err. The Number property of the Err object will tell you the value of the last error that occurred. For example.Raise 71 The OpenToRead procedure shown below demonstrates the use of the Resume Next and Error statements. enter the OpenToRead procedure as shown below: Sub OpenToRead() Dim myFile As String Dim myChar As String Dim myText As String Dim FileExists As Boolean FileExists = True On Error GoTo ErrorHandler myFile = InputBox("Enter the name of file you want to open:") Open myFile For Input As #1 If FileExists Then Do While Not EOF(1) of file ' loop until the end . check the value of Err. to check which error occurred.object. as well as the Err object. For example. After handling the error. In the Traps module Code window. Hands-On 11. You can also find the name of the application that caused the error by using the Source property of the Err object (this is very helpful when your procedure launches other applications).Number.Number back to zero. use the following statement: Err. and the Description property will return a description of the error.

" Case 75 Exit Sub Case Else MsgBox "Error " & Err." Case 53 MsgBox "This file can’t be found on the " & _ "specified drive.Number) Exit Sub End Select Resume Next End Sub The purpose of the OpenToRead procedure is to read the contents of the usersupplied text file character by character (working with files is covered in detail .Number & " :" & Error(Err.Number Case 76 MsgBox "The path you entered cannot be found. #1) character ' get one myText = myText + myChar ' store in the variable myText Loop Debug.Print myText Immediate window Close #1 ' print to the ' close the file End If Exit Sub ErrorHandler: FileExists = False Select Case Err.myChar = Input(1.

the variable FileExists is set to True. the filename or the path may be wrong. save the file as C:\Excel2013_ByExample\Vacation. or the user may try to open a file that is already open. 2. the statement Err. This means that before you . the error-handling routine at the end of the OpenToRead procedure uses the Number property of the Err object.Number) and error description (Error (Err. If an error occurs while the procedure is running. if VBA encounters an error. Visual Basic will display user-friendly messages stored inside the Select…Case block and then proceed to the Resume Next statement. Notice the Exit Sub statement before the ErrorHandler label. Put the Exit Sub statement just above the errorhandling routine because you don’t want Visual Basic to carry out the error handling if there are no errors. Use Windows Notepad to prepare a text file. all the instructions inside the If FileExists Then block will be executed. If another error occurs. 53. 3. the value of the FileExists variable will be set to False (see the first statement in the error-handling routine just below the ErrorHandler label). For example. Run the OpenToRead procedure three times in step mode (using the F8 key). if the program doesn’t encounter an error. This way. To trap these errors. “Manipulating Files and Folders with VBA”). each time supplying one of the following: Name of the C:\Excel2013_ByExample\Vacation. K:\Test) PROCEDURE TESTING You are responsible for the code that you produce. This way. The Err object contains information about runtime errors. At the beginning of the procedure. However. we will need a text file (see Step 2).Number)). Enter any text you want in this file. Visual Basic will not cause another error while trying to read a file that caused the error on opening. If errors 76.txt. or 75 occur. which will send it to the line of code following the one that caused the error. Visual Basic will return its error code (Err.. various errors can occur.in Part V. To test the OpenToRead procedure and better understand error trapping.g.Number will return the error number.txt file Filename that does not exist on drive C Path that does not exist on your computer (e. When the user enters a filename. When done.

Visual Basic returns the error description: Out of memory. especially when they work in an organization that has a team devoted to testing. use the following syntax: ?Error(error_number) For example. Some programmers think that testing their own code is some sort of degrading activity. To check the meaning of the generated error. To generate the same error at runtime in the form of a message box like the one in Figure 11. The testing process at the programmer level is as important as the code development itself. Division by zero. and ask him to play around with it and try to break it.3. you must test it yourself.Raise 7 . type the following in the Immediate window: Error 11 When you press Enter. type the following in the Immediate window: ?Error(7) When you press Enter.give your procedure to others to test. you should give it to users to test. Users will provide you with answers to questions such as: Does the procedure produce the expected results? Is it easy and fun to use? Does it follow the standard conventions? Also. Visual Basic will display an error message saying: Run-time error 11. After all. to display the error that occurs on the attempt to divide by zero. to find out the description of error number 7. Don’t make this mistake. This is how even the most unsuspected errors can quickly be discovered. you wrote the code and know how it is supposed to work. You can generate any built-in error by using the following syntax: Error error_number For example. enter in the Immediate window or in your procedure code: Err. it is usually a good idea to give the entire application not only to power users for their feedback but also to someone who knows the least about using this particular application. After you’ve tested the procedure yourself. You can test the ways that your program responds to runtime errors by causing them on purpose.

SETTING ERROR TRAPPING OPTIONS IN YOUR VISUAL BASIC PROJECT You can specify the error-handling settings for your current Visual Basic project by choosing Tools | Options and selecting the General tab (shown in Figure 11. use the Raise method of the Err object.3. This will generate a runtime error during the execution of your procedure. To test your error-handling code.Figure 11. make sure you remove all statements that raise errors. When you finish debugging your VBA procedures.4). .

Break in Class Module This setting will trap any unhandled error in a class module. The following options are available: Break on All Errors This setting will cause Visual Basic to enter the break mode on any error. The Error Trapping area located on the General tab determines how errors are handled in the Visual Basic environment. Visual Basic will activate a break mode when an error occurs and will highlight the line of code in .4.Figure 11. whether an error handler is active or whether the code is in a class module (class modules were covered in Chapter 9). Setting the error trapping options in the Options dialog box will affect all instances of Visual Basic started after you change the setting.

. The error will cause Visual Basic to activate a break mode. CHAPTER SUMMARY In this chapter. You also learned how to mark your code with bookmarks so you can easily navigate between various sections of your procedure. This chapter concludes Part IV of this book. If the error occurs in a class module. Break on Unhandled Errors This setting will trap errors for which you have not written an error handler. In the next chapter.the class module that produced this error. This chapter also showed you how to trap errors by including errorhandling routines inside your VBA procedures and how to use the VBA Err object. the error will cause Visual Basic to enter break mode on the line of code that called the offending procedure of the class. you will learn how to manipulate files and folders with VBA. you’ve learned how conditional compilation can enable you to run various parts of code based on the specified condition.

you can also perform file and folder manipulation tasks via objects and methods included in the installations of Windows. you can open and manipulate files directly via the low-level file I/O functions. In this part of the book. In addition. and write three types of files. Chapter 12 File and Folder Manipulation with VBA Chapter 13 File and Folder Manipulation with Windows Script Host (WSH) Chapter 14 Using Low-Level File Access .Part 5 Manipulating Files and Folders with VBA While VBA offers a number of built-in functions and statements for working with the file system. and learn how to programmatically open. read. you discover various methods of working with files and folders.

you’ve surely accessed. However. By using these functions. you’ve probably never performed these tasks programmatically. So here’s your chance. created.Chapter 12 File and Folder Manipulation With VBA In the course of your work. copied. and deleted hundreds of files and folders. This chapter focuses on VBA functions and instructions that specifically deal with files and folders. you’ll be able to: Find out the name of the current folder (CurDir function) Change the name of a file or folder (Name function) Check whether a file or folder exists on a disk (Dir function) Find out the date and time a file was last modified (FileDateTime function) Get the size of a file (FileLen function) Check and change file attributes (GetAttr and SetAttr functions) Change the default folder or drive (ChDir and ChDrive statements) Create and delete a folder (MkDir and RmDir statements) Copy and delete a file or folder (FileCopy and Kill statements) MANIPULATING FILES AND FOLDERS . renamed.

you often need to find out the name of the current folder. To see this function in action. Open a new workbook and save it as Practice_Excel12. Type the following statement.1. 2. If you omit drive. Hands-On 12. To return the path as String. Finding Out the Name of the Active Folder When you work with files. let’s perform a couple of exercises in the Immediate window. use CurDir$ (where $ is the type declaration character for a string). The CurDir function returns a file path as Variant. Using the CurDir Function 1. which looks like this: CurDir([drive]) Note that drive is an optional argument. You can get this information easily with the CurDir function. Switch to Microsoft Visual Basic Editor and press Ctrl+G to activate the Immediate window. VBA uses the current drive. as follows: . you can find out the current folder on drive D. For example: C:\ If you have a second disk drive (or a CD-ROM drive). Visual Basic displays the name of the current folder.xlsm in your C:\Excel2013_ByExample folder. Please note files for the “Hands-On” project may be found on the companion CD-ROM. and press Enter: ?CurDir When you press Enter.This section discusses a number of VBA functions used to perform operations on files and folders.

pressing Enter after each line: myDrive = Left(CurDir$. you can move a file from one folder to another (you can’t move a folder). Notice how the CurDir$ function is used as the first argument of the Left function. type the following statement and press Enter: ?myDrive 5. To return the letter of the drive followed by the colon. Using the Name function. Visual Basic will display the following error message: “Device unavailable.” 3. use the Name function.2) ?myDrive Changing the Name of a File or Folder To rename a file or folder. To check the contents of the variable myDrive. as follows: Name old_pathname As new_pathname Old_pathname is the current path and name of a file or folder that you want to rename. Visual Basic stores the letter of the current drive in the variable myDrive. New_pathname specifies the new path and name of the file or folder. type the following statement and press Enter: myDrive = Left(CurDir$.1) When you press Enter. 4. The Left function tells Visual Basic to extract the leftmost character from the string returned by the CurDir$ function and store it in the myDrive variable. type the following instructions.?CurDir("D:\") If you supply a letter for a drive that does not exist. Here are some precautions to consider while working with the Name function: . To store the name of the current disk drive in a variable called myDrive.

Name "C:\system. Renaming an Open File You must close an open file before renaming it.txt file to the specified drive.txt" The above instruction moves the test. Also note that the filename cannot contain the wildcard characters (*) or (?).txt file to the DOS folder on drive C.The filename in new_pathname cannot refer to an existing file. You can use one of the constants or values in Table 12.txt" As "D:\test. Checking the Existence of a File or Folder The Dir function. Visual Basic will display the following error message: “File already exists. the “File not found” error message will appear if the file you want to rename does not exist. Name "D:\test. however. Visual Basic moves the c:\system.txt" As "C:\test. This is easily done with the following statement: Name "C:\system. has the following syntax: Dir[(pathname[. the Name function moves the specified file to a new folder and changes its name. if necessary.txt file to test. If new_pathname and old_pathname refer to different directories and both supplied filenames are the same. Pathname is the name of a file or folder.txt" However. it does not rename the file. the Name function moves the specified file to a new location without changing the filename. attributes])] Notice that both arguments of the Dir function are optional.txt already exists on drive C. If new_pathname already exists. if the file c:\test.txt file doesn’t exist in the root directory on drive D. [[Suppose you’d like to change the name of the system.txt" If the test.” Similarly.1 for .txt" As "C:\DOS\test. which returns the name of a file or folder. Try the above statement in the Immediate window (replace the example names with the actual names of your files). and it’s different from old_pathname.txt.

Hands-On 12. or System file attribute. In the Immediate window.1. Folder. vbNormal) As soon as you press Enter. type the Dir function without an argument and press Enter: ?Dir 2.2). Using the Dir Function 1. Let’s try out the Dir function in several exercises in the Immediate window. Volume Label. the empty string (“”) is returned (see Step 3 in HandsOn 12. If a file or folder does not exist.2.the attributes argument: Table 12. To return the names of other files in the current directory. Visual Basic returns the name of the first file in the specified folder. Enter the following instructions in the Immediate window and examine their results as you press Enter: . Directory. type the following statement and press Enter: ?Dir("C:\". A normal file ( vbNormal) is any file that does not have a Hidden. File attributes The Dir function is often used to check whether a file or folder exists on a disk.

Type the following instruction on one line in the Immediate window and press Enter: If Dir("C:\stamp. as shown below (the lines in italics show what Visual Basic might return as you call the Dir function): ?Dir("C:\WINDOWS\*.myfile = Dir("C:\". Visual Basic prints the message “File was not found” in the Immediate window. For example.Print "File was not found. to find all the configuration settings files in the WINDOWS folder.ini ?dir win. 4. To find out whether a file exists on a disk.bat file doesn’t exist on your drive C.ini ?dir .Print "This file exists on your C drive.ini".bat") = "" Then Debug.bat") < > "" Then Debug. you can look for all the INI files.ini ?dir winfile. vbHidden) ?myfile myfile = Dir ?myfile 3. vbNormal) system." The Dir function allows you to use the wildcards in the specified pathname—an asterisk (*) for multiple characters and a question mark (?) for a single character.ini ?dir control. type the following statement on one line in the Immediate window and press Enter: If Dir ("C:\autoexec." Because the stamp.

equip32. Open the Visual Basic Editor window in the Practice_Excel12. " & _ "C:\Excel2013_ByExample") If Right(mpath. Rename the VBA project FileMan_VBA. which causes the names of files to appear in lowercase. and rename it DirFunction. e.g. 2. Insert a new module into the FileMan_VBA (Practice_Excel12. 4. 3. How about writing the names of files in the specified directory to the Immediate window and a spreadsheet? We’ll make our output consistent by using the LCase$ function.xlsm) project.3. 1) < > "\" Then mpath = mpath & "\" myfile = Dir(mpath & "*. Enter the MyFiles procedure in the Code window as shown below: Sub MyFiles() Dim myfile As String Dim mpath As String mpath = InputBox("Enter pathname. Using the Dir Function in a Procedure 1.ini Now let’s try out a couple of complete procedures that use the Dir function.*") . Hands-On 12.ini ?dir sxpwin32.xlsm workbook.

Next.Print LCase$(myfile) If myfile = "" Then MsgBox "No files found. If the path does not end with the backslash.If myfile < > "" Then Debug. enter the GetFiles procedure in the same module where you entered the MyFiles procedure. To output the filenames to a worksheet.*". Run the MyFiles procedure. If files exist. a message is displayed. Visual Basic looks for all the files (*) in the specified path. and then run it: Sub GetFiles() Dim myfile As String Dim nextRow As Integer nextRow = 1 With Worksheets("Sheet1").Print LCase$(myfile) Loop End Sub The MyFiles procedure shown above asks the user for the pathname. 6. If there are no files.Range("A1") myfile = Dir("C:\Excel2013_ByExample\*." Exit Sub End If Do While myfile < > "" myfile = Dir Debug. 5. the Right function appends the backslash to the end of the pathname string.Print "Files in the " & _ mpath & " folder:" Debug. vbNormal) . the filenames are written to the Immediate window.

Finding Out the Date and Time the File Was Modified If your procedure must check when a file was last modified.xl When you press Enter. If there are no files in the root. Enter the following statement on one line in the Immediate window: ? FileDateTime("C:\Excel2013_ByExample\Practice_Excel11. Visual Basic returns the date and timestamp in the following format: . The function returns the date and timestamp for the specified file. change the drive or folder reference in the Dir function.4. The date and time format depends on the regional settings selected in the Windows Control Panel. Using the FileDateTime Function 1. The pathname may include the drive and folder where the file resides. Let’s practice using this function in the Immediate window. use the FileDateTime function in the following form: FileDateTime(pathname) Pathname is a string that specifies the file you want to work with. 0).Value = myfile Do While myfile < > "" myfile = Dir .Offset(nextRow. Hands-On 12..Value = myfile nextRow = nextRow + 1 Loop End With End Sub The GetFiles procedure obtains the names of files located in the root directory of drive C and writes each filename into a worksheet.

. Enter the following statement on one line in the Immediate window: If DateValue(FileDateTime("C:\Excel2013_ByExample\ Practice_Excel11. use the FileLen function in the following form: FileLen(pathname) The FileLen function returns the size of a specified file in bytes. and rename it FileLenFunction. Suppose you want to find out the total size of all the files that store the configuration settings in the Windows directory.5. Let’s write a procedure that performs this task. Finding Out the Size of a File (the FileLen Function) To check whether a certain file will fit on a diskette. Insert a new module into the project FileMan_VBA (Practice_Excel12. For instance: ? DateValue(FileDateTime("C:\Excel2013_ByExample\Practice_ ? TimeValue(FileDateTime("C:\Excel2013_ByExample\Practice_ 2.xlsm). If the file is open. Hands-On 12.6/14/2013 10:52:00 AM To return the date and time separately. Using the FileLen Function 1.Print "This file was not modified today." The Date function returns the current system date as it is set in the Date and Time Properties dialog box accessed in the Windows Control Panel. use the FileDateTime function as an argument of the DateValue or TimeValue functions.xlsm")) < Date then Debug. Visual Basic returns the size of the file when it was last saved.

2.ini files occupy. The Immediate window displays the total number of bytes that the . File and folder attributes . The only argument of this function is the name of the file or folder you want to work with: GetAttr(pathname) Table 12.2. system. and archive. which returns an integer that represents the sum of one or more of the constants shown in Table 12. Enter the TotalBytesIni procedure in the module’s Code window and run it: Sub TotalBytesIni() Dim iniFile As String Dim allBytes As Long iniFile = Dir("C:\WINDOWS\*. use the GetAttr function. Returning and Setting File Attributes (the GetAttr and SetAttr Functions) Files and folders can have attributes such as read-only.2.ini files located in the Windows folder.Print "Total bytes: " & allBytes End Sub As the procedure loops through the . hidden. the size of each file is stored in the allBytes variable.ini") allBytes = 0 Do While iniFile < > "" allBytes = allBytes + FileLen("C:\WINDOWS\" & iniFile) iniFile = Dir Loop Debug. To find out the attributes of a file or folder.

Manifest") And vbHidden 2 ? getattr("C:\Windows\WindowsShell. Enter the following statements preceded with the question mark in the Immediate window and press Enter.2. Feel free to substitute the filename with an existing file on your computer. Check the return values that you get against Table 12.2. Hands-On 12. If the function returns a nonzero value.Manifest") And vbSystem 0 . use the AND operator to compare the result of the GetAttr function with the value of the constant.Manifest") And vbReadOnly 1 ? getattr("C:\Windows\WindowsShell. Returning File Attributes with the GetAttr Function 1. ? getattr("C:\Windows\WindowsShell. the file or folder specified in the pathname has the attribute for which you are testing.To find out whether a file has any of the attributes shown in Table 12. What are the attributes of a file located on your computer? You can find out quickly in the Immediate window.6.

and rename it GetAttrFunction. strFileName End Sub . _ "Drive\Folder\Filename") If strFileName = "" Then Exit Sub attr = GetAttr(strFileName) msg = "" If attr And vbReadOnly Then msg = msg & "Read-Only (R)" If attr And vbHidden Then msg = msg & Chr(10) & "Hidden (H)" If attr And vbSystem Then msg = msg & Chr(10) & "System (S)" If attr And vbArchive Then msg = msg & Chr(10) & "Archive (A)" MsgBox msg.Manifest") And vbArchive 32 Now let’s put this information together in a procedure. 2.xlsm). Sub GetAttributes() Dim attr As Integer Dim msg As String Dim strFileName As String strFileName = InputBox("Enter the complete file name:". Insert a new module into the project FileMan_VBA (Practice_Excel12. .? getattr("C:\Windows\WindowsShell. Enter the following GetAttributes procedure and run it. 3.

txt". as follows: ChDir pathname In the statement above. If pathname doesn’t include a drive designation. Hands-On 12.2 earlier in this chapter for the list of available constants. The statement: . Its syntax is: SetAttr pathname. Pathname may include the name of the disk drive.txt with the name of a file that exists on your disk): SetAttr "C:\stamps. The current drive will not be changed. is one or more constants that specify the attributes you want to set.txt and you want to set two attributes: read-only and hidden.txt") Changing the Default Folder or Drive (the ChDir and ChDrive Statements) You can easily change the default folder by using the ChDir statement. which allows you to set the attributes for files or folders that are closed. See Table 12. type the following instruction in the Immediate window. and press Enter (replace C:\stamps. The second argument. Suppose the default folder is C:\WINDOWS. To set the file attributes.7.The opposite of the GetAttr function is the SetAttr function. pathname is the name of the new default folder. attributes Pathname is a string that specifies the file or folder that you want to work with. attributes. Setting File Attributes with the SetAttr Function 1.2): ?GetAttr("C:\stamps. the default folder will be changed on the current drive. type the following instruction in the Immediate window and press Enter (check the returned value against Table 12. To find out what attributes were set in Step 1. vbReadOnly + vbHidden 2. Suppose you have a file called C:\stamps.

” Let’s run through some examples in the Immediate window. Visual Basic will create the new folder on the current drive.8. you will get the message “Device unavailable. Visual Basic will display the error message “Path not found.ChDir "D:\MyFiles" changes the default folder to D:\MyFiles. the current drive is still drive C. This function has the following syntax: RmDir pathname Pathname specifies the folder you want to delete. Creating and Deleting Folders with the MkDir and RmDir Statements . however. use the ChDrive statement in the following format: ChDrive drive The drive argument specifies the letter of the new default drive. to change the default drive to drive D or E. Hands-On 12.” Creating and Deleting Folders (the MkDir and RmDir Statements) You can create a new folder using the following syntax of the MkDir statement: MkDir pathname Pathname specifies the new folder you want to create. use the RmDir function. If you don’t include the name of the drive. To delete a folder you no longer need. For instance. Otherwise. use the following statements: ChDrive "D" ChDrive "E" If you refer to a nonexistent drive. If you omit the name of the drive. To change the current drive. Pathname may include the drive name. Visual Basic will delete the folder on the current drive if a folder with the same name exists.

destination. is the name of the destination file and may include the drive and folder designation. enter the following statement and press Enter: ChDir "C:\Mail" 3. specifies the name of the file that you want to copy. Copying Files (the FileCopy Statement) To copy files between folders.9.1. Type the following instruction in the Immediate window and press Enter to create a folder called Mail on drive C: MkDir "C:\Mail" 2. To change the default folder to C:\Mail. You should first delete the files with the Kill statement (discussed later in this chapter). Suppose you want to copy a file specified by a user to a folder called C:\Abort. enter the following statements and press Enter: ChDir "C:\" RmDir "C:\Mail" RmDir Removes Empty Folders You cannot delete a folder if it still contains files. Copying Files with the FileCopy Statement . Both parameters are required. use the FileCopy statement shown below: FileCopy source. destination The first parameter of this statement. The second parameter. source. To find out the name of the active folder. enter the following statement and press Enter: ?CurDir 4. To delete the C:\Mail folder that was created in Step 1. Hands-On 12.9 demonstrates how to do this. Hands-On 12. The name may include the drive in which the file resides.

Insert a new module into the project FileMan_VBA (Practice_Excel12. enter the following CopyToAbortFolder procedure: Sub CopyToAbortFolder() Dim folder As String Dim source As String Dim dest As String Dim msg1 As String Dim msg2 As String Dim p As Integer Dim s As Integer Dim i As Long On Error GoTo ErrorHandler folder = "C:\Abort" msg1 = "The selected file is already in this folder.GetOpenFilename ' don’t do anything if cancelled If source = "False" Then Exit Sub ' get the total number of backslash characters "\" in the ' source variable’s contents Do Until p = 0 .1.xlsm). 2. and rename it FileCopyAndKill. In the module’s Code window." msg2 = "was copied to" p = 1 i = 1 ' get the name of the file from the user source = Application.

1) If p = 0 Then Exit Do s = p i = p + 1 Loop ' create the destination filename dest = folder & Mid(source. "\". dest MsgBox source & " " & msg2 & " " & dest End If Exit Sub ErrorHandler: If Err = "75" Then Resume Next End If If Err = "70" Then MsgBox "You can’t copy an open file. Len(source)) ' create a new folder with this name MkDir folder ' check if the specified file already exists in the ' destination folder If Dir(dest) < > "" Then MsgBox msg1 Else ' copy the selected file to the C:\Abort folder FileCopy source.p = InStr(i. s." Exit Sub End If . source.

4. the selected file will be assigned to the variable source. 3. If such a folder already exists. the first argument of the FileCopy statement. 5. If the user cancels. in any directory. Visual Basic returns the value “False” and the procedure ends. If the file does not exist in the destination folder and the file is not currently open. If the user selects a file and clicks Open. Next. Next. Notice that the error handler is a fragment of code that begins with the label ErrorHandler followed by a colon. it will continue to execute the procedure from the instruction following the instruction that caused the error. so the Do…Until loop finds out the position of the last backslash (\) in the file stored in the variable source. the user will get the message stored in the variable msg1. Run the procedure MyFiles prepared earlier in this chapter to write to the . Using this dialog box. If the file already exists there. Visual Basic will encounter runtime error 70 and run the corresponding instructions in the ErrorHandler section of the procedure. Visual Basic will need to deal with error 75. For the purpose of copying. If the file is open. you can choose any file. When Visual Basic encounters the Resume Next statement. and on any disk drive. Visual Basic will copy the file to the specified folder and notify the user with the appropriate message. you’ll only need the filename (without the path). Run the CopyToAbortFolder procedure several times. Try to copy an open file while using the CopyToAbortFolder procedure. This error will be caught by the error-handler code included at the end of the procedure. 6. the second argument of the FileCopy statement. Try to copy a file that was copied before by this procedure to the C:\Abort folder. the procedure checks whether the selected file already exists in the destination folder. This variable holds the string obtained by concatenating the name of the destination folder (C:\Abort) with the user-specified filename preceded by a backslash (\). This means that the statement MkDir folder won’t be executed. The MkDir function creates a new folder called C:\Abort if it doesn’t exist on drive C. This method causes the built-in Open dialog box to pop up.End Sub The procedure CopyToAbortFolder uses the Excel application method called GetOpenFilename to get the name of the file from the user. Visual Basic prepares a string of characters and assigns it to the variable dest. each time selecting files from different folders.

10. To delete the files from any folder. Deleting Files with the Kill Statement 1. Enter the code of the RemoveMe procedure.xlsm).Immediate window the contents of the folder C:\Abort Do not delete the C:\Abort folder and files that you have copied to it. your hard drive now contains the folder C:\Abort with several files. To enable quick deletion of files. use the following Kill statement: Kill pathname Pathname specifies the names of one or more files that you want to delete. as shown below: Sub RemoveMe() Dim folder As String . Hands-On 12. 2. Let’s write a VBA procedure to dispose of this folder and the files contained in it. Deleting Files (the Kill Statement) You already know from one of the earlier sections in this chapter that you can’t delete a folder if it still contains files. Optionally. you can use the wildcard characters (* or ?) in the pathname argument. You’ll delete both the folder and the files in the next section using a VBA procedure. pathname may include the drive and folder name where the file resides. Insert a new module into the project FileMan_VBA(Practice_Excel12. You can’t delete a file that is open. If you worked through the exercises in the preceding section. and rename it KillStatement.

CHAPTER SUMMARY In the course of this chapter. such as the CurDir function to get the name of the current folder. and RmDir. we will look at Windows Script Host (WSH). You also learned about creating.Dim myFile As String ' assign the name of folder to the folder variable ' notice the ending backslash "\" folder = "C:\Abort\" myFile = Dir(folder. copying. you learned about and tried out VBA functions and statements that allow you to work with the filesystem. . Run the RemoveMe procedure. vbNormal) Do While myFile < > "" Kill folder & myFile myFile = Dir Loop RmDir folder End Sub 3. FileCopy. You wrote code that uses the GetAttr and SetAttr functions to check and change file attributes. In the next chapter. check Windows Explorer to see that the Abort folder was removed. When the procedure ends. an invaluable ActiveX tool that lets you control and retrieve information from the Windows operating system environment. and deleting files and folders by using the statements MkDir. You found out how to manage files and folders by using built-in VBA functions.

.ocx file (see Figure 13.exe). This file is automatically installed in the Windows\System32 folder.1). A script is a set of commands that can be run automatically. WSH is a scripting language. you will learn how the Windows Script Host works together with VBA. Scripts can be created and run directly from the command prompt by using the Command Script Host (Cscript.exe) or from Windows by using the Windows Script Host (Wscript.File Chapter 13 and Folder Manipulation with Windows Script Host (WSH) There is a hidden treasure in your computer called Windows Script Host (WSH) that allows you to create little programs that control the Windows operating system and its applications. as well as retrieve information from the operating system. WSH is an ActiveX control found in the Wshom. In the following sections of this chapter.

Figure 13. Windows Script Host is an ActiveX control used to create scripts that perform simple or complex operations that previously could only be .1.

Hands-On 13. Click the checkbox next to Microsoft Scripting Runtime. then click .2. Using the CreateObject function. as in Figure 13. WSH has its own object hierarchy. locate the file in your Windows directory and right-click it to access the properties window. and computer name Launch other applications Display dialog boxes and retrieve user input Create and manage shortcuts on your Windows desktop Please note files for the “Hands-On” project may be found on the companion CD-ROM. folders. you can refer to WSH objects from your VBA procedure. domain. To check the version of the WSH file on your machine.xlsm. Switch to the Visual Basic Editor window and choose Tools | References. Before you start writing VBA procedures that utilize WSH objects. Controlling Objects with Windows Script Host (WSH) 1. let’s take a look at some of the objects you will be able to control. save it as 2. Open a new workbook and C:\Excel2013_ByExample\Practice_Excel13. access the Windows registry.1. and files using the FileSystemObject Retrieve information about Windows. read and set environment variables. Useful Things You Can Do with WSH Work with and manipulate Windows drives.performed by writing batch files (. retrieve user.bat) in the MS-DOS operating system.

3. Press F2 to open the Object Browser.2. 4.3. Figure 13. choose Scripting. . You will see a list of objects that are part of the Windows Script Host library. In the < All Libraries > combo box. Creating a reference to the Microsoft Scripting Runtime.OK to close the References dialog box. as shown in Figure 13.

Windows Script Host allows you to quickly obtain answers to such questions as “On which disk can I locate a particular file?” (GetDrive method). files. “What is .3. and their contents. After establishing a reference to the Microsoft Scripting Runtime. the Object Browser displays many objects that allow you to work with disks.Figure 13. folders.

GetFile("C:\WINDOWS\System. In the Visual Basic Editor window.Name & vbCrLf . 2.xlsm) to FileMan_WSH. This object has several methods for working with the filesystem. In the WSH module’s Code window. and “Does this folder or file exist on a given drive?” (FolderExists and FileExists methods). Using WSH to Obtain File Information 1.2. Insert a new module into the FileMan_WSH project and rename it WSH. FINDING INFORMATION ABOUT FILES WITH WSH Windows Script Host exposes an object called FileSystemObject. enter the following FileInfo procedure (you may need to change the path to the Windows folder to make it run on your computer): Sub FileInfo() Dim objFs As Object Dim objFile As Object Dim strMsg As String Set objFs = CreateObject("Scripting.FileSystemObject") Set objFile = objFs.the extension of a filename?” (GetExtensionName method). Let’s see how you can obtain some information about a specific file. 3. Close the Object Browser. “When was this file last modified?” (DateLastModified property). 5. activate the Properties window and change the name of VBAProject (Practice_Excel13.ini") strMsg = "File name: " & _ objFile. Hands-On 13.

.DateCreated & vbCrLf strMsg = strMsg & "Date Modified: " & _ objFile. Check the Object Browser for other things you can learn about the file by referencing the File object.ini") creates and returns a reference to the File object for the System. objFile. The statement Set objFile = objFs.DateCreated and objFile.Size. 4. Dim objFs As Object Set objFs = CreateObject("Scripting. it uses the CreateObject function to create an ActiveX object and assigns the object to an object variable.Drive returns the drive name where the file is located. Next. and objFile. The statement objFile. .strMsg = strMsg & "Disk: " & _ objFile.Drive & vbCrLf strMsg = strMsg & "Date Created: " & _ objFile. its attributes.ini file in the C:\WINDOWS folder and assigns it to the objFile object variable. The statements objFile.ParentFolder.GetFile("C:\WINDOWS\System. Run the FileInfo procedure. For example. and the name of the parent folder. objFile. The File object has many properties that you can read. "File Information" End Sub The FileInfo procedure shown above uses the CreateObject VBA function to create an ActiveX object (FileSystemObject) that is a part of the Windows Script Host library.FileSystemObject") The above code declares an object variable named objFs. This object provides access to a computer’s filesystem.DateLastModified return the date the file was created and when it was last modified.Type. the statement objFile.DateLastModified & vbCrLf MsgBox strMsg. This procedure can be modified easily so that it also returns the type of file. Try to modify this procedure on your own by adding the following instructions to the c o d e : objFile.Attributes.Name returns the full name of the file.

This object offers a number of methods.Methods and Properties of FileSystemObject You can access the computer’s filesystem using FileSystemObject.doc" .FileSystemObject") strFile = InputBox("Enter the full name of the file: ") If objFs.FileExists(strFile) Then MsgBox strFile & " was found.doc" strNewFile = "C:\Program Files\Hello." Else MsgBox "File does not exist. some of which are shown below: FileExists—Returns True if the specified file exists Sub FileExists() Dim objFs As Object Dim strFile As String Set objFs = CreateObject("Scripting." End If End Sub GetFile—Returns a File object GetFileName—Returns the filename and path GetFileVersion—Returns the file version CopyFile—Copies a file Sub CopyFile() Dim objFs As Object Dim strFile As String Dim strNewFile As String strFile = "C:\Hello.

" .DeleteFile "C:\Program Files\Hello.DriveExists(disk) Then strMsg = "Drive " & UCase(disk) & " exists. strNewFile MsgBox "A copy of the specified file was created.FileSystemObject") If objFs.doc" MsgBox "The requested file was deleted." Set objFs = Nothing End Sub MoveFile—Moves a file DeleteFile—Deletes a file Sub DeleteFile() ' This procedure requires that you set up ' a reference to Microsoft Scripting Runtime ' Object Library by choosing Tools | References ' in the VBE window Dim objFs As FileSystemObject Set objFs = New FileSystemObject objFs." End Sub DriveExists—Returns True if the specified drive exists Function DriveExists(disk) Dim objFs As Object Dim strMsg As String Set objFs = CreateObject("Scripting.Set objFs = CreateObject("Scripting.CopyFile strFile.FileSystemObject") objFs.

_ "Drive Name".DriveLetter) & vbCrLf infoStr = infoStr & "Drive Type: " & _ objDisk.GetDrive( _ objFs.Else strMsg = UCase(disk) & " was not found.FileSystemObject") Set objDisk = objFs. "C:\") Set objFs = CreateObject("Scripting.GetDriveName(strDiskName)) infoStr = "Drive: " & UCase(strDiskName) & vbCrLf infoStr = infoStr & "Drive letter: " & _ UCase(objDisk." End If DriveExists = strMsg ' run this function from the worksheet ' by entering the following in any cell : =DriveExists("E:\") End Function GetDrive—Returns a Drive object Sub DriveInfo() Dim objFs As Object Dim objDisk As Object Dim infoStr As String Dim strDiskName As String strDiskName = InputBox("Enter the drive letter:".DriveType & vbCrLf infoStr = infoStr & "Drive File System: " & .

FreeSpace / 1024.SerialNumber & vbCrLf infoStr = infoStr & "Total Size in Bytes: " & _ FormatNumber(objDisk.FileSystem & vbCrLf infoStr = infoStr & "Drive SerialNumber: " & _ objDisk.TotalSize / 1024. "Drive Information" End Sub GetDriveName—Returns a string containing the name of a drive or network share Function DriveName(disk) As String Dim objFs As Object Dim strDiskName As String Set objFs = CreateObject("Scripting.FileSystemObject") strDiskName = objFs. vbInformation._ objDisk.GetDriveName(disk) DriveName = strDiskName ' run this function from the Immediate window ' by entering ?DriveName("C:\") End Function FolderExists—Returns True if the specified folder exists . 0) & _ " Kb" & vbCrLf infoStr = infoStr & "Free Space on Drive: " & _ FormatNumber(objDisk. 0) & _ " Kb" & vbCrLf MsgBox infoStr.

Formula = objFile.Name .Type .Offset(1.FolderExists("C:\Program Files") End Sub GetFolder—Returns a Folder object Sub FilesInFolder() Dim objFs As Object Dim objFolder As Object Dim objFile As Object Set objFs = CreateObject("Scripting.Select End With Next Columns("A:B").FileSystemObject") MsgBox objFs.GetFolder("C:\") Workbooks.Range("A1").Add For Each objFile In objFolder.Offset(0.FileSystemObject") Set objFolder = objFs. 0).Range("A1").Files With ActiveCell .AutoFit End Sub GetSpecialFolder—Returns the path to the operating system folders: 0—Windows folder 1—System folder 2—Temp folder .Formula = objFile. 1).Sub DoesFolderExist() Dim objFs As Object Set objFs = CreateObject("Scripting.

Name & " was created.GetSpecialFolder(1) strTempFolder = objFs.CreateFolder("C:\TestFolder") MsgBox "A new folder named " & _ objFolder." End Sub CopyFolder—Creates a copy of a folder Sub MakeFolderCopy() . vbInformation + vbOKOnly.FileSystemObject") Set objFolder = objFs.GetSpecialFolder(2) MsgBox strWindowsFolder & vbCrLf _ & strSystemFolder & vbCrLf _ & strTempFolder. _ "Special Folders" End Sub CreateFolder—Creates a folder Sub MakeNewFolder() Dim objFs As Object Dim objFolder As Object Set objFs = CreateObject("Scripting.GetSpecialFolder(0) strSystemFolder = objFs.Sub SpecialFolders() Dim objFs As Object Dim strWindowsFolder As String Dim strSystemFolder As String Dim strTempFolder As String Set objFs = CreateObject("Scripting.FileSystemObject") strWindowsFolder = objFs.

DeleteFolder "C:\TestFolder" MsgBox "The folder was deleted.CopyFolder "C:\TestFolder".FileSystemObject") If objFs.FolderExists("C:\TestFolder") Then objFs." End If End Sub CreateTextFile—Creates a text file (see the example procedure later in this chapter) OpenTextFile—Opens a text file Sub ReadTextFile() Dim objFs As Object Dim objFile As Object Dim strContent As String Dim strFileName As String . "C:\FinalFolder" MsgBox "The folder was copied." End If End Sub MoveFolder—Moves a folder DeleteFolder—Deletes a folder Sub RemoveFolder() Dim objFs As Object Dim objFolder As Object Set objFs = CreateObject("Scripting.FolderExists("C:\TestFolder") Then objFs.Dim objFs As FileSystemObject Set objFs = New FileSystemObject If objFs.

Close Set objFile = Nothing ActiveWorkbook.FileSystemObject") Set colDrives = objFs. The Drives property returns a reference to the collection of drives.AtEndOfStream strContent = strContent & objFile. Using this property you can create a list of drives on a computer.ReadLine & vbCrLf Loop objFile.Drives For Each Drive In colDrives .Formula = strContent Columns("A:A"). as shown below: Sub DrivesList() Dim objFs As Object Dim colDrives As Object Dim strDrive As String Dim Drive As Variant Set objFs = CreateObject("Scripting.AutoFit End With End Sub The FileSystemObject has only one property.ini" Set objFs = CreateObject("Scripting.FileSystemObject") Set objFile = objFs.Rows.43 .OpenTextFile(strFileName) Do While Not objFile.Select With Selection .strFileName = "C:\Windows\System.Select Range("A1").Sheets(3).ColumnWidth = 62.

These are the properties of the File object: Attributes—Returns file attributes (compare this property to the GetAttr VBA function explained in Chapter 12. “File and Folder Manipulation with VBA”).GetFile("C:\My Documents\myFile. Name—Name of the file.strDrive = "Drive " & Drive. . Drive—Drive name followed by a colon.Print strDrive Next End Sub Properties of the File Object The File object allows you to access all of the properties of a specified file. DateCreated—File creation date. Size—File size in bytes (compare this property to the FileLen VBA function explained in Chapter 12).FileSystemObject") Set objFile = objFs. ParentFolder—Parent folder of the file. Path—Full path of the file.doc") You will find an example of using the File object in the FileInfo procedure that was created earlier in this chapter. The following lines of code create a reference to the File object: Set objFs = CreateObject("Scripting.DriveLetter & ": " Debug. DateLastAccessed—File last-access date. DateLastModified—File last-modified date.

and shortcut.Type—File type.. This is the text that appears in the Type column in Windows Explorer.GetFolder(strFolder) . application. The following lines of code create a reference to the Folder object: Set objFs = CreateObject("Scripting. e. configuration settings.g.FileSystemObject") Set objFolder = objFs. Properties of the Folder Object The Folder object provides access to all of the properties of a specified folder.FileSystemObject") Set objFolder = objFs.GetFolder("C:\My Documents") Examples of VBA procedures that access the Folder object are provided in the following properties list: Attributes—Folder attributes DateCreated—Folder creation date Drive—Returns the drive letter of the folder where the specified folder resides Files—Collection of files in the folder Sub CountFilesInFolder() Dim objFs As Object Dim strFolder As String Dim objFolder As Object Dim objFiles As Object strFolder = InputBox("Enter the folder name:") If Not IsFolderEmpty(strFolder) Then Set objFs = CreateObject("Scripting.

g. IsRootFolder—Returns True if the folder is the root folder Name—Name of the folder ParentFolder—Parent folder of the specified folder Path—Full path to the folder Size—Folder size in bytes Function IsFolderEmpty(myFolder) Dim objFs As Object Dim objFolder As Object Set objFs = CreateObject("Scripting. file folder or Recycle Bin .Files MsgBox "The number of files in the folder " & _ strFolder & " = " & objFiles..Set objFiles = objFolder.Count Else MsgBox "Folder " & strFolder & " has 0 files.Size = 0) End Function SubFolders—Collection of subfolders in the folder Type—Folder type.GetFolder(myFolder) IsFolderEmpty = (objFolder." End If End Sub The above procedure calls the IsFolderEmpty function (used in the Size property description example below).FileSystemObject") Set objFolder = objFs. e.

The following lines of code create a reference to the Drive object: Set objFs = CreateObject("Scripting.Properties of the Drive Object The Drive object provides access to the properties of the specified drive on a computer or a server.FileSystemObject") Set objDrive = objFs.GetDrive("C:\") You will find several procedure examples that use the Drive object in the following list of properties: AvailableSpace—Available space in bytes FreeSpace—Same as AvailableSpace DriveLetter—Drive letter (without the colon) DriveType—Type of drive: 0—Unknown 1—Removable 2—Fixed 3—Network 4—CD-ROM 5—RAM disk Sub CDROM_DriveLetter() Dim objFs As Object Dim colDrives As Object Dim Drive As Object Dim counter As Integer Const CDROM = 4 Set objFs = CreateObject("Scripting.FileSystemObject") .

GetDrive(strDriveLetter) IsCDROMReady = (objDrive.IsReady = True ' run this function from the Immediate window ' by entering: ?IsCDROMReady("D:") End Function Path—Path of the root folder .Set colDrives = objFs.DriveLetter End If Next MsgBox "There are " & counter & " CD-ROM drives.Print "The CD-ROM Drive: " & _ Drive.FileSystemObject") Set objDrive = objFs.DriveType = 4) And _ objDrive.Drives counter = 0 For Each Drive In colDrives If Drive.DriveType = CDROM Then counter = counter + 1 Debug. or CDFS IsReady—Returns True if the appropriate media (CD-ROM) is inserted and ready for access Function IsCDROMReady(strDriveLetter) Dim objFs As Object Dim objDrive As Object Set objFs = CreateObject("Scripting. NTFS." End Sub FileSystem—Filesystem such as FAT.

txt". unicode]]) Object is the name of the FileSystemObject or the Folder object. CreateTextFile object. The value is True if the file is created as a Unicode file and False if it’s created as an ASCII file.WriteLine ("Margaret Kubiak: 212-3388778") objFile.CreateTextFile("C:\Phones. Sub CreateFile_Method1() Dim objFs As Object Dim objFile As Object Set objFs = CreateObject("Scripting. Overwrite (optional) is a Boolean value that indicates whether you can overwrite an existing file. Unicode (optional) is a Boolean value that indicates whether the file is created as a Unicode or ASCII file.FileSystemObject") Set objFile = objFs.SerialNumber—Serial number of the drive TotalSize—Total drive size in bytes CREATING A TEXT FILE USING WSH Windows Script Host (WSH) offers three methods for creating text files: CreateTextFile. OpenTextFile. overwrite[. The value is True if the file can be overwritten and False if it can’t be overwritten. The syntax of each of these methods and example procedures are shown below. and OpenAsTextStream. If omitted.WriteBlankLines (2) . Filename is a string expression that specifies the file to create. If omitted.CreateTextFile(filename[. existing files are not overwritten. an ASCII file is assumed. True) objFile.

Sub CreateFile_Method2() Dim objFs As Object Dim objFile As Object . Iomode (optional) is a Boolean value that indicates whether a new file can be created if the specified filename doesn’t exist. TristateUseDefault—Open the file using the system default. TristateFalse—Open the file as Unicode. If omitted. If omitted. a new file isn’t created. iomode [. create[.Close End Sub The above procedure creates a text file to store the names and phone numbers of two people. The Iomode argument can be one of the following constants: [[ForReading (1) ForWriting (2) ForAppending (8) Create (optional) is a Boolean value that indicates whether a new file can be created if the specified filename doesn’t exist. the C:\Phones. the file is opened as ASCII. Because there is a Boolean value of True in the position of the overwrite argument. If omitted. format]]]) Object is the name of the FileSystemObject. The value is True if a new file is created and False if it isn’t created. TristateTrue—Open the file as ASCII.txt file will be overwritten if it already exists in the specified folder.OpenTextFile(filename[.WriteLine ("Robert Prochot: 202-9882331") objFile.objFile. Filename is a string expression that identifies the file to open. The value is True if a new file is created and False if it isn’t created. a new file isn’t created. Format (optional) is one of three Tristate values used to indicate the format of the opened file. OpenTextFile object.

Object is the name of the File object.OpenAsTextStream([iomode.Close End Sub OpenAsTextStream [format]]) object.WriteLine ("Strawberries") objFile. Sub CreateFile_Method3() Dim objFs As Object . TristateFalse—Open the file as Unicode. TristateTrue—Open the file as ASCII. TristateUseDefault—Open the file using the system default.FileSystemObject") Set objFile = objFs.txt".WriteLine ("Milk") objFile.WriteLine ("Bread") objFile.Const ForWriting = 2 Set objFs = CreateObject("Scripting.OpenTextFile("C:\Shopping. Iomode (optional) indicates input/output mode. _ ForWriting. If omitted. the file is opened as ASCII. This can be one of three constants: ForReading (1) ForWriting (2) ForAppending (8) Format (optional) is one of three Tristate values used to indicate the format of the opened file. True) objFile.

WSH allows you to perform such tasks as handling WSH and ActiveX objects.txt" Set objFile = objFs.txt") Set objText = objFile.OpenAsTextStream(ForReading. creating Windows and Internet shortcuts.Write "Wedding Invitation" objText.Dim objFile As Object Dim objText As Object Const ForWriting = 2 Const ForReading = 1 Set objFs = CreateObject("Scripting. manipulating the registry.FileSystemObject") objFs. In addition to accessing the filesystem through FileSystemObject. _ TristateUseDefault) objText. _ TristateUseDefault) MsgBox objText. mapping and unmapping printers and remote drives.OpenAsTextStream(ForWriting. and accessing the Windows NT Active Directory service.Close Set objText = objFile.CreateTextFile "New.ReadLine objText.Close End Sub PERFORMING OTHER OPERATIONS WITH WSH WSH makes it possible to manipulate any Automation object installed on your computer. The WSH object model is made of the following three main objects: WScript .GetFile("New.

Suppose you want to start up Windows Notepad from your VBA procedure. If you’d rather launch the built-in calculator. The procedure that follows shows you how easy it is to run an application using the WshShell object that is a part of Windows Script Host.xlsm) and rename it WSH_Additional. Enter the RunNotepad procedure in the WSH_Additional module’s Code window.Run "Notepad" Set WshShell = Nothing End Sub The above procedure begins by declaring and creating a WshShell object: Dim WshShell As Object . as shown below: Sub RunNotepad() Dim WshShell As Object Set WshShell = CreateObject("WScript. Running Other Applications In Chapter 15.3. “Using Excel VBA to Interact with Other Applications. You can add to those methods what you are about to find out in this section. 2. Hands-On 13.” you will learn various methods of launching external applications from Excel.Shell") WshShell.WshShell WshNetworkThe following sections demonstrate how you can take advantage of the WshShell object to write procedures to start other applications and create shortcuts. Running Other Applications Using the WSH Object 1. just replace the name of the Notepad application with Calc. Insert a new module into the project FileMan_WSH (Practice_Excel13.

to open “C:\My Files\my text file. or the Run method will raise a runtime error.Run "Calc" WshShell. as shown in the following procedure: Sub OpenTxtFileInNotepad() Dim WshShell As Object Set WshShell = CreateObject("WScript.txt""" or use the ANSI equivalent for double quote marks as shown below: WshShell. For example.txt” file in Notepad.Shell") WshShell. you can start your application with a specific document.Run "Notepad " & """C:\My Files\my text file. Visual Basic will prompt you whether you want to create the file.Run "Notepad " & Chr(34) & _ .Set WshShell = CreateObject("WScript.Shell") The next statement uses the Run method to run the required application: WshShell.Run "Explorer" The last line in the procedure destroys the WshShell object because it is no longer needed: Set WshShell = Nothing 3.Run "Notepad" Using the same concept. the pathname must be enclosed in double quotes. it is easy to run Windows utility applications such as Calculator or Explorer: WshShell.txt" Set WshShell = Nothing End Sub If the specified file cannot be found. If the path contains spaces. Instead of launching an empty application window. use the following statement: WshShell.Run "Notepad C:\Phones. Execute the RunNotepad procedure.

txt" & Chr(34) The above statement uses the VBScript function Chr to convert an ANSI value to its character equivalent. You can use the Environment property of the WshShell object to access these variables.Run "Control. 34 is the ANSI value for double quotes. The following statement will open the System property page with the Hardware tab selected: WshShell. and wait until the process terminates: WshShell.exe Sysdm.exe" The Control Panel has various property sheets.cpl.Run "Notepad". If the second parameter is set to True.com") The following statement invokes a Control Panel: WshShell. you will not be able to work with Excel until you close Notepad. vbMinimizedFocus Because the second optional parameter is not specified. For example.Run ("http://msn.2" The parameters after the name of the Control Panel property page (identified by the .exe) and immediately terminates the process.cpl extension) specify which page is selected. replace 2 with 0 (zero). vbMinimizedFocus. . as in the following: WshShell. Obtaining Information about Windows Windows stores various kinds of information in environment variables. the ."C:\My Files\my text file. To open a particular Web page. you can launch Notepad in the minimized view as shown below: WshShell. True If you run the above statement with the second parameter set to True. the Run method will create a new process. Note that the Run method has two optional arguments that allow you to specify the window style and whether the system should wait until the executed process completes. execute the command. To select the General tab on this property page. the Run method executes the command (Notepad. pass the Web page address to the Run method.Run "Notepad".Run "Control. Depending on which version of operating system you are using.

Print "Path=" & objEnv("PATH") Debug. The following procedure demonstrates how to retrieve the values of several environment variables from the Process category: Sub ReadEnvVar() Dim WshShell As Object Dim objEnv As Object Set WshShell = CreateObject("WScript.Print "System Drive=" & objEnv("SYSTEMDRIVE") Debug.Print "Windows folder=" & objEnv("Windir") Debug. or the computer name. Volatile.Print "System Root=" & objEnv("SYSTEMROOT") Debug. domain name. or Computer You can use the properties of the WshNetwork object of WSH to retrieve the user name.Environment("Process") Debug. and Process categories. as shown in the procedure below: Sub GetUserDomainComputer() Dim WshNetwork As Object Dim myData As String .environment variables are grouped into System.Shell") Set objEnv = WshShell. You can use the name of the category as the index of the Environment property. User.Print "Operating System=" & objEnv("OS") Set WshShell = Nothing End Sub Retrieving Information about the User. Domain.

and you can use its Shell object to create shortcuts to applications or Websites without any user intervention.Network") myData = myData & "Computer Name: " _ & WshNetwork. which must be included in the pathname. VBA does not provide a way to create Windows shortcuts. users will certainly request that you automatically place a shortcut to your application on their desktop. The CreateShortcut method returns a shortcut object that exposes a number of properties and one method: TargetPath—The TargetPath property is the path to the shortcut’s executable.UserDomain & vbCrLf myData = myData & "User Name: " _ & WshNetwork. All shortcut files have the . you now know how to work with WSH.UserName & vbCrLf MsgBox myData End Sub Creating Shortcuts When you start distributing your VBA applications. The WshShell object exposes the CreateShortcut method. WshShell.FullName WindowStyle—The WindowStyle property identifies the window style used . which you can use in the following way: Set myShortcut = WshShell.CreateShortcut(pathname) Pathname is a string indicating the full path to the shortcut file.lnk extension.TargetPath = ActiveWorkbook.Set WshNetwork = CreateObject("WScript.ComputerName & vbCrLf myData = myData & "Domain: " _ & WshNetwork. Luckily for you.

exe. WshShell.IconLocation = "notepad. 0" Description—The Description property contains a string value describing a shortcut. strWorkDir = WshShell. WshShell. Ctrl-Shift+Z.WindowStyle = 1 Hotkey—The Hotkey property is a keyboard shortcut. If not specified. After using the CreateShortcut method to create a Shortcut object and set the Shortcut object’s properties. 5. Initialize its properties (shown above). . etc. 1—Normal window 3—Maximized window 7—Minimized window WshShell.WorkingDirectory = strWorkDir Save—Save is the only method of the Shortcut object. For example.Hotkey = "Ctrl+Alt+W" IconLocation—The IconLocation property is the location of the shortcut’s icon. Save it to disk with the Save method. you should provide the path to the icon file followed by the index number of the desired icon in this file. Windows uses the default icon for the file. WshShell. Create an instance of a WshShortcut object. Shift+G. Because icon files usually contain more than one icon. 6.by a shortcut.Description = "Mercury Learning Web Site" WorkingDirectory—The WorkingDirectory property identifies the working directory used by a shortcut. Creating a shortcut is a three-step process: 4. Alt+F.SpecialFolders("Desktop") WshShell. the CreateShortcut method must be used to save the Shortcut object to disk.

url") With objShortcut .TargetPath = strWebAddr .merclearning.CreateShortcut(WshShell.com" Set WshShell = CreateObject("WScript. Both shortcuts are placed on the user’s desktop. In the WSH_Additional module created in the previous Hands-On exercise.4.The following example creates a WshShell object and uses the CreateShortcut method to create two shortcuts: a Windows shortcut to the active Microsoft Excel workbook file and an Internet shortcut to the Mercury Learning Website.Save End With ' create a file shortcut . Hands-On 13.Shell") ' create an Internet shortcut Set objShortcut = WshShell. enter the CreateShortcut procedure as shown below: Sub CreateShortcut() ' this script creates two desktop shortcuts Dim WshShell As Object Dim objShortcut As Object Dim strWebAddr As String strWebAddr = "http://www. Creating Shortcuts Using the WshShell Object 1. _ SpecialFolders("Desktop") & "\Mercury Learning.

CreateShortcut( _ WshShell. Close the active workbook file and test the shortcut to this file that you should now have on your desktop.Description = "Discover Mercury Learning" .SpecialFolders("Desktop") & _ "\" & ActiveWorkbook.lnk") With objShortcut . Using the SpecialFolders Property You can find out the location of a special folder on your machine using the SpecialFolders property. 4.FullName .' you cannot create a shortcut to unsaved workbook file Set objShortcut = WshShell. AllUsersStartup.Name & ". The following special folders are available: AllUsersDesktop.WindowStyle = 7 . AllUsersStartMenu. AllUsersPrograms. Switch to your desktop and click the Mercury Learning shortcut.TargetPath = ActiveWorkbook.Save End With Set objShortcut = Nothing Set WshShell = Nothing End Sub The above procedure uses the SpecialFolders property of the WshShell object to return the path to the Windows desktop. 3. Run the CreateShortcut procedure. 2. .

Listing Shortcut Files The following procedure prints to the Immediate window the list of all shortcut files found on the desktop.GetFolder(s) strLinks = strLinks & objFolder.SpecialFolders Set objFolder = objFs.Name = "Desktop" Then For Each f In objFolder. from the end of string. Programs. MyDocuments. This function has the same syntax as the InStr function. Notice that the procedure uses the InStrRev function to check whether the file is a shortcut.Desktop.Shell") Set objFs = CreateObject("Scripting.FileSystemObject") strLinks = "" For Each s In wshShell. Fonts. the SpecialFolders property returns an empty string. If the requested special folder is not available. and others as listed in the sidebar) or enumerate all folders by removing the conditional statement. Favorites. Sub ListShortcuts() Dim objFs As Object Dim objFolder As Object Dim wshShell As Object Dim strLinks As String Dim s As Variant Dim f As Variant Set wshShell = CreateObject("WScript. StartMenu. You can easily modify this procedure to list other special folders (StartMenu.Name _ & " Shortcuts:" & vbCrLf If objFolder. and Templates. NetHood. except that it returns the position of an occurrence of one string within another. Startup. Recent. Recent.Files . PrintHood. SendTo.

". and binary.Name & vbCrLf End If Next End If Exit For Next Debug. such as launching applications and creating Windows shortcuts with the WshShell object. . you will learn how to work with three types of files: sequential. random access. you learned how to use the Windows Script Host (WSH) to access the FileSystemObject and perform other operations.If InStrRev(UCase(f).LNK") Then strLinks = strLinks & f.Print strLinks End Sub CHAPTER SUMMARY In the course of this chapter. In the next chapter.

Chapter

14

Using LowLevel File
Access

In addition to opening files within a particular application, your VBA procedures
are capable of opening other types of files and working with their contents. This
chapter will put you in direct contact with your data by introducing you to the process
known as low-level file I/O (input/output).

FILE ACCESS TYPES
There are three types of files used by a computer:
Sequential access files are files where data is retrieved in the same order as it is
stored, such as files stored in the CSV format (comma-delimited text), TXT
format (text separated by tabs), or PRN format (text separated by spaces).
Sequential access files are often used for writing text files such as error logs,
configuration settings, and reports. Sequential access files have the following
modes: Input, Output, and Append. The mode specifies how you can work with a
file after it has been opened.
Random-access files are text files where data is stored in records of equal length
and fields separated by commas. Random-access files have only one mode:
Random.
Binary access files are graphic files and other nontext files. Binary files can only
be accessed in a Binary mode.

WORKING WITH SEQUENTIAL FILES
The hard drive of your computer contains hundreds of sequential files.

Configuration files, error logs, HTML files, and all sorts of plain text files are all
sequential files. These files are stored on disk as a sequence of characters.
The beginning of a new text line is indicated by two special characters: the
carriage return and the linefeed. When you work with sequential files, start at the
beginning of the file and move forward character by character, line by line, until you
encounter the end of the file. Sequential access files can be easily opened and
manipulated by just about any text editor.
Reading Data Stored in Sequential Files
Let’s take one of the sequential files already present on your computer and read its
contents with VBA straight from the Microsoft Excel Visual Basic Editor window.
You can read any other text file you want. To read data from a file, open the file with
the Open statement. Here’s the general syntax of this statement, followed by an
explanation of each component:
Open pathname For mode[Access access][lock] As
[#]filenumber
[Len=reclength]
T he Open statement has three required arguments: pathname, mode, and
filenumberPathname is the name of the file you want to open. The filename may
include the name of a drive and folder.
Mode is a keyword that determines how the file was opened. Sequential files can
be opened in one of the following modes: Input, Output, or Append. Use Input to
read the file, Output to write to a file overwriting any existing file, and Append to
write to a file by adding to any existing information.
The optional Access clause can be used to specify permissions for the file
(Read, Write, or Read Write).
The optional Lock argument determines which file operations are allowed for
other processes. For example, if a file is open in a network environment, lock
determines how other people can access it. The following lock keywords can
be used: Shared, Lock Read, Lock Write, or Lock Read Write.
Filenumber is a number from 1 to 511. This number is used to refer to the file
in subsequent operations. You can obtain a unique file number using the Visual
Basic built-in FreeFile function.

The last element of the Open statement, reclength, specifies the buffer size
(total number of characters) for sequential files, or the record size for randomaccess files.
Taking the preceding into consideration, to open Vacation.txt or any other
sequential file in order to read its data, use the following instruction:
Open "C:\Excel2013_ByExample\Vacation.txt" For
Input As #1
If a file is opened for input, it can only be read from. After you open a sequential
file, you can read its contents with the Line Input # or Input # statements or
by using the Input function. When you use sequential access to open a file for input,
the file must already exist.
What Is a Sequential File?
A sequential file is one in which the records must be accessed in the order
they occur in the file. This means that before you can access the third record, you
must first access record number 1 and then record number 2.
Reading a File Line by Line
To read the contents of a sequential file line by line, use the following Line
Input # statement:
Line Input #filenumber, variableName
#filenumber is the file number that was used in the process of opening the
file with the Open statement. VariableName is a String or Variant variable that
will store the line being read. The statement Line Input # reads a single line in
an open sequential file and stores it in a variable. Bear in mind that the Line Input
# statement reads the sequential file one character at a time, until it encounters a
carriage return (Chr(13)) or a carriage return-linefeed sequence (Chr(13) & Chr(10)).
These characters are omitted from the text retrieved in the reading process.
The ReadMe procedure that follows demonstrates how you can use the Open and
Line Input # statements to read the contents of the Win.ini file line by line.
Apply the same method for reading other sequential files.

Please note files for the “Hands-On” project may be found on the companion CD-

ROM.

Hands-On 14.1. Reading File Contents with the Open and Line Input #
Statements

1. Open a new workbook and save it as C:\Excel2013_ByExample\Practice_
Excel14.xlsm.
2. Switch to the Visual Basic Editor and use the Properties window to rename
VBAProject (Practice_Excel14.xlsm) FileMan_IO.
3. Insert a new module in the FileMan_IO project and rename it SeqFiles.
4. In the SeqFiles module’s Code window, enter the ReadMe procedure shown
below:
Sub ReadMe(strFileName As String)
Dim rLine As String
Dim i As Integer
' line number
i = 0
On Error GoTo ExitHere
Open strFileName For Input As #1
' stay inside the loop until the end of file
is reached
Do While Not EOF(1)
i = i + 1
Line Input #1, rLine
MsgBox "Line " & i & " in " & strFileName
& " reads: " _
& Chr(13) & Chr(13) & rLine

Loop
MsgBox i & " lines were read."
Close #1
Exit Sub
ExitHere:
MsgBox "File " & strFileName & " could not be
found."
End Sub
The ReadMe procedure opens the specified text file in the Input mode as file
number 1 in order to read its contents. If the specified file cannot be opened
(because it may not exist), Visual Basic jumps to the label ExitHere and displays
a message box.
If the file is successfully opened, we can proceed to read its content. The Do…
While loop tells Visual Basic to execute the statements inside the loop until the
end of the file has been reached. The end of the file is determined by the result of
the EOF function. The EOF function returns a logical value of True if the next
character to be read is past the end of the file. Notice that the EOF function
requires one argument—the number of the open file you want to check. This is the
same number used in the Open statement. Use the EOF function to ensure that
Visual Basic doesn’t read past the end of the file.
T he Line Input # statement stores each line’s contents in the variable
rLine. Next, a message is displayed that shows the line number and its contents.
Visual Basic exits the Do…While loop when the result of the EOF function is
true. Before VBA ends the procedure, two more statements are executed. A
message is displayed with the total number of lines that have been read, and the
file is closed.
5. To run the procedure, open the Immediate window, type the following statement,
and press Enter to execute:
ReadMe "C:\Excel2013_HandsOn\TestTextFile.txt"
Reading Characters from Sequential Files
Suppose that your procedure needs to check how many commas appear in the
Win.ini file. Instead of reading entire lines, you can use the Input function to return
the specified number of characters. Next, the If statement can be used to compare the

obtained character against the one you are looking for. Before you write a procedure
that does this, let’s review the syntax of the Input function:
Input(number, [#]filenumber)
Both arguments of the Input function are required; number specifies the
number of characters you want to read, and filenumber is the same number that the
Open statement used to open the file. The Input function returns all the characters
being read, including commas, carriage returns, end-of-file markers, quotes, and
leading spaces.

Hands-On 14.2. Reading Characters from Sequential Files

1. Enter the CountChar procedure below in the SeqFiles module.
Sub CountChar(strFileName As String, srchChar
As String)
Dim counter As Integer
Dim char As String
counter = 0
Open strFileName For Input As #1
Do While Not EOF(1)
char = Input(1, #1)
If char = srchChar Then
counter = counter + 1
End If
Loop
If counter < > 0 Then
MsgBox "Characters (" & srchChar & _

") found: " & counter
Else
MsgBox "The specified character (" & _
srchChar & ") has not been found."
End If
Close #1
End Sub
2. To run the procedure, open the Immediate window, type the following statement,
and press Enter to execute:
CountChar
"C:\Excel2013_HandsOn\TestTextFile.txt", "."
3. Run the procedure again after replacing the period character with any other
character you’d like to find.
The Input function allows you to return any character from the sequential file.
If you use the Visual Basic function LOF (length of file) as the first argument of
the Input function, you’ll be able to quickly read the contents of the sequential
file without having to loop through the entire file. The LOF function returns the
number of bytes in a file. Each byte corresponds to one character in a text file.
The following ReadAll procedure shows how to read the contents of a sequential
file to the Immediate window:
Sub ReadAll(strFileName As String)
Dim all As String
Open strFileName For Input As #1
all = Input(LOF(1), #1)
Debug.Print all
Close #1
End Sub
4. To execute the above procedure, open the Immediate window, type the following
statement, and press Enter:
ReadAll "C:\Excel2013_HandsOn\TestTextFile.txt"

Instead of printing the file contents to the Immediate window, you can read it
into a text box placed in a worksheet, similar to the one in Figure 14.1. Let’s take
a few minutes to write this procedure.

Hands-On 14.3. Printing File Contents to a Worksheet Text Box

1. Enter the WriteToTextBox procedure below in the SeqFiles module.
Sub WriteToTextBox(strFileName As String)
Dim sh As Worksheet
Set sh = ActiveWorkbook.Worksheets(3)
On Error GoTo CloseFile:
Open strFileName For Input As #1
sh.Shapes.AddTextbox(msoTextOrientationHorizontal,
_
10, 10, 300, 200).Select
Selection.Characters.Text = Input(LOF(1), #1)
CloseFile:
Close #1
End Sub
Notice that the statement On Error GoTo CloseFile activates error
trapping. If an error occurs during the execution of a line of the procedure, the
program will jump to the error-handling routine that follows the CloseFile label.
The statement Close #1 will be executed, whether or not the program
encounters an error. Before the file contents are placed in a worksheet, a text box
is added using the AddTextbox method of the Shapes object.
2. To execute the above procedure, open the Immediate window, type the following
statement, and press Enter:
WriteToTextBox

"C:\Excel2013_HandsOn\TestTextFile.txt"
The result should be similar to Figure 14.1.

Figure 14.1. The contents of a text file are displayed in a text box
placed in an Excel worksheet.

Reading Delimited Text Files
In some text files (usually files saved in CSV, TXT, or PRN format), data entered
on each line of text is separated (or delimited) with a comma, tab, or space character.
These types of files can be read faster with the Input # statement instead of the
Line Input # statement introduced earlier in this chapter. The Input #
statement allows you to read data from an open file into several variables. This
function looks like the following:
Input #filenumber, variablelist
Filenumber is the same file number that was used in the Open statement.
Variablelist is a comma-separated list of variables that you will want to use to
store the data being read. You can’t use arrays or object variables. You can, however,

use a user-defined variable explained later in this chapter). An example of a
sequential file with comma-delimited values is shown below:
Smith,John,15
Malloney,Joanne,28
Ikatama,Robert,15
Note that in this example there are no spaces before or after the commas. To read
text formatted in this way, you must specify one variable for each item of data: last
name, first name, and age. Let’s try it out.

Hands-On 14.4. Reading a Comma-delimited (CSV) File with the Input #
Statement

1. Open a new workbook and enter the data shown in the worksheet in Figure 14.2:

Figure 14.2. You can create a comma-delimited file from an Excel
workbook.

2. Click the File tab on the Ribbon, then click Save As. Switch to the
C:\Excel2013_ByExample folder. In the Save as type drop-down box, select
CSV (Comma delimited) (*.csv). Change the filename to Winners.csv and click
Save.
3. Excel will display a message that some features will be lost if you save the file
as CSV. Click Yes to use that format.

The CSV file type does not support workbooks that contain multiple
sheets. If you added more sheets to the workbook and try to save the
workbook in as a comma delimited file (CSV), Excel will display a
warning message.

4. Close the Winners.csv file.
5. Activate the Practice_Excel14.xlsm workbook and switch to the Visual Basic
Editor.
6. In the Project Explorer window, double-click the SeqFiles module in the
FileMan_IO project and enter the Winners procedure as shown below:
Sub Winners()
Dim lname As String
Dim fname As String
Dim age As Integer
Open "C:\Excel2013_ByExample\Winners.csv" For
Input As #1
Do While Not EOF(1)
Input #1, lname, fname, age
MsgBox lname & ", " & fname & ", " & age
Loop
Close #1
End Sub
The above procedure opens the Winners.csv file for input and sets up a Do…
While loop that runs through the entire file until the end of file is reached. The
Input #1 statement is used to write the contents of each line of text into three
variables: lname, fname, and age. Then a message box displays the contents
of these variables. The procedure ends by closing the Winners.csv file.
7. Run the Winners procedure.

Writing Data to Sequential Files
When you want to write data to a sequential file, you should open the file in
Append or Output mode. The differences between these modes are explained below:
Append mode—This mode allows adding data to the end of an existing text file.
For example, if you open the Readme.txt file in Append mode and add to this file
the text “Thank you for reading this document,” Visual Basic won’t delete or alter
the text that is currently in the file but will add the new text to the end of the file.
Output mode—When you open a file in Output mode, Visual Basic will delete the
data that is currently in the file. If the file does not exist, a brand-new file will be
created. For example, if you open the Readme.txt file in Output mode and attempt
to write some text to it, the previous text that was stored in this file will be
removed. If you don’t back up the file prior to writing the data, this mistake may
be quite costly. You should open an existing file in Output mode only if you
want to replace its entire contents with new data.
Here are some examples of when to open a file in Append mode or Output mode:
To create a brand-new text file called C:\Excel2013_ByExample\Readme.txt,
open the file in Output mode as follows:
Open "C:\Excel2013_ByExample\Readme.txt" For
Output As #1
To add new text to the end of C:\Excel2013_ByExample\Readme.txt, open the
file in Append mode as follows:
Open "C:\Excel2013_ByExample\Readme.txt" For
Append As #1
To replace the contents of an existing file C:\Excel2013_ByExample\
Winners.csv with a list of new winners, first prepare a backup copy of the
original file, then open the original file in Output mode:
FileCopy "C:\Excel2013_ByExample\Winners.csv",
"C:\Excel2013_ByExample\Winners.old"
Open "C:\Excel2013_ByExample\Winners.csv" For
Output As #1

Can’t Read and Write at the Same Time
You cannot perform read and write operations simultaneously on an open
sequential file. The file must be opened separately for each operation. For
instance, after data has been written to a file that has been opened for output, the
file must be closed before being opened for input.
Advantages and Disadvantages of Sequential Files
Although sequential files are easy to create and use, and don’t waste any space,
they have a number of disadvantages. For example, you can’t easily find one specific
item in the file without having to read through a large portion of the file. Also, you
must rewrite the entire file to change or delete an individual item in the file. And as
stated above, sequential files have to be opened for reading and again for writing.
Using Write # and Print # Statements

Now that you know both methods (Append and Output) for opening a text file with
the intention of writing to it, it’s time to learn the Write # and Print # statements
that will allow you to send data to the file.
When you read data from a sequential file with the Input # statement, you
usually write data to this file with the Write # statement. This statement looks like this:
Write #filenumber, [outputlist]
Filenumber specifies the number of the file you’re working with. It is the only
required argument of the Write # statement. outputlist is the text you want to
write to the file and can be a single text string or a list of variables that contain data
that you want to write. If you specify only the filenumber argument, Visual Basic
will write a single empty line to the open file.
To illustrate how data is written to a file, let’s prepare a text file with the first
name, last name, birthdate, and the number of siblings for three people.

Hands-On 14.5. Using the Write # Statement to Write Data to a File

1. In the SeqFiles module, enter the DataEntry procedure as shown below:
Sub DataEntry()
Dim lname As String
Dim fname As String
Dim birthdate As Date
Dim sib As Integer
Open "C:\Excel2013_ByExample\Friends.txt" For
Output As #1
lname = "Smith"
fname = "Gregory"
birthdate = #1/2/1963#
sib = 3
Write #1, lname, fname, birthdate, sib
lname = "Conlin"
fname = "Janice"
birthdate = #5/12/1948#
sib = 1
Write #1, lname, fname, birthdate, sib
lname = "Kaufman"
fname = "Steven"
birthdate = #4/7/1957#
sib = 0
Write #1, lname, fname, birthdate, sib
Close #1
End Sub
The
above
procedure
creates
a
brand-new
file
named
C:\Excel2013_ByExample\Friends.txt file, opens it for output, then writes three
records to it. The data written to the file is stored in variables. Notice that the
strings are delimited with double quotes (“”) and the birthdate is surrounded by
pound signs (#).

2. Run the DataEntry procedure.
3. Locate the Friends.txt file created by the DataEntry procedure and open it using
Windows Notepad.
The Friends.txt file opened in Notepad looks as follows:
"Smith","Gregory",#1963-01-02#,3
"Conlin","Janice",#1948-05-12#,1
"Kaufman","Steven",#1957-04-07#,0
T he Write # statement in the DataEntry procedure automatically inserted
commas between the individual data items in each record and placed the carriage
return-linefeed sequence (Chr(13) & Chr(10)) at the end of each line of text so
that each new record starts in a new line. Each line of text shows one record—
each record begins with the last name and ends with the number of siblings.
To show the data separated by columns, instead of commas, write the data with
the Print # statement. For example, if you replace the Write # statement in
the DataEntry procedure with the Print # statement, Visual Basic will write
the data as follows:
Smith Gregory 1/2/63 3
Conlin Janice 5/12/48 1
Kaufman Steven 4/7/57 0
Although the Print # statement has the same syntax as the Write #
statement, Print # writes data to the sequential file in a format ready for printing.
The variables in the list may be separated with semicolons or spaces. To print out
several spaces, you should use the Spc(n) instruction, where n is the number of
spaces. Similarly, to enter a word in the fifth column, you should use the instruction
Tab(5). Let’s look at some formatting examples:
To add an empty line to a file, use the Write # statement with a comma:
Write #,
To enter the text “fruits” in the fifth column: Write
"fruits"

#1,

Tab(5);

To separate the words “fruits” and “vegetables” with five spaces: Write #1,
"fruits"; Spc(5); "vegetables"

WORKING WITH RANDOM-ACCESS FILES
When a file contains structured data, open the file in random-access mode. A file
opened for random access allows you to:
Read and write data at the same time
Quickly access a particular RecordIn random-access files, all records are of
equal length, and each record has the same number of fixed-size fields. The
length of a record or field must be determined prior to writing data to the file. If
the length of a string that is being written to a field is less than the specified size
of the field, Visual Basic automatically enters spaces at the end of the string to
fill in the entire size of the field. If the text being written is longer than the size of
the field, the text that does not fit will be truncated.
What Is a Random-Access File?
A random-access file is one in which data is stored in records that can be
accessed without having to read every record preceding it.
To find out how to work with random-access files, let’s create a small
database for use in a foreign language study. This database will contain records
made up of two fields: an English term and its foreign language equivalent.

Hands-On 14.6. Creating a Random-Access Database with a User-defined Data
Type

1. Insert a new module into the FileMan_IO project in Practice_Excel14.xls, and
rename it RandomFiles.
2. Enter the following statements just below the Option Explicit statement at
the top of the RandomFiles module:
' create a user-defined data type called
Dictionary

Type Dictionary
en As String * 16 ' English word up to
16 characters
sp As String * 20 ' Spanish word up to
20 characters
End Type
In addition to the built-in data types introduced in Chapter 4 and listed in Table
4.1, Visual Basic allows you to define a nonstandard data type using a Type…
End Type statement placed at the top of the module. This nonstandard data type
is often referred to as a user-defined data type. The user-defined data type can
contain items of various data types (String, Integer, Date, and so on). When you
work with files opened for random access, you often create a user-defined
variable because such a variable provides you with easy access to the individual
fields of a record.
The user-defined type called Dictionary that you just defined contains two
items declared as String with the specified size. The en item can accept up to 16
characters. The size of the second item (sp) cannot exceed 20 characters. By
adding up the lengths of both of these items, you will get a record length of 36
characters (16 + 20).
Understanding the Type Statement
The Type command allows you to create a custom group of mixed variable
types called a “user-defined data type.” This statement is generally used with
random-access files to store data as fields within records of a fixed size. Instead
of declaring a separate variable for each field, cluster the fields into a userdefined variable using the Type statement. For example, define a record
containing three fields in the following way:
Type MyRecord
country As String * 20
city As String * 14
rank As Integer
End Type
Once the general type is defined, you must give a name to the particular
variable that will be of that type:

Dim myInfo As MyRecord
Access the interior variables (country, city, rank) by using the
following format:
Variable_name.Interior_variable_name
For example, to specify the city, enter:
MyInfo.city = "Warsaw"
3. Enter the EnglishToSpanish procedure as shown below:
Sub EnglishToSpanish()
Dim d As Dictionary
Dim recNr As Long
Dim choice As String
Dim totalRec As Long
recNr = 1
' open the file for random access
Open "C:\Excel2013_ByExample\Translate.txt" _
For Random As #1 Len = Len(d)
Do
' get the English word
choice = InputBox("Enter an English word",
"ENGLISH")
d.en = choice
' exit the loop if cancelled
If choice = "" Then Exit Do
choice = InputBox("Enter the Spanish
equivalent of " _
& d.en, "SPANISH EQUIVALENT
If choice = "" Then Exit Do
d.sp = choice
' write to the record

" & d.en)

Put #1, recNr, d
' increase record counter
recNr = recNr + 1
'ask for words until Cancel
Loop Until choice = ""
totalRec = LOF(1) / Len(d)
MsgBox "This file contains " & totalRec & "
record(s)."
' close the file
Close #1
End Sub
The EnglishToSpanish procedure begins with the declaration of four
variables. The variable d is declared as a user-defined type called Dictionary.
This type was declared earlier with the Type statement (see Step 2 above).
After the initial value is assigned to the variable RecNr, Visual Basic
opens the Translate.txt file for random access as file number 1. The Len(d)
instruction tells Visual Basic that the size of each record is 36 characters. (The
variable d contains two elements: sp is 20 characters and en is 16 characters.
Consequently, the total size of a record is 36 characters.) Next, Visual Basic
executes the statements inside the Do…Until loop.
The first statement in the loop prompts you to enter an English word and
assigns it to the variable choice. The value of this item is then passed to the
first element of the user-defined variable d (d.en). When you cancel or stop
entering data, Visual Basic exits the Do loop and executes the final statements in
the procedure that calculate and display the total number of records in the file.
The last statement closes the file.
When you enter an English word and click OK, you will be prompted to
supply a foreign language equivalent. If you do not enter a word, Visual Basic
will exit the loop and continue with the remaining statements. If you do enter the
foreign language equivalent, Visual Basic will assign it to the variable choice
and then pass it to the second element of the user-defined variable d (d.sp).
Next, Visual Basic will write the entire record to the file using the following
statement:
Put #1, recNr, d

After writing the first record, Visual Basic will increase the record counter
by one and repeat the statements inside the loop. The EnglishToSpanish
procedure allows you to enter any number of records into your dictionary. When
you quit supplying the words, the procedure uses the LOF and Len functions to
calculate the total number of records in the file, and displays the message:
"This file contains " & totalRec & "
record(s)."
After displaying the message, Visual Basic closes the text file (Translate.txt).
Creating a random-access file is only the beginning. Next, we create the
VocabularyDrill procedure to illustrate how to work with records in a file
opened for random access. Here you will learn statements that allow you to
quickly find the appropriate data in your file.
4. Run the EnglishToSpanish procedure. When prompted, enter data as shown in
Figure 14.3. For example, enter the word mother. When prompted for a Spanish
equivalent of mother, enter madre.

Figure 14.3. The contents of a random-access file opened in Notepad.

5. Below the EnglishToSpanish procedure, enter the VocabularyDrill procedure as
shown here:
Sub VocabularyDrill()
Dim d As Dictionary
Dim totalRec As Long
Dim recNr As Long
Dim randomNr As Long
Dim question As String
Dim answer As String
' open a random access file
Open "C:\Excel2013_ByExample\Translate.txt" _

For Random As #1 Len = Len(d)
' print the total number of bytes in this
file
Debug.Print "There are " & LOF(1) & " bytes
in this file."
' find and print the total number of records
recNr = LOF(1) / Len(d)
Debug.Print "Total number of records: " &
recNr
Do
' get a random record number
randomNr = Int(recNr * Rnd) + 1
Debug.Print randomNr
' find the random record
Seek #1, randomNr
' read the record
Get #1, randomNr, d
Debug.Print Trim(d.en); " "; Trim(d.sp)
' assign answer to a variable
answer = InputBox("What’s the Spanish
equivalent?", d.en)
' finish if cancelled
If answer = "" Then Close #1: Exit Sub
Debug.Print answer
' check if the answer is correct
If answer = Trim(d.sp) Then
MsgBox "Congratulations!"
Else
MsgBox "Invalid Answer!!!"
End If

' keep on asking questions until Cancel is
pressed
Loop While answer < > ""
' close file
Close #1
End Sub
After declaring variables, the VocabularyDrill procedure opens a file for
random access and tells Visual Basic the length of each record: Len =
Len(d). Next, two statements print in the Immediate window the total number
of bytes and records in the open file. The number of bytes is returned by the
LOF(1) statement. The number of records is computed by dividing the entire
file (LOF) by the length of one record—Len(d). Next, Visual Basic executes
the statements inside the loop until the Esc key is pressed or Cancel is clicked.
The first statement in the loop assigns the result of the Rnd function to the
variable randomNr. The next statement writes this number to the Immediate
window. The instruction:
Seek #1, randomNr
moves the cursor in the open file to the record number specified by the
variable randomNr. The next instruction reads the contents of the found record.
To read the data in a file opened for random access, you must use the Get
statement.
The instruction:
Get #1, randomNr, d
tells Visual Basic the record number (randomNr) to read and the variable
(d) into which data is being read. The first record in a random-access file is at
position 1, the second record at position 2, and so on. Omitting a record number
causes Visual Basic to read the next record. The values of both elements of the
user-defined type dictionary are then written to the Immediate window. The
Trim(d.en) and Trim(d.sp) functions print the values of the record being
read without the leading and trailing spaces that the user may have entered.
Next, Visual Basic displays an input box with a prompt to supply the foreign
language equivalent of the word shown in the input box title. The word is
assigned to the variable answer. If you press the Esc key instead of clicking
OK, Visual Basic closes the file and ends the procedure. Otherwise, Visual
Basic prints your answer to the Immediate window and notifies you whether or

not your answer is correct. You can press the Esc key or click the Cancel button
in the dialog box whenever you want to quit the vocabulary drill.
If you decide to continue and click OK, a new random number will be
generated, and the program will retrieve the English word and ask you for the
Spanish equivalent.
You can modify the VocabularyDrill procedure so that every incorrectly
translated word is written to a worksheet. Also, you may want to write all the
records from the Translate.txt file to a worksheet so that you always know the
contents of your dictionary.
6. Run the VocabularyDrill procedure. When prompted, type the Spanish equivalent
of the English word shown in the title bar of the input box. Press Cancel to exit
the vocabulary drill.
7. Press Alt+F11 to activate the Microsoft Excel application screen.
Steps 8 to 9 demonstrate the process of opening random-access files in Excel.
8. Click the File tab on the Ribbon, then click Open. Switch to the
C:\Excel2013_ByExample folder. Select All Files (*.*) in the Files of type dropdown box, and double-click the Translate.txt file. Excel displays the Text Import
Wizard shown in Figure 14.4.

Figure 14.4. The contents of a random-access file on attempt to open it
with Microsoft Excel. Notice that Excel correctly recognizes the original
data type—the data in a random-access file is fixed width.

9. Click Finish to load your translation data file into Excel.
10. Close the Translate.txt file.
Advantages and Disadvantages of Random-Access Files
Unlike sequential files, data stored in random-access files can be accessed
very quickly. Also, these files don’t need to be closed before writing into them
and reading from them, and they don’t need to be read or written to in order.
Random-access files also have some disadvantages. For example, they often
store the data inefficiently. Because they have fixed-length fields and records, the
same number of bytes is used regardless of the number of characters being stored.
So if some fields are left blank or contain strings shorter than the declared field

size, you may waste a lot of space.

WORKING WITH BINARY FILES
Unlike random-access files that store data in records of fixed length, binary files
store records with variable lengths. For example, the first record may contain 10
bytes, the second record may have only 5 bytes, while the third record may have 15
bytes. This method of storing data saves a lot of disk space because Visual Basic
doesn’t need to add additional spaces to the stored string to ensure that all the fields
are of the same length.
Just like random-access files, binary files can be opened for simultaneous read
and write operations. However, because binary file records are of variable length, it
is more difficult to manipulate these files. In order to retrieve the data correctly, you
must store information about the size of each field and record.
To work with binary files, you will use the following four statements:
The Get statement is used to read data. This statement has the following syntax:
Get [#]filenumber, [recnumber], varname
The filenumber argument is the number used in the Open statement to open a
file. The optional recnumber argument is the record number in random-access
files, or the byte number in binary access files, at which reading begins. If you
omit recnumber, the next record or byte after the last Get statement is read.
You must include a comma for the skipped recnumber argument. The required
varname argument specifies the name of the variable that will store this data.
The Put statement allows you to enter new data into a binary file. This statement
has the following syntax:
Put [#]filenumber, [recnumber], varname
The filenumber argument is the number used in the Open statement to open a
file. The optional recnumber argument is the record number in random-access
files, or the byte number in binary access files, at which writing begins. If you
omit recnumber, the next record or byte after the last Put statement is written.
You must include a comma for the skipped recnumber argument. The required
varname argument specifies the name of the variable containing data to be
written to disk.
The Loc statement returns the number of the last byte that was read. (In random-

access files, the Loc statement returns the number of the record that was last
read.)
The Seek statement moves the cursor to the appropriate position inside the
file.To quickly master the usage of the above statements, let’s open the Immediate
window and enter the instructions shown in the left column of the following table.
The purpose of this exercise is to enter your first and last name in a binary file
called C:\Excel2013_ByExample\MyData.txt and then retrieve the information
you entered.

Hands-On 14.7. Mastering the Get and Put Statements

When entering data to a binary file, use the following guidelines:
Before writing a string to a binary file, assign the length of the string to an Integer
type variable. Usually the following block of instructions can be used:
string_length = Len(variable_name)

Put #1, , string_length
Put #1, , variable_name
When reading data from binary files, first read the string length and then the string
contents. To do this, use the Get statement and the String function:
Get #1, , string_length
variable_name = String(string_length, " ")
Get #1, , variable_name
Advantages and Disadvantages of Binary Access Files
In comparison with sequential and random-access files, binary files are the
smallest of all. Because they use variable-length records, they can conserve disk
space. Like files opened for random access, you can simultaneously read and
write to a file opened for binary access. One big disadvantage of binary access
files is that you must know precisely how the data is stored in the file to retrieve
or manipulate it correctly.

CHAPTER SUMMARY
This chapter has given you a working knowledge of writing to and retrieving data
from three types of files: sequential, random access, and binary.
The next chapter introduces you to more automating tasks. You will learn, for
example, how to use VBA to control other applications. You will also learn various
methods of starting applications and find out how to manipulate them directly from
Microsoft Excel.

Part

6

Controlling
Other
Applications
with VBA

Chapter 15 Using Excel VBA to Interact with Other Applications
Chapter 16 Using Excel with Microsoft Access

The VBA programming language goes beyond Excel. It is used by other Office
applications such as Word, PowerPoint, Outlook, and Access and is also supported by
a growing number of non-Microsoft products. The VBA skills you acquire in Excel
can be used to program any application that supports this language.
In this part of the book, you learn how other applications expose their objects to
VBA.

Using
Chapter 15 Excel VBA
to Interact
with Other
Applications

One of the nicest things about the VBA language is that you can use it to launch
and control other Office applications. For example, you can create or open a Word
document straight from your VBA procedure without ever leaving Excel or seeing the
Word user interface. You can also start and manipulate a number of non-Office
programs by using built-in VBA functions. This chapter shows you various methods of
launching other programs and transferring data between them.

LAUNCHING APPLICATIONS
There are several ways you can manually start a program under the Windows
operating system. This section assumes that you are familiar with the manual
techniques of launching applications and that you are eager to experiment with
additional techniques to start applications by writing code.
Let’s begin with the simplest of all—the Shell function, which allows you to
start any program directly from a VBA procedure. Suppose that your procedure must
open the Windows Notepad application. To launch Notepad, all you need is one
statement between the keywords Sub and End Sub. Or better yet, you can type the
following statement in the Immediate window and press Enter to see the result
immediately:
Shell "notepad.exe", vbMaximizedFocus
Here, notepad.exe is the name of the program you want to start. This name should
include the complete path (the drive and folder name) if you have any concerns that the
program may not be found. Notice that the program name is in double quotes. The
second argument of the Shell function is optional. This argument specifies the

1. Using the Shell Function to Activate the Control Panel 1. If the Shell function cannot start the specified program.1 lists the window style constants and appearance options.3 Hands-On 15. the program will be minimized with focus. In this example. Window styles used in the Shell function If the Shell function is successful in launching the specified executable file. Visual Basic generates an error. Notepad will appear in a maximized window. do not enter any other statements in the procedure after the Shell function. Open a new workbook and save it as C:\Excel2013_ByExample\Practice_ . Please note files for the “Hands-On” project may be found on the companion CDROM. The Shell function works asynchronously.1. If the window style is not specified. Let’s see how to use the Shell function to launch the Control Panel. If you want to work with the program launched by the Shell function. it returns to the procedure to continue with the execution of the remaining instructions without giving you a chance to work with the application. and immediately after launching.window style. Table 15. it will return a number called a Task ID which uniquely identifies the application that has been launched. That means that Visual Basic starts the program specified by the Shell function. Table 15.

Run the above procedure. 4.exe". In the Shell_Function Code window. before you create a procedure that changes the regional settings in your computer. Unfortunately. The Control Panel contains a number of tools represented by individual icons. If asked. click the Shortcut tab and then click the Change Icon . and Region icon or link.xlsm VBA project. choose Properties from the shortcut menu. In the Properties window. Close the Control Panel window. vbNormalFocus End Sub 5. click the Clock.Excel15. 3. 8. Switch to the Visual Basic Editor window and insert a new module in the Practice_Excel15. and change the module name to Shell_Function. When you run the StartPanel procedure. 6. Next. the icons in the Control Panel have the Properties option disabled. 7. Right-click the Region link and choose Create Shortcut from the shortcut menu. 2. 9.xlsm. As you know. let’s find out the name of the file that activates this tool. you can check what filename is driven by a particular icon by looking at the icon’s properties. enter the StartPanel procedure as shown below: Sub StartPanel() Shell "Control. Rename the VBA project WorkWApplets. click Yes to place the shortcut on the desktop. Language. the Control Panel window is opened automatically on top of any other windows. however. there is a program behind every icon that is activated when the user double-clicks the icon or selects the icon with the arrow keys and then presses Enter. For example. As a rule. find out the name of the Control Panel file by creating a shortcut. Switch to your desktop and right-click the Region shortcut icon. You can. In the Control Panel window. 10.

1. .button to bring up the Change Icon window shown in Figure 15.

Write down the name of the CPL file (Control Panel Library) or DLL file . 11. Each Control Panel tool icon file has a .Figure 15.cpl extension.1.

Some of the files that activate Control Panel tools are listed in Table 15. In the ShellFunction Code window.Print nrTask End Sub The ChangeSettings procedure demonstrates how to launch the Control Panel’s Regional Settings icon using the Shell function.2. Notice that the arguments of the Shell function must appear in parentheses if you want to use the returned value . Table 15.(Dynamic Link Library) listed at the top of the Change Icon window and close all the windows that were opened in this exercise. Sample files that activate Control Panel tools 12.cpl".exe intl. enter the ChangeSettings procedure as shown below: Sub ChangeSettings() Dim nrTask nrTask = Shell("Control. vbMinimizedFocus) Debug.2.

13. this instruction does not open a new occurrence of the program.exe " & iconFile. to launch PowerPoint from the Immediate window. This method is available from the Microsoft Excel Application object.2. You may want to modify the above procedure as follows: Sub ChangeSettings2() Dim nrTask Dim iconFile As String iconFile = InputBox("Enter the name of the control " & _ "icon CPL or DLL file:") nrTask = Shell("Control. For example.later in your procedure. _ vbMinimizedFocus) Debug. all you need to do is type the following instruction and press Enter: Application. . revise the above procedure as follows: nrTask = Shell("Control. You can use the constants shown in Table 15. it’s more convenient to use the Visual Basic ActivateMicrosoftApp method than the Shell function. The above statement starts Microsoft PowerPoint if it is not already running. the second an index of 1.ActivateMicrosoftApp xlMicrosoftPowerPoint Notice that the ActivateMicrosoftApp method requires a constant to indicate which program to start. vbMinimizedFocus) The first tab in the window has an index of 0. Run the ChangeSettings procedure several times. each time supplying a different CPL file according to the listing presented in Table 15.1".3 with the ActivateMicrosoftApp method. If the program is already open.cpl 0. To open the Control Panel window with the Languages tab activated.Print nrTask End Sub If a program you want to launch is a Microsoft application.exe intl. it simply activates the already running application. and so on.

your VBA procedure must know how to switch between the open programs. here’s how you can activate Microsoft Word: AppActivate "Microsoft Word" Notice that the name of the application is surrounded by double quotation marks. wait] Only the title argument is required. Suppose that in addition to Microsoft Excel.Table 15. The optional argument wait is a Boolean value (True/False) that specifies when Visual Basic activates the application. you have two other applications open: Microsoft Word and Windows Explorer. the calling application waits until it has the focus before it activates the specified application. even if the calling application does not have the focus.3. If you place True in the position of the wait argument. For example. You can also use the return value of the Shell function as the argument of the AppActivate statement: ' run Microsoft Word . The value of False in this position immediately activates the specified application. This is the name of the application as it appears in the title bar of the active application window or its task ID number as returned by the Shell function. use the AppActivate statement using the following syntax: AppActivate title [. ActivateMicrosoftApp method constants MOVING BETWEEN APPLICATIONS Because the user can work simultaneously with several applications in the Windows environment. To activate an already open program.

string. You can send a key or a combination of keys and achieve the same result as if you worked directly in the active application window using the keyboard. wait] The required argument. This statement merely changes the focus. .” use the following instruction: SendKeys "f" To send the key combination Alt+f. CONTROLLING ANOTHER APPLICATION Now that you know how to use VBA statements to start a program and switch between applications. 1) ' activate Microsoft Word AppActivate ReturnValue End Sub T he AppActivate statement is used for moving between applications and requires that the program is already running. This statement allows you to send a series of keystrokes to the active application window.Sub RunWord() Dim ReturnValue As Variant ReturnValue = Shell("C:\Program Files\" & _ "Microsoft Office 15\root\office15\" & _ "WINWORD. The AppActivate statement will not start an application running.EXE". to send a letter “f. To send a combination of keys. For example. is the key or key combination that you want to send to the active application. use: SendKeys "%f" The percent sign (%) is the symbol used for the Alt key. The simplest way for an application to get control of another is by means of the SendKeys statement. use the following statement: SendKeys "+{TAB}" The plus sign (+) denotes the Shift key. such as Shift+Tab. The SendKeys statement looks as follows: SendKeys string [. The specified application becomes the active window. let’s see how one application can communicate with another.

Remember to enclose these codes in quotes. wait. For example: SendKeys "{BACKSPACE}" Table 15. Visual Basic returns to the procedure only after the sent keystrokes have been executed.4. is optional.4.To send other keys and combinations of keys. If wait is True. To send characters that aren’t displayed when you press a key. Keycodes used with the SendKeys statement . If False (default).4. Visual Basic returns to the procedure immediately upon sending the keystrokes. Wait is a logical value that is True or False. use the codes in Table 15. see Table 15. The SendKeys statement’s second argument.

You can only send keystrokes to applications that were designed for the Microsoft Windows operating system. .

Figure 15. Earlier in this chapter you learned how to launch various Control Panel windows . press the Alt key. These keys are: plus sign (+). To send braces. to activate the Insert tab and select the Insert Picture command. and parentheses ( ). After pressing the key for the tab you’d like to activate. as illustrated in Figure 15.2. the Ribbon will now display the access keys assigned to individual commands. SendKeys and Reserved Characters Some characters have a special meaning when used with the SendKeys statement.2.You can use the SendKeys statement to activate a particular Ribbon tab. You should see the Ribbon mappings as shown in Figure 15. Each Ribbon tab has an access key that can be used with the SendKeys statement to activate a particular tab.3. Figure 15. Each icon/command in the Ribbon has an access key that can be used to activate a particular command using the SendKeys statement. use the following keys: SendKeys "%np" To view the list of keys assigned to individual Ribbon tabs. To send these characters to another application. you must enclose them in braces {}.3. caret (^). enter {{} and {}}. tilde (~). For example.

2. as shown below: Sub FindCPLFiles_Win8() ' The keystrokes are for Windows 8 Shell "Explorer". True ' delay the execution by 5 seconds Application. The example procedure uses keystrokes that work under Windows 8.Wait (Now + TimeValue("0:00:05")) ' change the search location to search all folders ' on your computer C drive SendKeys "%js".2. Let’s create a VBA procedure that will locate all the files with the . Insert a new module into the WorkWApplets (Practice_Excel15.using CPL files. True ' Activate the Search box .Wait (Now + TimeValue("0:00:05")) ' Activate the Search box SendKeys "{F3}". True SendKeys "%js". True SendKeys "%a".cpl extension on your computer. Enter the FindCPLFiles_Win8 procedure.xlsm) project and rename it SendKeysStatement. vbMaximizedFocus ' delay the execution by 5 seconds Application. Using the SendKeys Statement in a VBA Procedure 1. True SendKeys "%c". Hands-On 15.

to gain full control of another application you must resort to other methods. True ' type in the search string SendKeys "*. True End Sub After activating Windows Explorer with the Shell statement. 3. The old data-exchange technology called DDE (Dynamic Data Exchange) is a slow and difficult to work with protocol that allows you to dynamically send data between two programs by creating a special channel for sending and receiving . SendKeys Statement Is Case Sensitive When you send keystrokes with the SendKeys statement. the procedure uses a number of keystrokes from Table 15. and then click Run). Switch to the Microsoft Excel application window and run the FindCPLFiles_Win8 procedure (use Alt+F8 to open the Macro dialog.cpl". Using Automation. to send the key combination Ctrl+d.SendKeys "{F3}". Therefore. you must use ^d. highlight the name of the procedure.4 to perform operations in the active application. properties. and to send Ctrl+Shift+d. OTHER METHODS OF CONTROLLING APPLICATIONS Although you can pass commands to another program by using the SendKeys statement. There are two standard ways in which applications can communicate with one another. you can write VBA procedures that control other applications by referencing another application’s objects. and methods. Observe what happens in the Search Results window as your VBA procedure sends keystrokes that activate the Search function. bear in mind that you must distinguish between lower. True ' execute the Search SendKeys "{ENTER}". you should use the following string: ^+d.and uppercase characters.

such as documents or paragraphs. It should be used only to communicate with older applications that do not support Automation. you may require more functionality than simply activating it for sending keystrokes. Experiments with Linking and Embedding 1. all Microsoft Office applications can act as Automation servers and controllers. The applications that support Automation are called Automation servers or Automation objects.3. Understanding Linking and Embedding Before you learn how to control other applications from a VBA procedure using Automation. Compound documents are created by either linking or embedding objects. Some applications can be only a server or a controller. The main difference between a linked object and an embedded object is in the way the object is stored and updated. When you use the manual method to embed an object. DDE is not covered in this book. Understanding Automation When you communicate with another application. you can write a VBA procedure in Excel to manipulate Word objects. Object linking and embedding (OLE) allows you to create compound documents. A compound document contains objects created by other applications. Let’s try this out. Hands-On 15. let’s take a look at how the manual method is used to link and embed an object. Excel only needs to know the name of the application that was used to create this object and the method of displaying the object on the screen. You can embed an entire Word document in a Microsoft Excel worksheet. if you embed a Word document in a Microsoft Excel worksheet. you may want to create and manipulate objects within that application. For example. Because both Excel and Word support Automation. . The Automation controllers can be all sorts of ActiveX objects installed on your computer. The applications that can manipulate a server’s objects are referred to as Automation controllers.information. you first need to copy it in one application and then paste it into another. For example. and others can act in both of these roles. Beginning with the Office 2000 release. Activate Microsoft Word and open any document.

(Right-click on a cell.Document denotes the version of Word . Notice that when you embed an object.2. A demonstration of linking and embedding.8". Of course. Click the Paste option button."") The number following the Word. In a Microsoft Excel worksheet. and choose Paste from the shortcut menu. Figure 15.) The text will be pasted into the worksheet as an embedded object (cell A3). the information is static.Document. 3. Figure 15. all of the data is stored in the destination file. the source program must be installed on the computer. you can now paste the copied text using one of four methods. the Formula bar displays: =EMBED("Word.4 displays samples of the four methods described here. the embedded object is not updated. Select and copy any text. (Right-click on a cell. Paste as text. select Microsoft Word Document Object in the As list. When you embed objects. The embedded object becomes a part of the destination file.) The copied text will appear in the active cell (cell A1). and choose Paste Special. Paste as an embedded object. you must double-click it. To change the embedded data.4. and click OK. This will open the object for editing in the source program. When the data changes in the source file. This causes the file size to increase considerably. Because the embedded object is not connected with the original data.

12". Linking and Embedding with VBA Now that we’ve reviewed the manual process needed to link and embed objects.Document. and click OK.Document. If your source program is Word 2013/2010/2007.12|’C:\Excel2013_HandsOn\ LinkOrEmbed."") Paste as a linked object. You can quickly activate the source file by clicking on the hyperlink.) The pasted data appears in the worksheet as single underlined. When you double-click the linked object (cell A7). You should replace the reference to C:\Hello.docx’!’!OLE_LINK5’ Paste as a hyperlink. choose Hyperlink.) Although the destination file displays all of the data. Linking objects is a dynamic operation. and choose Paste Special. let’s see how linking and embedding is done with VBA. Because the destination document contains only information on how the object is linked with the source document. Version 8 indicates that we are bringing an object from Word 97-2003. Hands-On 15.4. select Microsoft Word Document Object in the As list. The following formula is used to link an object in Microsoft Excel: =Word. and click OK. The InsertLetter procedure shown below demonstrates how to programmatically embed a Word document in an Excel worksheet. (Right-click on a cell. the formula bar displays: =EMBED("Word. Click the Paste option button. it stores only the address of the data. (Right-click on a cell. Writing a Procedure to Embed a Word Document in a Worksheet . colored text (cell A12).you are using. and choose Paste Special. This means that the linked data is updated automatically when the data in the source file changes. object linking doesn’t increase the size of a destination file.docx with your own document name. Click the Paste link option button. the source application is launched.

1.xlsm) VBA project and rename it OLE. The procedure opens a new workbook and embeds the indicated Word document in it. Additional arguments that the AddOLEObject method can use are listed in the Visual Basic online documentation. Insert a new module into the WorkWApplets (Practice_Excel15. or you have enough disk space and memory to handle large files.docx" End Sub The InsertLetter procedure uses the AddOLEObject method.AddOLEObject _ Filename:="C:\Excel2013_HandsOn\Hello. as shown below: ActiveSheet. you must specify an additional argument. . 3. If you’d rather link a document. 2.Shapes. You will never need the source file or use source text in other compound documents.Shapes. enter the InsertLetter procedure as shown below: Sub InsertLetter() Workbooks. This method creates an OLE object and returns the Shape object that represents the new OLE object.AddOLEObject FileName:="C:\Excel2013_HandsOn\Hello.Add ActiveSheet. Link.docx". Run the InsertLetter procedure. _ Link:=True Objects—Linking or Embedding Use object embedding rather than linking if: You don’t mind if the size of a document increases. In the OLE module Code window.

Because the declaration As Object or As Variant is very general in nature. which determines the rules for creating objects by the server application and specifies the methods that both the server and the control application must apply when using these objects. methods. Late Binding When you declare a variable As Object or As Variant. The controller application doesn’t need to know the internal structure of the object in order to control it. Visual Basic uses late binding. and you want to make sure that they can read the data without any problems. This interface includes properties.You want to send the document to other people by email or on a disk. This process is known as binding. it only needs to know how to manipulate the object interface that is made available by the server application. The disadvantage is that there is no support for built-in constants. Your choice of binding will have a great impact on how well your application performs. Understanding Binding For a controller application to communicate with the Automation object (server). COM and Automation The driving force behind Automation is the Component Object Model (COM). Because Visual Basic does not know at design time the type library to which your object is referring. Late binding simply means that Visual Basic doesn’t associate your object variable with the Automation object at design time but waits until you actually run the procedure. The following declaration results in late binding of the specified object: Dim mydoc As Object The advantage of late binding is that all the Automation objects know how to use it. When a server application creates an object. Late binding is also known as runtime binding. it automatically makes available an interface that goes along with it. . There are two types of binding: late binding and early binding. and events that can be recognized by the object. The COM standard contains a collection of functions that are made available as Automation interfaces. Visual Basic cannot determine at compile time that the object your variable refers to has the properties and methods your VBA procedure is using. you must associate the object variable that your VBA procedure uses with the actual Automation object on the server.

Documents.Application") With objWord .5. Hands-On 15.Visible = True . Be sure to modify the filename so that you can actually print a Word document that exists on your hard disk.xlsm) VBA project and rename it Automation. Insert a new module into the WorkWApplets (Practice_Excel15. Also. 2. Use late binding if you are uncertain that your users will have the referenced type libraries installed on their machines.you must define constants in your code by looking up the values in the application’s documentation. Late binding makes it possible to access objects in a type library of another application without first establishing a reference to the object library. In the Automation module Code window. querying an application at runtime can slow down the performance of your solution . enter the PrintWordDoc procedure as shown below: Sub PrintWordDoc() Dim objWord As Object Set objWord = CreateObject("Word. The purpose of this procedure is to print out a Word document.Open "C:\Excel2013_HandsOn\LinkOrEmbed. Let’s write a VBA procedure that uses late binding.docx" . Printing a Word Document with VBA 1. The main difference between late binding and early binding is how you declare your object variables.

Options.PrintOut .. For example. You should get a printed copy of your document. Although VBA . and Auto Quick Info (all discussed in Chapter 3) can help you write your code faster and with fewer errors. This means that Visual Basic associates your object variable with the Automation object while the procedure source code is being translated into executable code. document. The following declarations result in early binding: Dim mydoc As Word.ObjectType In the above syntax. you can look up external objects. The handy built-in syntax checking.Document Dim mydoc As Excel.PrintBackground = False . Word and Excel). and methods with the Object Browser. early binding allows you to use built-in constants as arguments for methods and property settings. Early Binding When you declare object variables as specific object types. The general syntax looks like this: Dim objectVariable As Application. Visual Basic Auto Syntax Check. Application is the name of the application as it appears in the Object Browser’s Project/Library drop-down list (for example.ActiveDocument.Close . or support for built-in constants aren’t available with late binding. Run the PrintWordDoc procedure. also known as compile-time binding. you do not need to define them.Documents. properties. In addition. ObjectType is the name of the object class type (for example.Worksheet Early binding allows you to take full advantage of many of the debugging tools that are available in the Visual Basic Editor window. Visual Basic uses early binding. application. workbook. and worksheet). IntelliSense features. Because these constants are available in the type library at design time.Quit End With Set objWord = Nothing End Sub 3. Auto List Members.

Follow the steps outlined in Hands-On 15. choose the name of the application in the Available References list box. Establishing a Reference to a Type Library If you decide to use early binding to connect to another application via Automation. some very old Windows applications can only use late binding In order to use early binding.5).procedures that use early binding execute faster. In the References dialog box. Setting Up a Reference to a Type Library 1. click the checkbox next to Microsoft Word 15. 2. Hands-On 15.0 Object Library or its earlier release (see Figure 15.6. Use early binding when you are certain that your users will have the referenced type libraries installed on their machines. . you must first establish a reference to the object library (see the following section). Scroll down in the Available References list box to locate this object library. and choose Tools | References. Select the current project in the Project Explorer window. start by establishing a reference to the object library whose objects you are planning to manipulate. For this example. Activate the Visual Basic Editor window. 3.6 to create a reference to the Microsoft Word object library.

Setting a reference to the required object library is one of the steps you need to complete before attempting to manipulate objects of another application. The references that are checked are listed by priority. you can browse the object properties and methods by using the Object Browser (see Figure 15. The references that are not used are listed alphabetically.6). After setting a reference to the required object library.Figure 15. 4. Visual Basic searches each referenced object library in the order in which the libraries are displayed in the References dialog box. For example. Click OK to close the References dialog box.0 object library has a higher priority than the Microsoft Word 15.5. . in Excel.0 object library. the Microsoft Excel 15. The References dialog box lists the names of the references that are available to your VBA project. When a procedure references an object.

properties.Figure 15.5). All of the Microsoft Word objects. and methods can be accessed from a Microsoft Excel VBA project after adding a reference to the Microsoft Word 15. .6.0 object library (see Figure 15.

The Automation object must be assigned to the object variable by using the Set keyword. to activate Word using the Automation object.CREATING AUTOMATION OBJECTS To create an Automation object in your VBA procedure. use the CreateObject function. as shown below: Set variable_name = CreateObject(class) For example. If you are using early binding. Assign the object returned by the CreateObject or GetObject function to the object variable by using the Set keyword. use the References dialog box to establish a reference to the Application object type library.Document Set wordAppl = CreateObject("Word. use the CreateObject function with the following syntax: CreateObject(class) The argument class is the name of the application you want to reference. If the Automation object already exists. If the Automation object doesn’t exist yet.Application") Or ' late binding . follow these steps: Declare an object variable using the Dim…As Object or Dim…As Application.ObjectType clause (see the topics on using late and early binding in the preceding sections). This name includes the object class type as discussed earlier (see the section on early binding). include the following declaration statements in your VBA procedure: ' early binding Dim wordAppl As Word. Using the CreateObject Function To create a reference to the Automation object from a VBA procedure. establish the reference to the object by using the GetObject function.

If the Microsoft Word 15.7. locate this object library and click the checkbox to select it. This means that you cannot run more than one instance of the application at a time. 2. Creating a New Word Document Using Automation Let’s see how you can apply what you have learned in the preceding sections about binding in a real-life example. In the Visual Basic Editor screen.Application") As a rule.Application Dim strFolder As String Dim strFileName As String Dim flag As Boolean . Sometimes you may be required to open a Word document programmatically and write some data to it straight from Excel.0 object library or an earlier object library is not selected in the Available References list box. 3. Therefore. the CreateObject function creates a new instance of the specified Automation object. if Word or PowerPoint is already running. The following example uses early binding.xlsm) VBA project and choose Tools | References. register themselves as so-called “single-instance” applications. however.Dim wordAppl As Object Set wordAppl = CreateObject("Word. In the Automation module Code window. Click OK when done. select the WorkWApplets (Practice_Excel15. Creating a New Word Document with VBA 1. the CreateObject function will simply reference a running instance instead of creating a new instance. Microsoft Word and PowerPoint are such single-instance applications. Hands-On 15. Some applications. enter the WriteLetter procedure as shown below: Sub WriteLetter() Dim wordAppl As Word.

Paragraphs(1). _ InsertBefore "Invitation" . "Document Created and Saved" Set wordAppl = Nothing .Range." .docx" Set wordAppl = CreateObject("Word...Visible = True ..StatusBar = "Saving document.". _ vbInformation.StatusBar = "Exiting Word..ActiveDocument... Len(strFolder) ." .Add .Documents.Application") With wordAppl .On Error GoTo ErrorHandler flag = True strFolder = "C:\Excel2013_ByExample\" strFileName = "Invite.StatusBar = "Creating a new document.ActiveDocument.SaveAs2 _ Filename:=strFolder & strFileName .Quit End With ExitHere: If flag Then MsgBox "The Document file " & _ strFileName & Chr(13) & "was saved in " & _ Left(strFolder.1) & "." .

As mentioned earlier. and close the Word application (the Quit method).Exit Sub ErrorHandler: If Err. . Recall that this type of declaration (early binding) requires that you establish a reference to the Microsoft Word object library (discussed earlier in this chapter). it will use the currently active instance of Word. To run the procedure. the statement: wordAppl.Description flag = False End If Resume ExitHere End Sub The WriteLetter procedure begins with the declaration of the object variable of the specific object type (Word. enter text in the first paragraph (the InsertBefore method). Microsoft Word is a single-instance application.Number < > 0 Then MsgBox Err.Visible = True will make the launched Word application visible so that you can watch VBA at work. When the Word application is closed. 4.Number & ":" & Err. save the document in a disk file (the SaveAs2 method). This means that you cannot run more than one instance of Word at a time. otherwise. Because the applications launched by Automation don’t appear on the screen. The remaining statements of this procedure open a new Word document (the Add method). Select the WriteLetter procedure in the list of macros and click Run.Application). In short. switch to the Microsoft Excel application window and choose View | Macros | View Macros . the CreateObject function used in the WriteLetter procedure will launch Word if it is not already running. Each statement is preceded by an instruction that changes the message displayed in the status bar at the bottom of the Word application window. the instruction: Set wordAppl = Nothing will clear the object variable to reclaim the memory used by the object. The Automation object returned by the CreateObject function is assigned to the object variable called class.

consider using the GetObject function. you would use: ' early binding Dim wordObj As Word.Sheet.Sheet. you could use the following declaration: ' late binding Dim excelObj As Object Set excelObj = GetObject("C:\Excel2013_HandsOn\"& _ "Report. "Excel. The function looks like this: GetObject([pathname][.8") Use “Excel.xls workbook and force the object to be an Excel 97–2003 version worksheet.Sheet Excel. however. one of the arguments must be specified. class]) The GetObject function has two arguments that are optional. If pathname is omitted. class is required.Chart Excel.Application Set wordObj = .Document PowerPoint. To set the object variable to a specific Word document.xls".Range Word.Using the GetObject Function If you are certain that the Automation object already exists or is already open.12” for Microsoft Office Excel 2007-2013 Worksheet.Application Excel. For example: Excel.Application Word.Application To create an Excel object based on the Report.

Opening and Modifying a Word Document with VBA This Hands-On uses the Word document file (Invite.8.7.docx") To access a running Office application object. 1.docx" myAppl = "Word. As you recall.Document Dim wordAppl As Word. "Excel.Application") When the GetObject function is called without the first argument.doc) created in Hands-On 15. enter the CenterText procedure as shown below: Sub CenterText() Dim wordDoc As Word. it returns a reference to an instance of the application.Application" ' first find out whether the specified . Hands-On 15.Application Dim strDoc As String Dim myAppl As String On Error GoTo ErrorHandler strDoc = "C:\Excel2013_ByExample\Invite. leave the first argument out: Dim excelObj As Object Set excelObj = GetObject(. In the Automation module Code window. If the application isn’t running. Opening an Existing Word Document The CenterText procedure that follows demonstrates the use of the GetObject function to access the Invite. The CenterText procedure will center the first paragraph in the specified Word document. this file was created earlier in this chapter by the WriteLetter procedure. an error will occur.GetObject("C:\Excel2013_ByExample\Invite.doc file.

Alignment = wdAlignParagraphCenter End With wordDoc.Range .document exists If Not DocExists(strDoc) Then MsgBox strDoc & " does not exist.ParagraphFormat.> will get the specified document.Application. " Set wordAppl = CreateObject("Word.Application") Set wordDoc = wordAppl.> will create " & _ "a new instance of Word.Open(strDoc) Else MsgBox "Word is running .Documents." & Chr(13) & Chr(13) _ & "Please run the WriteLetter procedure to create " & _ strDoc & ". " ' bind the wordDoc variable to a specific Word document Set wordDoc = GetObject(strDoc) End If ' center the 1st paragraph horizontally on page With wordDoc." Exit Sub End If ' now check if Word is running If Not IsRunning(myAppl) Then MsgBox "Word is not running .Quit SaveChanges:=True .Paragraphs(1).

In the Automation module Code window. the error number and error description are displayed. enter the IsRunning function procedure as shown below: Function IsRunning(ByVal myAppl As String) As Boolean Dim applRef As Object . In the Automation module Code window. Based on the findings. checks whether a copy of Microsoft Word is already running. IsRunning (see code in Step 3). either the CreateObject or GetObject function is used.Description.Number End Sub The CenterText procedure uses a custom function named DocExists (see code in Step 2) to check for the existence of the specified document. Another custom function.Set wordDoc = Nothing Set wordAppl = Nothing MsgBox "The document " & strDoc & " was reformatted. enter the DocExists function procedure as shown below: Function DocExists(ByVal mydoc As String) As Boolean On Error Resume Next If Dir(mydoc) < > "" Then DocExists = True Else DocExists = False End If End Function 3._ "Error: " & Err." Exit Sub ErrorHandler: MsgBox Err. 2. vbCritical. If an error occurs.

return a reference to that instance. Using the New Keyword Instead of using the CreateObject function to assign a reference to another application. you can use the New keyword. If the application is already running and you don’t want to start another instance. then choose Debug | Step Into. The New keyword tells Visual Basic to create a new instance of an object.Number = 429 Then IsRunning = False Else IsRunning = True End If ' clear the object variable Set applRef = Nothing End Function 4. you . myAppl) If Err. you can use the New keyword in the following way: Dim objWord As Word.Application Set objAccess = New Access. and assign the reference to the object variable being declared. 5. Visual Basic creates a new instance of the application. Keep on pressing F8 to execute the procedure step by step.Application Dim objAccess As Access. Notice how Visual Basic jumps to the appropriate function procedure to find out whether the specified Word document exists and whether the Word application is running. In the Visual Basic Editor window.Application Set objWord = New Word. When a yellow highlight appears on the Sub CenterText line. Each time you use the New keyword. position the pointer anywhere within the code of the CenterText procedure.On Error Resume Next Set applRef = GetObject(. Using the New keyword is more efficient than using the CreateObject function.Application Object variables declared with the New keyword are always early bound. For example. press F8.

For example: Dim objWord As New Word.0 (or earlier) object library.Application Notice that when you declare the object variable with the New keyword in the Dim statement. Therefore. The following section demonstrates how to use the New keyword to create a new instance of Microsoft Outlook and write your contact addresses to an Excel worksheet.Application Set objWord = New Word. In the Automation module Code window. The New keyword can also be used to create a new instance of the object at the same time that you declare its object variable. The example procedure that follows will insert your Outlook contact information into an Excel spreadsheet. 2. this method of creating an object variable is not recommended because you lose control over when the object variable is actually created. However. Establish a reference to the Microsoft Outlook 15. if you want control over when the object is created. Using the New keyword in the declaration statement causes the object variable to be created even if it isn’t used.Application .should use the GetObject function. you do not need to use the Set statement.Application The Set statement can be placed further in your code where you need to use the object. begin by establishing a reference to the Microsoft Outlook 15. Using Automation to Access Microsoft Outlook To access Outlook’s object model directly from Excel.9. enter the GetContacts procedure as shown below: Sub GetContacts() Dim objOut As Outlook. Bringing Outlook Contacts to Excel 1. Hands-On 15. always declare your object variables using the following syntax: Dim objWord As Word.0 or earlier object library.

Activate For Each cell In Range("A1:F1") cell.GetNamespace("MAPI") Headings = Array("Full Name".FormulaR1C1 = Headings(i) i = i + 1 Next For Each objItem In objNspc.Value = _ objItem.Items With ActiveSheet .Value = _ objItem.GetDefaultFolder _ (olFolderContacts).Add Sheets(1).FullName .BusinessAddressCity .Dim objNspc As Namespace Dim objItem As ContactItem Dim r As Integer ' row index Dim Headings As Variant Dim i As Integer ' array element Dim cell As Variant r = 2 Set objOut = New Outlook.Value = _ objItem.Cells(r. 3). 2). 1). "City".Cells(r. "E-Mail") Workbooks.Application Set objNspc = objOut. "Zip Code".BusinessAddress .Cells(r. _ "State". "Street".

Value = _ objItem.Cells(r. Journal. After all the contact items are written to an Excel spreadsheet.). An item is a particular instance of Outlook data. 6)..Cells(r. which in turn contain items. This variable is defined by a specific object type (Outlook.BusinessAddressState .Email1Address End With r = r + 1 Next objItem Set objItem = Nothing Set objNspc = Nothing Set objOut = Nothing MsgBox "Your contacts have been dumped to Excel. etc. we use the New keyword discussed earlier to create a new instance of an Outlook Application object. the procedure releases all . therefore VBA will use early binding.BusinessAddressPostalCode . In order to access contact items in Outlook. Notice that in this procedure. and assign the reference to the objOut variable being declared. The GetDefaultFolder method returns an object variable for the Contacts folder. the constant representing the folder you want to access.Value = _ objItem. the procedure uses another For Each…Next loop to iterate through the Items collection in the Contacts folder. return a reference to that instance. Tasks.Cells(r. 5). 4). you also need to declare object variables to reference the Outlook Namespace and Item objects. The Namespace object represents the message store known as MAPI (Messaging Application Programming Interface). The Namespace object contains folders (Contacts. such as an email message or a contact. This method takes one argument." End Sub The GetContacts procedure starts by declaring an object variable called objOut to hold a reference to the Outlook application.Application).Value = _ objItem. After writing column headings to the worksheet using the For Each…Next loop.

. click OK to the message and switch to the Microsoft Excel application window to view your Outlook contacts in a new workbook file that was created by the GetContacts procedure.object variables by setting them to Nothing. 3. Run the GetContacts procedure. Choose Allow access for 1 minute and click Yes to allow the operation. You learned how to send keystrokes to another application by using the SendKeys method and how to manually and programmatically link and embed objects. you may get a warning message that the program is trying to access email addresses. activate. you learned how to launch. and control other applications from VBA procedures. You also learned how to retrieve your contact addresses from Microsoft Outlook and place them in an Excel worksheet. Additionally. you will learn various methods of controlling Microsoft Access from Excel. You expanded your knowledge of VBA statements with two new functions—CreateObject and GetObject—and learned how and when to use the New keyword. When you run the GetContacts procedure. CHAPTER SUMMARY In this chapter. you used Automation to create a new Word document from Excel and accessed this document later to change some formatting. In the next chapter. Upon the successful execution of the procedure.

OLB file and can be found in the C:\Users\< username >\Microsoft Office 15\root\office15 folder. OBJECT LIBRARIES A Microsoft Access database consists of various types of objects stored in different object libraries. properties. The library is stored in the MSACC.Chapter 16 Using Excel with Microsoft Access In Chapter 15. you learned about controlling Microsoft Word and Outlook from Excel via Automation. you will be accessing objects. provides objects that are used to display data and work with the Microsoft Access 2013 application. and methods from several libraries that are listed below.0 object library This library. you will be able to look up this library’s objects. shown in Figure 16. . and methods in the Object Browser.1. The Microsoft Access 15. let’s briefly examine the data access methods that Microsoft Access uses to gain programmatic access to its objects. properties. This chapter shows you how to programmatically use Microsoft Access from Excel as well as how to retrieve Access data into an Excel spreadsheet by using the following methods: Automation DAO (Data Access Objects) ADO (ActiveX Data Objects) Before you learn how to use Excel VBA to perform various tasks in an Access database. In this chapter. After setting up a reference to this library in the References dialog box (this is covered in the next section).

6 object library Data Access Objects (DAO) that are provided by this library allow you to determine the structure of your database and manipulate data using VBA.Figure 16. you will be able to look up the library’s objects. The Microsoft DAO 3. After setting up a reference to this library in the References dialog box (this is covered in the next section).2) . properties. The Microsoft Access 15. and methods in the Object Browser (see Figure 16.dll file and can be found in the C:\Program Files\Common Files\Microsoft Shared\DAO folder.0 object library. This library is stored in the DAO360.1.

2.Important Note: On 64-bit systems.1 library (ADODB) ActiveX Data Objects (ADO) provided by this library let you access and manipulate data using the OLE DB provider. insert. The Microsoft ActiveX Data Objects 6. properties. modify. Figure 16. and methods in the Object Browser (see . ADO objects make it possible to establish a connection with a data source in order to read. After setting up a reference to this library in the References dialog. look for files mentioned in this section in Program Files(x86) instead of Program Files folder. you will be able to access this library’s objects.6 object library. and delete data in an Access database. The Microsoft DAO 3.dll and can be found in the C:\Program Files\Common Files\System\ado folder. This library is stored in MSADO15.

you can define tables. properties. After setting up a reference to this library in the References dialog box.Figure 16. indexes. 6.0 for DDL and Security library (ADOX) Objects that are stored in this library allow you to define the database structure and security. as well as create and modify user and group accounts. For example. and relationships.3).dll and can be found in the C:\Program Files\Common Files\System\ado folder. The Microsoft ActiveX Data Objects 6. is stored in MSADOX. . and methods in the Object Browser.3. This library. you will be able to look up this library’s objects.4. The Microsoft ADO Ext. shown in Figure 16. Figure 16.1 library (ADODB).

Please note that database replication is no longer supported in Access 2013. After setting up a reference to this library in the References dialog box. . you will be able to look up this library’s objects. The Microsoft ADO Ext. The Microsoft Jet and Replication Objects 2.0 for DDL and Security library (ADOX).5. This library is stored in MSJRO. and methods in the Object Browser.dll and can be found in the C:\Program Files\Common Files\System\ado folder.Figure 16.6 library (JRO) Objects contained in this library.4. 6. shown in Figure 16. properties. are used in the replication of a database.

is shared between all Office 2013 applications. convert data.Figure 16. This library is stored in the VBE7. and read text files. perform mathematical and financial computations. This library. The Visual Basic for Applications object library (VBA) Objects contained in this library allow you to access your computer’s file system.6 library (JRO).dll file located in the C:\Program Files\Common Files\Microsoft Shared\VBA\VBA7. shown in Figure 16. The reference to this library is automatically set when you install Excel 2013. .5.1 folder. work with date and time functions. The Microsoft Jet and Replication Objects 2.6. interact with users.

. Setting Up References to Object Libraries To work with Microsoft Access 2013 objects.Figure 16. The Visual Basic for Applications object library (VBA). Please note files for the “Hands-On” project may be found on the companion CDROM.0 object library. begin by creating a reference to the Microsoft Access 15.6.

Save the file as C:\Excel2013_ByExample\Practice_Excel16. and ASP (ISBN: 978-1-936420-0-2-5) and Access 2007 Programming by Example with VBA.1 in the previous section). properties. XML. 2. XML. Close the References dialog box. Locate Microsoft Access 15. and ASP (ISBN: 1-59822-042-X) Advantages of Creating a Reference to a Microsoft Access Object Library When you set a reference to the Microsoft Access object library. Start Microsoft Excel and open a new workbook. Use the References dialog box to set up references to other object libraries that will be accessed in this chapter’s exercises.1. including those of mine: Access 2010 Programming by Example with VBA. and methods in the Object Browser. You will find the list of libraries at the beginning of this chapter.Hands-On 16.xlsm. This dialog displays a list of all the type libraries that are available on your computer based on the applications you have installed. and choose Tools | References to open the References dialog box. Once you’ve created a reference to the Microsoft Access type library. If you are interested in database replication. Activate the Visual Basic Editor window. you can use the Object Browser to view a list of the application’s objects. properties. and methods (see Figure 16. as it will not be used here. 5. . there are many books on Microsoft Access VBA programming that cover this subject.6 library (JRO). Establishing a Reference to the Access Object Library 1. 4. 3. You can skip setting up the reference to the Microsoft Jet and Replication Objects 2.0 Object Library in the list of entries and select its checkbox. you gain the following: You can look up Microsoft Access objects.

You can use Microsoft Access built-in constants in your VBA code.Application (early binding) is faster than declaring it as Dim objAccess As Object (late binding).You can run Microsoft Access functions directly in your VBA procedures. you must take the following steps: 1. Declaring the object variable as Dim objAccess As Access. you need to open it. Your VBA procedure will run faster. (Refer to the section . Set a reference to the Microsoft Access 15. Using Automation to Connect to an Access Database When working with Microsoft Access from Excel (or another application) using Automation. How you open a particular database depends largely on which method you selected to establish a database connection. Each method is discussed in detail as it first appears in the procedure (see the next section titled “Opening an Access Database”). CONNECTING TO ACCESS The example procedures in this chapter use various methods of connecting to Microsoft Access. You can declare the object variable of the Application type instead of the generic Object type. You can establish a connection to Microsoft Access by using one of the following three methods: Automation Data Access Objects (DAO) ActiveX Data Objects (ADO) OPENING AN ACCESS DATABASE In order to access data in a database.0 object library.

) 2. Declare an object variable to represent the Microsoft Access Application object: Dim objAccess As Access. Dim objAccess As Object Set objAccess = GetObject(.accdb") Arguments of the GetObject Function The first argument of the GetObject function.15") or Set objAccess = GetObject("C:\Excel2013_HandsOn\" & _ "Northwind 2007. or the New keyword as demonstrated below. pathname. Notice that you must assign the reference to the object variable with the Set statement.Application. objAccess is the name of the object variable. GetObject function. Return the reference to the Application object using the CreateObject function.Application In the declaration line above.15") Use the GetObject function to return a reference to the Application object to use the current instance of Microsoft Access or to start Microsoft Access and have it load a file. It is . a new instance is started and the specified object is created.Application. Return the reference to the Application object and assign that reference to the object variable. 3. Use the CreateObject function to return a reference to the Application object when there is no current instance of the object.Application qualifies the object variable with the name of the Visual Basic object library that supplies the object. and Access."Access.titled “Setting up References to Object Libraries” earlier in this chapter. If Microsoft Access is already running. Dim objAccess As Object Set objAccess = CreateObject("Access. is optional.

a reference to an existing instance of the Microsoft Access application class is returned. Dim objAccess As New Access.Application Using the New Keyword When you declare the object variable with the New keyword. Dim objAccess As Object Set objAccess = GetObject("C:\Excel2013_HandsOn\" & _ "Northwind 2007.Application. The second argument. When the first argument is optional and the second argument is required. "Access. a new instance of the Microsoft Access application is activated or created with the specific database. all in one step. which gives more control over the object: Dim objAccess As Access.Application Set objAccess = New Access. as shown below: Dim objAccess As Object Set objAccess = GetObject(. return a reference to the Application object. the Access application does not start until you begin working with the object variable in your VBA code.used when you want to work with an object in a specific file. specifies which application creates the object and what type of object it is. When you use the New keyword to declare the Application object variable.accdb") When the first argument of the GetObject function is the name of a database file. class.14") Because the first argument (pathname) of the GetObject function is omitted. Use the New keyword to declare an object variable.Application It is also possible to declare an object variable using the two-step method. you must place a comma in the position of the first argument. a . and assign the reference to the object variable.

Now that you know how to create an object variable that represents the Application object. Hands-On 16. Switch to the Visual Basic Editor window and rename VBAProject (Practice_Excel16. Opening an Access Database Using Automation This Hands-On requires that you establish a reference to the Microsoft Access 15 object library (see Hands-On 16. include the version number in the argument of the GetObject or CreateObject function. Using the New keyword to create a new instance of the Application object is faster than using the CreateObject function. .xlsm) to AccessFromExcel. let’s take a look at an example procedure that opens an Access database straight from an Excel VBA procedure.1). You can close the Microsoft Access database that you opened through Automation by using the CloseCurrentDatabase method. Because you may have more than one version of Microsoft Access installed. 1. you can open a database or create a new database with the help of OpenCurrentDatabase. The seven most recent versions of Microsoft Access are shown below: Once you’ve created a new instance of the Application class by using one of the methods outlined in Step 3 above.new instance of Microsoft Access is created automatically and you don’t need to use the CreateObject function.2.

Application End If strPath = "C:\Excel2013_HandsOn\Northwind 2007.Visible = True . 3.15") If objAccess Is Nothing Then ' Get a reference to the Access Application object Set objAccess = New Access. enter the AccessViaAutomation procedure as shown below: Sub AccessViaAutomation() Dim objAccess As Access. acViewNormal.DoCmd. acReadOnly If MsgBox("Do you want to make the Access " & vbCrLf _ & "Application visible?".OpenCurrentDatabase strPath . " Access. In the Automation module Code window. _ "Display Access") = vbYes Then . vbYesNo.2.accdb" ' Open the Employees table in the Northwind database With objAccess .Application.Application Dim strPath As String On Error Resume Next Set objAccess = GetObject(. Insert a new module into the AccessFromExcel project and rename it Automation.OpenTable "Employees".

This particular example uses the New keyword to start a new instance of Access.MsgBox "Notice the Access Application icon " _ & "now appears on the Windows taskbar. As mentioned earlier.CloseCurrentDatabase ." End If ' Close the database and quit Access . we issue a command to open the Employees table in read-only mode. you can use the CreateObject function to start a new instance of an automation server. Therefore. as illustrated below: Set objAccess Access. you can trap this error.Quit End With Set objAccess = Nothing End Sub This procedure uses a current instance of Access if it is available. a new instance of Access will be started. " If objAccess Is Nothing Then Set objAccess Access. If Access isn’t running. a runtime error will occur and the object variable will be set to Nothing.15") = End If Once Access is opened and the Northwind database is loaded with the OpenCurrentDatabase method. the Northwind database is closed with the CloseCurrentDatabase . If the user selects Yes to this prompt. " CreateObject(. the Visible property of the Access Application object is set to True and the user is prompted to look for the Access icon on the taskbar.Application.Application. After selecting OK in response to the message. By placing the On Error Resume Next statement inside this procedure. if Access isn’t running.15") = GetObject(. The procedure then asks the user whether to make the Access application window visible. instead of creating a new object instance with the New keyword.

(See Chapter 1 for more information on trusted locations.Database Dim strDb As String strDb = "C:\Excel2013_HandsOn\Med. You should also replace the name of the database file with your own Access database that you have previously secured with password “test. You can prevent an instance of Microsoft Access from closing by making an object variable a module-level variable rather than declaring it at the procedure level. you must set up a reference to the Microsoft DAO 3. automatically disables all potentially harmful database content. After closing the object. At the top of the Access window just below the Ribbon you should see a familiar security warning message. Be sure to check the Access interface before running the statement that closes Access. click the Options button and then select the Enable this content option button.) Opening a Secured Microsoft Access Database If the Access database is secured with a password. You must use Data Access Objects (DAO) or ActiveX Data Objects (ADO) to programmatically open a password-protected Microsoft Access database.6 object library. Access 2013. the object variable is set to the Nothing keyword to free the memory resources used by the variable. the connection to the database will remain open until you close the Automation controller (Excel) or use the Quit method in your VBA code. The following example uses the DBEngine property of the Microsoft Access object to specify the password of the database. Run the above procedure by stepping through its code with the F8 key. To let Microsoft Access know that you trust the database. the user will be prompted to enter the correct password.mdb" . like Excel 2013. choose File | Options | Trust Center and then proceed to designate the C:\Excel2013_HandsOn folder as a trusted location. 4.Application Dim db As DAO. as explained in the beginning of this chapter. Under these circumstances.” Sub OpenSecuredDB() Static objAccess As Access.method and the Access Application object is closed with the Quit method. To permanently trust the Northwind 2007 database for this chapter’s exercises. For this procedure to work.

Set objAccess = New Access.PWD=test") With objAccess . 2. _ ReadOnly:=False.OpenDatabase(Name:=strDb. _ Options:=False. _ Connect:=".Visible = True . In the Examples_DAO module Code window.OpenCurrentDatabase strDb End With db.6 object library in the References dialog box (see the section titled “Setting up References to Object Libraries” earlier in this chapter). The example procedure shown below uses the OpenDatabase method of the DBEngine object to open the Northwind database and then proceeds to read the names of its tables.Close Set db = Nothing End Sub Using DAO to Connect to an Access Database To connect to a Microsoft Access database using Data Access Objects (DAO).3. enter the DAO_OpenDatabase procedure as shown below: Sub DAO_OpenDatabase(strDbPathName As String) . you must first set up a reference to the Microsoft DAO 3. Hands-On 16.DBEngine. Insert a new module into the AccessFromExcel VBA project and rename it Examples_DAO.Application Set db = objAccess. Opening an Access Database with DAO 1.

Close Set db = Nothing MsgBox "The database has been closed. You can open a file in the . Finally.Dim db As DAO. A TableDefs collection contains all stored TableDef objects in a Microsoft Access database.OpenDatabase(strDbPathName) MsgBox "There are " & db.Name Next db. Once the database is open. To run the DAO_OpenDatabase procedure. and open a database file. the DAO_OpenDatabase procedure retrieves the total number of tables from the TableDefs collection.mdb" Notice that when the procedure finishes. reading the names of tables and printing them out to the Immediate window.accdb" DAO_OpenDatabase "C:\Excel2013_HandsOn\Northwind.TableDefs Debug.TableDefs. All these operations occur behind the scenes." For Each tbl In db. type either of the following statements in the Immediate window and press Enter: DAO_OpenDatabase "C:\Excel2013_HandsOn\Northwind 2007. the Immediate window contains the list of all the database tables. notice that the Access application window is not visible to the user. the procedure uses the Close method to close the database file." & vbCrLf & _ " View the names in the Immediate window.Database Dim tbl As Variant Set db = DBEngine. 3.Print tbl.accdb or an older .Count & _ " tables in " & strDbPathName & ". Next. the procedure iterates through the TableDefs collection. ." End Sub The DBEngine object allows you to initialize the standard Access database engine known as Jet/ACE.mdb Microsoft Access file format.

The example procedure ADO_OpenDatabase connects to the Northwind database using the Connection object.4.Field Dim iCol As Integer Dim wks As Worksheet ' connect with the database If Right(strDbPathName.Jet. In the Examples_ADO module Code window.Using ADO to Connect to an Access Database Another method of establishing a connection with an Access database is using ActiveX Data Objects (ADO)." _ & "Data Source=" & strDbPathName ElseIf Right(strDbPathName.Open _ "Provider=Microsoft. enter the ADO_OpenDatabase procedure as shown below: Sub ADO_OpenDatabase(strDbPathName) Dim con As New ADODB. 2. 5) = "accdb" Then con.OLEDB.OLEDB.12. Opening an Access Database with ADO 1.1 library or a lower version.Connection Dim rst As New ADODB. Hands-On 16. You must begin by setting up a reference to the Microsoft ActiveX Data Objects 6.ACE." _ .4.0.0.Recordset Dim fld As ADODB. 3) = "mdb" Then con.Open _ "Provider = Microsoft. Insert a new module into the AccessFromExcel VBA project and rename it Examples_ADO.

CopyFromRecordset rst 'autofit the columns to make the data fit wks.Cells(1.count .Open "SELECT * FROM Employees " & _ "WHERE City = 'Redmond’".& "Data Source=" & strDbPathName Else MsgBox "Incorrect filename extension" Exit Sub End If ' open Recordset based on the SQL statement rst.Range("A2").Sheets(1) wks.Fields.Value = rst. _ adOpenForwardOnly.Activate 'write column names to the first worksheet row For iCol = 0 To rst.1 wks.Fields(iCol).Add Set wks = ActiveWorkbook.Name Next 'copy records to the worksheet wks. iCol + 1).AutoFit 'release object variables . adLockReadOnly ' enter data into an Excel worksheet in a new workbook Workbooks.Columns. con.

it’s the full name of the database file you want to open).OLEDB. The adOpenForwardOnly constant tells VBA to create the forward-only recordset. The source of records can be the name of a database table. the procedure. After establishing a connection to the Northwind database.Close ' destroy object variables to reclaim the resources Set rst = Nothing Set con = Nothing End Sub In the above procedure. The Recordset object is made up of records (rows) and fields (columns). After specifying the source of records.Jet.Close con. Next. a query. the Close method closes the recordset and another Close method is used to close the connection with the Access database. . one of which defines the type of cursor (adOpenForwardOnly) and the other the lock type (adLockReadOnly).12.Set wks = Nothing ' close the Recordset and connection with Access rst. it’s Microsoft.0 for databases in the Access 2013 .0 for Access databases in the . you also need to indicate the connection with the database (con) and two constants. Recordset objects are used to manipulate data at the record level. To obtain a set of records. The second constant.mdb file format and Microsoft. adLockReadOnly. you can use the Recordset object to access its data. The Open method requires a connection string argument that contains the name of the data provider (in this example.4. After obtaining the data. you need to use the Open method and specify information such as the source of records for the recordset.OLEDB.accdb file format) and the data source name (in this example. we open the Access database via the Open method. or the SQL statement that returns records.ACE. iterates through the entire recordset and its Fields collection to print the contents of all the fields to an Excel worksheet. the records are read-only. which scrolls forward in the returned set of records. specifies the type of the lock placed on records during editing. which means that you cannot alter the data.

accdb" ADO_OpenDatabase "C:\ Excel2013_HandsOn\Northwind. Hands-On 16. This section demonstrates in particular how to use VBA code to: Create a new Access database Open an existing database form Create a new database form Open a database report Run an Access function Creating a New Access Database with DAO If you want to programmatically transfer Excel data into a new Access database. The following example procedure demonstrates how this is done using Data Access Objects (DAO).3. Creating a New Access Database . To run the ADO_OpenDatabase procedure.5. PERFORMING ACCESS TASKS FROM EXCEL After connecting to Microsoft Access from Excel you can perform different tasks within the Access application. type either of the following statements in the Immediate window and press Enter: ADO_OpenDatabase "C:\Excel2013_HandsOn\Northwind 2007.mdb" 4. Activate the Microsoft Excel application window to view the worksheet with the procedure results. you may need to create a database from scratch by using VBA code.

dbText.CreateField("StateCapital".mdb" strTbl = "tblStates" ' Create a new database named ExcelDump Set db = CreateDatabase(strDb. 2) .CreateField("StateID". In the Examples_DAO module Code window.CreateField("StateName". 25) .Fields.Fields.1.Database Dim tbl As DAO. dbText. 25) End With ' Append the new tbl object to the TableDefs .TableDef Dim strDb As String Dim strTbl As String On Error GoTo Error_CreateDb_DAO strDb = "C:\Excel2013_ByExample\ExcelDump. dbLangGeneral) ' Create a new table named tblStates Set tbl = db. dbText. enter the NewDB_DAO procedure as shown below: Sub NewDB_DAO() Dim db As DAO.Append .Fields.CreateTableDef(strTbl) ' Create fields and append them to the Fields collection With tbl .Append .Append .

Number & ": " & Err.Close Set db = Nothing MsgBox "There is a new database on your hard disk.Append tbl ' Close the database db. the fields must be created and appended to the table. 25.Number = 3204 Then ' Delete the database file if it ' already exists Kill strDb Resume Else MsgBox Err. The CreateTableDef method of the Database object is then used to create a table named tblStates. " _ & Chr(13) & "This database file contains a table " _ & "named " & strTbl & ". Before a table can be added to a database." Exit_CreateDb_DAO: Exit Sub Error_CreateDb_DAO: If Err.mdb. As each field is created.db. it is appended to the Fields collection of the TableDef object using the Append method. .TableDefs. and 25 characters each. The procedure creates three text fields (dbText) that can store 2.Description Resume Exit_CreateDb_DAO End If End Sub T he CreateDatabase method is used to create a new database named ExcelDump.

open the table named tblStates. The following example uses Automation to connect to Access. Figure 16.mdb file. the table itself is added to the database with the Append method.Once the fields have been created and appended to the table. Launch Microsoft Access and open the ExcelDump. Because the database file may already exist in the specified location. Opening an Access Form You can open a Microsoft Access form from Microsoft Excel.7. Because other errors could occur. Next. the Else clause includes statements that will display the error and its description and allow an exit from the procedure.6. the procedure includes the error-handling routine that will delete the existing file so the database creation process can go on. Close the Access application.7. 4. Hands-On 16. The result of this procedure is shown in Figure 16. Opening an Access Form from a VBA Procedure . 2. You can also create a new form. Run the NewDB_DAO procedure. This Microsoft Access database table was created by an Excel VBA procedure. 3.

enter the following module-level declaration and the DisplayAccessForm procedure as shown below: Dim objAccess As Access.Application object variable (objAccess) is declared at the top of the module.DoCmd. 2. 3.Visible = True End With End Sub In the above procedure.8 shows the Customers form after it’s been opened.Application With objAccess .Application Sub DisplayAccessForm() Dim strDb As String Dim strFrm As String strDb = "C:\Excel2013_HandsOn\Northwind.mdb" strFrm = "Customers" Set objAccess = New Access. Insert a new module into the AccessFromExcel VBA project and rename it Database_Forms. Switch to the Microsoft Excel application window and press Alt+F8 to display the Macro dialog box. Highlight the DisplayAccessForm macro name and click Run. Notice that the Access. the OpenCurrentDatabase method is used to open the sample Northwind database. use the acDesign constant.Restore .1. The Restore method of the DoCmd object ensures that the form is displayed on the screen in a window and not minimized.OpenForm strFrm. To display the form in design view. The Customers form is opened in normal view (acNormal) with the OpenForm method of the DoCmd object. . In the Database_Forms module Code window.OpenCurrentDatabase strDb . Figure 16. For this procedure to work correctly. The Visible property of the Access Application object (objAccess) must be set to True for the form to become visible.DoCmd. you must set up a reference to the Microsoft Access object library. acNormal .

Hands-On 16. 4. A Microsoft Access form can be opened using an Excel VBA procedure. Opening an Access Report 1.8. 2. Opening an Access Report You can open a Microsoft Access report from Microsoft Excel. Close the Customer Details form and exit Microsoft Access.7. In the Database_Reports module Code window. enter the module-level declaration and the DisplayAccessReport procedure as shown below: . Insert a new module into the AccessFromExcel VBA project and rename it Database_Reports. The following procedure demonstrates how you can display an existing Access report straight from Excel.Figure 16.

Notice that the Access.Application object variable (objAccess) is declared at the top of the module. Switch to the Microsoft Excel application window and press Alt+F8 to display the Macro dialog box.OpenCurrentDatabase (strDb) . . the OpenCurrentDatabase method is used to open the sample Northwind database.mdb" strRpt = "Products by Category" Set objAccess = New Access. 3.9 shows the Products by Category report after it’s been opened and displayed in print preview mode. acViewPreview . Highlight the DisplayAccessReport macro name and click Run.Application Sub DisplayAccessReport() Dim strDb As String Dim strRpt As String strDb = "C:\Excel2013_HandsOn\Northwind.Visible = True End With End Sub In this procedure. Figure 16.DoCmd. For this procedure to work correctly.Application With objAccess .DoCmd. you must set up a reference to the Microsoft Access object library.Maximize . The Maximize method of the DoCmd object ensures that the form is displayed on the screen in a fullsize window.OpenReport strRpt. The Products by Category report is opened in print preview mode with the OpenReport method of the DoCmd object.Dim objAccess As Access.

The example procedure below is more versatile. Notice that this procedure takes two string arguments: the name of the Access database and the name of the report.9. A Microsoft Access report can be opened using an Excel VBA procedure. 4. strRpt As String) Set objAccess = New Access. as it allows you to display any Access report in any Access database.Application With objAccess .Application Sub DisplayAccessReport2(strDb As String. Close the Print Preview window and exit Microsoft Access. Make sure that the following declaration is present at the top of the module: Dim objAccess As Access.Figure 16.

OpenReport strRpt.Maximize .DoCmd.. "Invoice") Running the DisplayAccessReport2 procedure from a subroutine: ' Enter the following procedure in the Code window and run it Sub ShowReport() Dim strDb As String Dim strRpt As String strDb = InputBox("Enter the name of the database " & _ "(full path): ") strRpt = InputBox("Enter the name of the report:") Call DisplayAccessReport2(strDb. as shown below: Running the DisplayAccessReport2 procedure from the Immediate window: ' type the following statement on one line ' in the Immediate window and press Enter Call DisplayAccessReport2("C:\Excel2013_HandsOn\ Northwind.Visible = True End With End Sub You can run the DisplayAccessReport2 procedure from the Immediate window or from a subroutine. acViewPreview .OpenCurrentDatabase (strDb) .mdb". strRpt) End Sub Creating a New Access Database with ADO .DoCmd.

Creating a New Access Database with ADO 1. Notice that we created an Access 2013 database. Creating a new Access database from a VBA procedure is also possible and just as easy by using ActiveX Data Objects (ADO).Catalog Set cat = New ADOX. 3. views. make sure you change the Provider string and the filename.mdb by using Data Access Objects (DAO).accdb.5. we will create an Access database named ExcelDump2." & _ "Data Source=C:\Excel2013_ByExample\ExcelDump2. 4. To create a database file in the .0.accdb. choose Tools | References and ensure that the Microsoft ADO Ext. fields. Hands-On 16.OLEDB.Catalog cat. In the following Hands-On. 6.0 for DDL and Security Library is selected. In the Examples_ADO module’s Code window. The Catalog object represents the entire database. This object contains such database elements as tables. enter the CreateDB_ViaADO procedure as shown below: Sub CreateDB_ViaADO() Dim cat As ADOX." Set cat = Nothing End Sub The above procedure uses the ADOX Catalog object’s Create method to create a new Access database.In Hands-On 16.8. indexes. All you need is the Catalog object of the ADOX object library and its Create method. and stored procedures. 2. In the Visual Basic Editor window.12. Click OK to exit the References dialog box. Run the CreateDB_ViaADO procedure and switch to Windows Explorer to .ACE. you created a new database called ExcelDump.Create "Provider=Microsoft.mdb format.

Click OK to exit the References dialog box. Hands-On 16. Let’s work with a procedure that executes an Access select query.check out the database file that this procedure has created.1 and Microsoft ADO Ext.0 for DDL and Security libraries are selected.Recordset Dim i As Integer Dim strPath As String strPath = "C:\Excel2013_HandsOn\Northwind. 3.Catalog cat. In the Database_Queries module Code window.Catalog Dim cmd As ADODB. To place the data returned by the query into an Excel worksheet. 6. 2.mdb" Set cat = New ADOX. Choose Tools | References and ensure that the Microsoft ActiveX Data Objects 6. You can run these queries easily from within an Excel VBA procedure.ActiveConnection = _ . use the CopyFromRecordset method of the Range object.9. Running an Access Select Query 1. Running a Select Query The most popular types of queries that are executed in the Access user interface are select and parameter queries. 4.Command Dim rst As ADODB. enter the RunAccessQuery procedure as shown below: Sub RunAccessQuery(strQryName As String) Dim cat As ADOX. Insert a new module into the AccessFromExcel VBA project and rename it Database_Queries.

Name Next With ActiveSheet .1 Cells(1.4.Font.Columns.OLEDB."Provider=Microsoft.Value = rst.Close Set cmd = Nothing Set cat = Nothing End Sub The example procedure RunAccessQuery begins by creating an object variable that points to the Catalog object.Jet. rst.Fields.ActiveConnection = "Provider=Microsoft.Range("A2").CopyFromRecordset rst .Execute Sheets.Add Sheets(2).Fields(i).CurrentRegion.Select For i = 0 To rst.4." & _ "Data Source=" & strPath .Fields.Bold = True .Catalog cat.Command Set rst = cmd.AutoFit rst. i + 1)." & _ "Data Source=" & strPath Set cmd = cat. Next the ActiveConnection property of the Catalog object defines the method of establishing the connection to the database: Set cat = New ADOX.Jet.0.Views(strQryName).OLEDB.0. _ Cells(1.Range(Cells(1. 1).count .Select End With Selection.Range("A1").count)).

After creating the set of records. This procedure attempts to access a specific query in a database whose name will be supplied at runtime. After gaining access to the required query in the database. The returned set of records is then assigned to the object variable of the type Recordset using the Set keyword. . To run the above procedure.Views(strQryName).Command The Views collection.The Command object in the ADODB object library specifies the command that you want to execute in order to obtain data from the data source. 5. you can run the query in the following way: Set rst = cmd. contains all View objects of a specific catalog. type the following statement in the Immediate window and press Enter: RunAccessQuery("Current Product List") 6. these records are placed in an Excel worksheet using the CopyFromRecordset method (this method is discussed in more detail later in this chapter). an SQL statement. Set cmd = cat. which is a part of the ADOX object library. Switch to the Microsoft Excel application window to view the results obtained by executing the RunAccessQuery procedure in Sheet 2.10. or a stored procedure. A view is a filtered set of records or a virtual table created from other tables or views. as shown in Figure 16.Execute The Execute method of the Command object allows you to activate a specific query.

The results of running an Access query from an Excel VBA procedure are placed in a worksheet. This section demonstrates how you can run a . Running a Parameter Query When you want to obtain a different set of data based on the provided criteria.Figure 16. you will want to utilize parameter queries.10.

Command Dim rst As ADODB.Recordset Dim i As Integer Dim strPath As String Dim StartDate As String Dim EndDate As String strPath = "C:\Excel2013_HandsOn\Northwind." & _ "Data Source=" & strPath Set cmd = cat.4.Jet.Catalog Dim cmd As ADODB.mdb" StartDate = "7/1/96" EndDate = "7/31/96" Set cat = New ADOX. Let’s write a procedure to run the Employee Sales by Country query and retrieve records for the period beginning 7/1/96 and ending 7/31/96.Parameters("[Ending Date]") = EndDate . enter the RunAccessParamQuery procedure as shown below: Sub RunAccessParamQuery() Dim cat As ADOX. Running an Access Parameter Query 1. Hands-On 16.Command cmd.OLEDB.Parameters("[Beginning Date]") = StartDate cmd.Microsoft Access parameter query and place the resulting data in a Microsoft Excel worksheet.Catalog cat.0.Procedures("Employee Sales by Country"). In the Database_Queries module Code window.ActiveConnection = "Provider=Microsoft.10.

Range("A1").CopyFromRecordset rst .Columns.Select End With Selection.Command Because the Microsoft Access Employee Sales by Country query requires two parameters that define the beginning and ending dates. Cells(1.Range("A2"). i + 1).Font.Fields.Set rst = cmd.Close Set cmd = Nothing Set cat = Nothing End Sub To run parameter queries in the Microsoft Access database. the query is executed using the following statement: Set rst = cmd.Value = rst.Fields. rst.Procedures("Employee Sales by Country").Execute Sheets.Name Next With ActiveSheet .Parameters("[Beginning Date]") = StartDate cmd. 1).Fields(i). you need to access the Command object of the Procedures collection of the ADOX Catalog object: Set cmd = cat.count .1 Cells(1.AutoFit rst.CurrentRegion. you need to define these parameters by using the Parameters collection of the Command object: cmd.Bold = True .Range(Cells(1.Add For i = 0 To rst.Parameters("[Ending Date]") = EndDate After setting up the parameters.Execute .count)) _ .

The set of records returned by this query is assigned to the object variable of type Recordset and then copied to a worksheet using the CopyFromRecordset method (this method is discussed in more detail later in this chapter). Calling an Access Function You can run a built-in Microsoft Access function from Microsoft Excel through Automation. create a new one If objAccess Is Nothing Then Set objAccess = CreateObject("Access.000 Spanish pesetas to Euro dollars. On your own. The following example procedure calls the EuroConvert function to convert 1. 2. The EuroConvert function uses fixed conversion rates established by the European Union. "ESP". "EUR") & _ " euro dollars. Because the parameter values are hardcoded in the procedure.EuroConvert(1000. Run the above procedure. you are not prompted for input. Switch to the Excel application window to view the results obtained by executing the RunAccessParamQuery procedure.Application") End If MsgBox "For 1000 Spanish pesetas you will get " & _ objAccess. modify the RunAccessParamQuery procedure so that you can provide the parameter values at runtime. Sub RunAccessFunction() Dim objAccess As Object On Error Resume Next Set objAccess = GetObject(. " Set objAccess = Nothing .Application") ' if no instance of Access is open. 3. "Access.

Refer to the instructions on setting up a reference to object libraries earlier in this chapter. Record and field numbering begins with 0. The following example demonstrates how to use the GetRows method in a VBA procedure. Hands-On 16. We will run the Invoices query in the Northwind database and return records to a worksheet. This section shows you different techniques of putting Microsoft Access data into an Excel worksheet. you must first establish a reference to the Microsoft DAO 3. and the second subscript is the number representing the record. Retrieving Access Data Using the GetRows Method .End Sub RETRIEVING ACCESS DATA INTO AN EXCEL WORKSHEET There are numerous ways of bringing external data into Excel. For this procedure to work correctly.6 object library. While you have worked with some of these methods earlier in this book.11. you can use the GetRows method. the following sections discuss these methods in greater detail: Using the GetRows method Using the CopyFromRecordset method Using the TransferSpreadsheet method Using the OpenDatabase method Creating a text file Creating a query table Creating an embedded chart from Access data Retrieving Data with the GetRows Method To place Microsoft Access data into an Excel spreadsheet. This method returns a two-dimensional array where the first subscript is a number representing the field.

OpenRecordset rst.MoveLast countR = rst.1.RecordCount a = InputBox("This recordset contains " & _ .mdb" strShtName = "Returned records" Set db = OpenDatabase(strPath) Set qdf = db.QueryDef Dim rst As DAO.Database Dim qdf As DAO.Recordset Dim recArray As Variant Dim i As Integer Dim j As Integer Dim strPath As String Dim a As Variant Dim countR As Long Dim strShtName As String strPath = "C:\Excel2013_HandsOn\Northwind. 4.QueryDefs("Invoices") Set rst = qdf. Click OK to exit the References dialog box. 2. In the Method_GetRows module Code window. Choose Tools | References and ensure that Microsoft DAO 3. 3. Insert a new module into the AccessFromExcel VBA project and rename it Method_GetRows. enter the GetData_withGetRows procedure as shown below: Sub GetData_withGetRows() Dim db As DAO.6 Object Library is selected.

Close . j) = recArray(j.Fields(j). j) = rst.Clear recArray = rst. 1) .Name . i) Next j Next i For j = 0 To rst." & vbCrLf _ & "All records will be returned.Add ActiveWorkbook.GetRows(a) For i = 0 To UBound(recArray.Worksheets(1).EntireColumn. j).Offset(0. 2) For j = 0 To UBound(recArray." End If Workbooks.AutoFit Next j End With db.Offset(0.Name = strShtName rst.Range("A1") .countR & " records.1 .Fields.Offset(i + 1.count .CurrentRegion." & vbCrLf _ & "Enter number of records to return: ". _ "Get Number of Records") If a = "" Or a = 0 Then Exit Sub If a > countR Then a = countR MsgBox "The number you entered is too large.MoveFirst With Worksheets(strShtName).

Before retrieving records. If you enter a number that is greater than the record count. Notice that to obtain the correct record count. If you forget to do this.MoveLast countR = rst. the record pointer will remain on the last record and only one record will be retrieved. you must move the record pointer to the first record by using the MoveFirst method. You can cancel at this point by clicking the Cancel button in the input dialog box or you can type the number of records to retrieve. Next. as shown below: Set rst = qdf. When this is done.RecordCount The procedure then prompts the user to enter the number of records to return to the worksheet.6 object library. The records are first returned to the Variant variable containing a two-dimensional array by using the GetRows method of the Recordset object. the procedure will retrieve all the records.QueryDefs(“Invoices”) In the Microsoft DAO 3. the GetData_withGetRows procedure illustrated above runs the Invoices query using the following statement: Set qdf = db. another loop will fill in the first worksheet row with the names of fields and autofit each column so that the data is displayed correctly. the procedure places the records returned by the query in the object variable of type Recordset using the OpenRecordset method. while action queries allow you to modify data. the procedure loops through both dimensions of the array to place the records in the worksheet starting at cell A2. or delete records using action queries. (You can add. the QueryDefs object represents a select or action query. Select queries return data from one or more tables or queries. the record pointer must first be moved to the last record in the recordset by using the MoveLast method: rst.) After executing the query. The procedure then goes on to activate the Returned records worksheet and clear the current region.OpenRecordset Next. modify. .End Sub After opening an Access database with the OpenDatabase method. the record count is retrieved using the RecordCount method and placed in the countR variable.

The GetRows method can also be used with ActiveX Data Objects as demonstrated in the following GetData_withGetRows_ADO procedure." strShtName = "Returned records" Set cat = New ADOX.Catalog cat.Command Set rst = New ADODB. ensure that the References dialog box has the Microsoft ActiveX Data Objects 6.ACE.Open cmd. .Command Dim rst As ADODB.OLEDB. adLockReadOnly countR = rst.ActiveConnection = strConnect Set cmd = cat. If you want to try out this procedure. Next. Run the GetData_withGetRows procedure.12.accdb. 6." _ & "Data Source=C:\Excel2013_HandsOn\Northwind 2007.RecordCount . type 10 and click OK.Catalog Dim cmd As ADODB.Views("Order Summary").0.Recordset rst.0 for DDL and Security libraries checked.Recordset Dim strConnect As String Dim recArray As Variant Dim i As Integer Dim j As Integer Dim strPath As String Dim a As Variant Dim countR As Long Dim strShtName As String strConnect = "Provider=Microsoft. adOpenStatic. switch to the Microsoft Excel application window to view the results.1 and Microsoft ADO Ext. Sub GetData_withGetRows_ADO() Dim cat As ADOX.5. When prompted for the number of records.

a = InputBox("This recordset contains " & _ countR & " records. j) = recArray(j.Range("A1") .CurrentRegion. 2) For j = 0 To UBound(recArray.GetRows(a) For i = 0 To UBound(recArray.Offset(i + 1.count . i) Next j Next i For j = 0 To rst." End If Workbooks.Worksheets(1).Offset(0." & vbCrLf _ & "All records will be returned. 1) .AutoFit Next j End With .EntireColumn. j)." & vbCrLf _ & "Enter number of records to return: ".Offset(0.1 . j) = rst.MoveFirst With Worksheets(strShtName).Fields(j).Add ActiveWorkbook.Name = strShtName rst.Name .Fields. _ "Get Number of Records") If a = "" Or a = 0 Then Exit Sub If a > countR Then a = countR MsgBox "The number you entered is too large.Clear recArray = rst.

enter the GetProducts procedure as shown below. Insert a new module into the AccessFromExcel VBA project and rename it Method_CopyFromRecordset. The optional arguments. you must create a reference to the Microsoft ActiveX Data Objects 6. This method can take up to three arguments: Data.Set rst = Nothing Set cmd = Nothing Set cat = Nothing End Sub Retrieving Data with the CopyFromRecordset Method To retrieve an entire recordset into a worksheet. If you omit the MaxColumns argument. Only the first argument. If you omit the MaxRows argument. (Refer to the instructions on setting up a reference to object libraries earlier in this chapter. 2. and MaxColumns.) . Hands-On 16. all the fields will be retrieved. In the Method_CopyFromRecordset module Code window. MaxRows and MaxColumns.12. For this procedure to work correctly. allow you to specify the number of records (MaxRows) and the number of fields (MaxColumns) that should be returned. Data. MaxRows. all the returned records will be copied to the worksheet. use the CopyFromRecordset method of the Range object. Let’s try out a procedure that uses the ADO objects and the CopyFromRecordset method to retrieve all the records from the Northwind database Products table. This argument can be the Recordset object. Retrieving Access Data Using the CopyFromRecordset Method 1.1 library. is required.

Close Set rst = Nothing .CursorLocation = adUseClient ' Create a Recordset from all the records ' in the Products table Set rst = conn.Offset(0.1 . 0).Range("A1") .Execute(CommandText:="Products".mdb" conn.Offset(1.Close conn. j) = rst.4.CurrentRegion." _ & "Data Source=" & strPath & ".Recordset Dim strPath As String strPath = "C:\Excel2013_HandsOn\Northwind. _ Options:=adCmdTable) rst.MoveFirst ' transfer the data to Excel ' get the names of fields first With Worksheets("Sheet3").Open "Provider=Microsoft.CopyFromRecordset rst .Clear For j = 0 To rst.Columns.Connection Dim rst As ADODB." conn.OLEDB.Fields.Count .Jet.Sub GetProducts() Dim conn As New ADODB.Fields(j).CurrentRegion.Name Next j .AutoFit End With rst.0.

The Offset method causes the records to be entered in a spreadsheet.Set conn = Nothing End Sub The above procedure copies all the records from the Products table in the Northwind database into an Excel worksheet.CopyFromRecordset rst. you can also link the data in an Excel spreadsheet to the current Access database. 3.adp) and a spreadsheet file.Offset(1. range] T h e transfertype argument can be one of the following constants: . With a linked spreadsheet. Retrieving Data with the TransferSpreadsheet Method It is possible to use the TransferSpreadsheet action of the Microsoft Access DoCmd object to import or export data between the current Access database (. spreadsheettype]. use the MaxRows argument as follows: . Run the GetProducts procedure and switch to the Excel application window to view the results. 0). The TransferSpreadsheet method carries out the TransferSpreadsheet action in Visual Basic and has the following syntax: DoCmd. 2 The above statement tells Visual Basic to copy all the data from the first two columns. The comma between the rst and the number 2 is a placeholder for the omitted MaxRows argument. tablename.TransferSpreadsheet [transfertype][. 5 The above statement tells Visual Basic to copy only five records. .Offset(1. To send all the records to the worksheet using the data from only two table fields.mdb) or Access project (. Using this method. you can view and edit the spreadsheet data with Access while still allowing complete access to the data from your Excel spreadsheet application. hasfieldnames][. starting with the second spreadsheet row. If you want to copy fewer records. filename [.CopyFromRecordset rst. use the following statement: . 0).

The tablename argument is a string expression that specifies the name of the Access table you want to import spreadsheet data into.acImport (default setting).1. or link to. The default setting is False (no field names in the first row). These constants define whether data has to be imported. True indicates that the first worksheet row contains the field names.1. unless you need to specify the worksheet name. Spreadsheettype argument constants It is not difficult to guess that the spreadsheettype argument specifies the spreadsheet name and the version number. export spreadsheet data from. Leave this argument blank if you want to export. If you omit the range argument. The range argument is a string expression that specifies the range of cells or the name of the range in the worksheet. This argument applies only to importing. The filename argument is a string expression that specifies the filename and path of the spreadsheet you want to import from. The hasfieldnames argument is a logical value of True (–1) or False (0). Table 16. the entire spreadsheet will be imported. export to. The spreadsheettype argument can be one of the constants shown in Table 16. Instead of the table name. . False denotes that the first row contains normal data. or linked to the database. exported. acExport. or link spreadsheet data to. you may also specify the name of the select query whose results you want to export to a spreadsheet. or acLink.xls spreadsheet using the TransferSpreadsheet method. The ExportData example procedure shown below exports data from the Shippers table in the Northwind database to the Shippers.

DoCmd.Application") objAccess.13. In the Method_TransferSpreadsheet module Code window. The database is opened using the OpenCurrentDatabase method. _ Range:="Sheet1" objAccess. 2.Application Set objAccess = CreateObject("Access. Retrieving Access Data Using the TransferSpreadsheet Method 1. _ TableName:="Shippers". enter the ExportData procedure as shown below: Sub ExportData() Dim objAccess As Access.xls". The TransferSpreadsheet method of the DoCmd object is used to specify that the data from the Shippers table should be exported into an Excel .mdb" objAccess. _ Filename:="C:\Excel2013_ByExample\Shippers.TransferSpreadsheet _ TransferType:=acExport. Insert a new module into the AccessFromExcel VBA project and rename it Method_TransferSpreadsheet.OpenCurrentDatabase filepath:= _ "C:\Excel2013_HandsOn\Northwind.Hands-On 16. _ HasFieldNames:=True.Quit Set objAccess = Nothing End Sub The ExportData procedure uses Automation to establish a connection to Microsoft Access. _ SpreadsheetType:=acSpreadsheetTypeExcel12.

xls and placed in Sheet1 of this workbook. the OpenDatabase method is the easiest way to get database data into a Microsoft Excel spreadsheet. The following example procedure demonstrates how to open the Northwind database using the OpenDatabase method of the Workbooks collection. Switch to the Excel application window and choose View | Macros | View Macros. Table 16. requires that you specify the name of a database file that you want to open. a new workbook is opened with the worksheet showing data from the selected table or query. which applies to the workbooks. click OK. 3. Sub OpenAccessDatabase() On Error Resume Next Workbooks.xls file created by the ExportData procedure to view the retrieved data. In the Macros dialog box. listed in Table 16.2.11). 4. select the ExportData procedure and click Run. Using the OpenDatabase Method Introduced in Excel 2002. Excel will display a dialog box listing all the tables and queries in the database (see Figure 16. The first row of the worksheet is to be used by field headings. the Access application is closed and the object variable pointing to the Access application is destroyed.mdb" Exit Sub End Sub When you run the above procedure. The OpenDatabase method has four optional arguments.2. which you can use to further qualify the data that you want to retrieve.spreadsheet named Shippers. When asked to verify that the file is not corrupted or is from a trusted source. After making a selection from the list. This method. Optional arguments for the OpenDatabase method . When data is retrieved. Open the Shippers.OpenDatabase _ Filename:="C:\Excel2013_HandsOn\Northwind.

Figure 16. . Let’s write a procedure that creates a PivotTable report from the retrieved customer records.11. Database data stored in a table or query can be easily retrieved into an Excel workbook using the OpenDatabase method.

When you run the procedure. 2. _ CommandText:="Select * from Customers".OpenDatabase _ Filename:="C:\Excel2013_HandsOn\Northwind.Hands-On 16. _ BackgroundQuery:=True. Excel opens a new workbook and displays a PivotTable Field List window listing the fields that are available in the Customers table (see Figure 16. Retrieving Access Data into a PivotTable Using the OpenDatabase Method 1.mdb". .12). enter the Sub CountCustomersByCountry() On Error Resume Next Workbooks. _ ImportDataAs:=xlPivotTableReport Exit Sub End Sub 3. Switch to the Excel application window and choose View | Macros | View Macros. Insert a new module into the AccessFromExcel VBA project and rename it Method_OpenDatabase. In the Method_OpenDatabase module Code CountCustomersByCountry procedure as shown below: window.14. _ CommandType:=xlCmdSql. Select the CountCustomersByCountry procedure and click Run.

you can specify that the database data be retrieved into a specific format. Drag the Country and CustomerID fields from the PivotTable Fields and drop them in the Row Labels area. Using the OpenDatabase method’s optional arguments. .Figure 16. 4.12.13 displays the completed PivotTable report. such as a PivotTable report or a query table. Drag the CustomerID field and drop it in the Values area. Figure 16.

Text files are particularly useful for transferring large amounts of data to a spreadsheet. A PivotTable report based on the data retrieved from the Northwind database’s Customers table. Creating a Text File from Access Data You can create a comma. .or tab-delimited text file from Access data by using a VBA procedure in Excel. Close the workbook with the PivotTable report. 5.Figure 16. The example procedure below illustrates how you can create a tab-delimited text file from an ADO Recordset.13.

0. 2. you must create a reference to the Microsoft ActiveX Data Objects 6.OLEDB.mdb" conn.Jet.Recordset Dim strData As String Dim strHeader As String Dim strSQL As String Dim fld As Variant strPath = "C:\Excel2013_HandsOn\Northwind.Connection Dim rst As ADODB.Hands-On 16.Open "Provider=Microsoft. In the TextFiles module Code window." _ & "Data Source=" & strPath & ".15. _ . enter the CreateTextFile procedure as shown below.4. Creating a Text File from Access Data 1.CursorLocation = adUseClient strSQL = "SELECT * FROM Products WHERE UnitPrice > 50" Set rst = conn." conn. Insert a new module into the AccessFromExcel VBA project and rename it TextFiles.Execute(CommandText:=strSQL.1 library. For this procedure to work correctly. (Refer to the instructions on setting up a reference to object libraries earlier in this chapter.) Sub CreateTextFile() Dim strPath As String Dim conn As New ADODB.

NumRows.Name & vbTab Next Open "C:\Excel2013_ByExample\ProductsOver50. Use the adClipString constant for this argument. The second .txt" _ For Output As #1 Print #1. This method returns a set of records into a string and is faster than looping through the recordset. we retrieve the necessary records from the Access database using the GetString method of the Recordset object. strHeader Print #1.Close conn.GetString(StringFormat:=adClipString.Close Set rst = Nothing Set conn = Nothing End Sub Before the text file can be created.Fields strHeader = strHeader + fld. RowDelimeter:=vbCr. RowDelimiter. _ nullExpr:=vbNullString) For Each fld In rst. _ ColumnDelimiter. strData Close #1 rst.GetString(StringFormat. The GetString method has the following syntax: variant = recordset.Options:=adCmdText) ' save the recordset as a tab-delimited file strData = rst. _ ColumnDelimeter:=vbTab. NullExpr) The first argument (StringFormat) determines the format for representing the recordset as a string.

4. We store the names of fields in a separate String variable. the procedure creates a text file with the following statement: Open "C:\Excel2013_ByExample\ProductsOver50. Next.*) in the Files of type drop-down list. select All Files (*. The fifth argument (NullExpr) specifies an expression to represent NULL values (the default is an empty string— vbNullString). as it was discussed in detail in Chapter 14.txt file in the root directory of your C drive. the procedure loops through the fields in the recordset to retrieve the names of columns.txt: . Now let’s open the ProductsOver50.” you learned how to work with text files using the FileSystemObject. Now that the file has the data. Once we have all the data in a String variable.txt file. The procedure creates the ProductsOver50. In Chapter 13. Next. If blank. The fourth argument (RowDelimiter) specifies a row delimiter (the default is a carriage return—vbCr).argument (NumRows) specifies the number of recordset rows to return. Next. so if you need the data with the headings you need to get this info separately. Click Next to preview the structure of this file. The procedure below demonstrates how to use this object to create a text file named ProductsOver20. Click Finish to show the data in a worksheet. 3. In the Open dialog box. The third argument (ColumnDelimiter) specifies the delimiter for the columns within the row (the default is a tab— vbTab). The GetString method can only handle the data requests.txt" _ For Output As #1 You should already be familiar with this method of creating text files. The Text Import Wizard (Step 1 of 3) dialog box will open with the Delimited option button selected. Run the CreateTextFile procedure. GetString will return all the rows. “File and Folder Manipulation with Windows Script Host (WSH). select the ProductsOver50.txt file and click Open. we use the Print statement to write both the heading and the data string to the text file. we can close it with the Close statement.

Sub CreateTextFile2() Dim conn As New ADODB.accdb" conn.12. True) strPath = "C:\Excel2013_HandsOn\Northwind 2007.Recordset Dim strPath As String Dim strData As String Dim strHeader As String Dim strSQL As String Dim fso As Object Dim myFile As Object Dim fld As Variant Set fso = CreateObject("Scripting." conn.CursorLocation = adUseClient strSQL = "SELECT * FROM Products WHERE [List Price] > 20" Set rst = conn.OLEDB.0. _ nullExpr:=vbNullString) ." _ & "Data Source=" & strPath & ".CreateTextFile( _ "C:\Excel2013_ByExample\ProductsOver20. _ ColumnDelimeter:=vbTab.Open "Provider=Microsoft.ACE.GetString(StringFormat:=adClipString.FileSystemObject") Set myFile = fso. RowDelimeter:=vbCr.txt". Options:=adCmdText) ' save the recordset as a tab-delimited file strData = rst.Execute(CommandText:=strSQL.Connection Dim rst As ADODB.

Each QueryTable object represents a worksheet table built from data returned from an external data source. you can bring in data that fits your requirements exactly. SQL Server® database. By querying an external database. Thus. instead of bringing all product information into your spreadsheet for review. A query table is a special table in an Excel worksheet that is connected to an external data source. Web page. you may want to specify criteria that the data must meet prior to retrieval. To retrieve the most up-to-date information. This method requires three arguments that are explained in the following Hands-On exercise. Hands-On 16. you can retrieve only products with a unit price greater than $20. To create a query programmatically.Fields strHeader = strHeader + fld.16. you may want to create a query table.For Each fld In rst.WriteLine strHeader . such as an SQL Server or a Microsoft Access database. you can use the QueryTable object to access external data. Let’s see how you can use the QueryTable object programmatically. such as a Microsoft Access database.Close End With End Sub Creating a Query Table from Access Data If you want to work in Excel with data that comes from external data sources and you know that the data you’ll be working with often undergoes changes.Name & vbTab Next With myFile . For example. Creating a Query Table from Access Data . Microsoft Excel offers a special option for obtaining data from external data sources: Simply choose Data | From Other Sources | From Microsoft Query. or text file. In VBA. use the Add method of the QueryTables collection object. the user can easily refresh the query table. instead of bringing in all the products from an Access table.WriteLine strData .

Range("A1") Sheets(1)." _ & "Data Source=" & myDb & ".Add Set Dest = Worksheets(1). strSQL) With myQryTable . enter the CreateQueryTable procedure as shown below: Sub CreateQueryTable() Dim myQryTable As Object Dim myDb As String Dim strConn As String Dim Dest As Range Dim strSQL As String myDb = "C:\Excel2013_HandsOn\Northwind. _ Dest.Jet." Workbooks.Add(strConn.4.RefreshStyle = xlInsertEntireRows . In the QueryTable module Code window.mdb" strConn = "OLEDB.OLEDB. 2.Provider=Microsoft.Refresh False End With End Sub The CreateQueryTable procedure uses the following statement to create a query .QueryTables.Select strSQL = "SELECT * FROM Products WHERE UnitPrice > 20" Set myQryTable = ActiveSheet.1. Insert a new module into the AccessFromExcel VBA project and rename it QueryTable.0.

14). you should see a new workbook. _ strSQL) Dest. This is a required argument of the Variant data type that specifies the data source for the query table. strSQL is a variable that provides a value for the third argument—SQL. strConn is a variable that provides a value for the first argument of the QueryTables method—Connection. the query isn’t run until you call the Refresh method. xlInsertEntireRows—Entire rows are inserted to accommodate incoming data. The following constants can be used: xlOverwriteCells—Existing cells are overwritten with the incoming data. When you create a query using the Add method. This is an optional argument of the Variant data type that allows you to determine whether control should be returned to the procedure when a database connection has been established and the query has been submitted (True) or after the query has been run and all the data has been retrieved into the worksheet (False). Dest is a variable that provides a value for the second argument—Destination.table on the active sheet: Set myQryTable = ActiveSheet. The CreateQueryTable procedure only retrieves from the Northwind database’s Products table those products whose UnitPrice field is greater than 20. This is a required argument of the String data type that defines the data to be returned by the query. . When this procedure completes.QueryTables.Run the CreateQueryTable procedure. This method accepts one argument—BackgroundQuery. The RefreshStyle method determines how data is inserted into the worksheet. This is a required argument of the Range data type that specifies the cell where the resulting query table will be placed. Notice that the control is returned to the procedure only after all the relevant records have been fetched. The first sheet in this workbook will contain the data you specified in the query (see Figure 16. xlInsertDeleteCells—Cells are inserted or deleted to accommodate the incoming data.Add(strConn.

Creating an Embedded Chart from Access Data Using VBA. . Let’s spend some time now creating a procedure that fetches data from the Northwind database and creates an embedded chart.14. Insert a new module into the AccessFromExcel VBA project and rename it ChartingData. Hands-On 16. To modify the SQL statement for the query table. Creating an Embedded Chart from Access Data 1. right-click anywhere within the returned data and choose Edit Query. you can easily create a chart based on the data retrieved from a Microsoft Access database. Charts are created by using the Add method of the Charts collection.17.Figure 16.

enter the ChartData_ withADO procedure as shown below: Sub ChartData_withADO() Dim conn As New ADODB. j) = recArray(j." _ & "Data Source=C:\Excel2013_HandsOn\Northwind.Fields.2. i) Next j Next i For j = 0 To rst.4.Add Set mySheet = Worksheets("Sheet1") With mySheet.Open _ "Provider=Microsoft.Jet.Connection Dim rst As New ADODB. conn. adLockReadOnly Workbooks.Recordset Dim mySheet As Worksheet Dim recArray As Variant Dim strQueryName As String Dim i As Integer Dim j As Integer strQueryName = "Category Sales for 1997" ' Connect with the database conn.count .Open "SELECT * FROM [" & strQueryName & "]"." ' Open Recordset based on the SQL statement rst.Range("A1") recArray = rst. 1) .Offset(i + 1. 2) For j = 0 To UBound(recArray.mdb. In the ChartingData module Code window.GetRows() For i = 0 To UBound(recArray. _ adOpenForwardOnly.1 .0.OLEDB.

Name .HasTitle = True .AutoFit Next j End With rst.Location Where:=xlLocationAsObject.Axes(xlValue).HasTitle = True .Text = strQueryName .Characters. _ Name:=mySheet.Range("B1") .EntireColumn. j) = rst.Axes(xlCategory).Characters.AxisTitle.Name With ActiveChart . j)..Activate Charts.Offset(0.Close Set rst = Nothing Set conn = Nothing mySheet. 1).Fields(j).Cells(1.CurrentRegion.HasTitle = True .Axes(xlCategory). _ PlotBy:=xlRows ActiveChart.Add ActiveChart.Close conn. _ Characters.Offset(0.Axes(xlValue).SetSourceData _ Source:=mySheet.Text = "" .AxisTitle.Text = mySheet.ChartType = xl3DColumnClustered ActiveChart.ChartTitle.

The Name argument is required if Where is set to xlLocationAsObject. The SetSourceData method of the Chart object sets the source data range for the chart. _ Name:=mySheet.Location Where:=xlLocationAsObject. 1) . This method takes two arguments: Where and Name. Once the data is placed in an Excel worksheet. 3. PlotBy will cause the embedded chart to plot data by rows. Next. Run the ChartData_withADO procedure. the Location method of the Chart object specifies where the chart should be placed. As you already know from earlier examples in this chapter. the GetRows method retrieves data into a two-dimensional array.Cells(1. The resulting chart is shown in Figure 16.15. . The data rows are retrieved using the GetRows method of the Recordset object.Name Next.& "($)" . a group of statements formats the chart by setting various properties.CurrentRegion. You can use one of the following constants for this argument: xlLocationAsNewSheet. PlotBy:=xlRows Source is the range that contains the source data that we have just placed on the worksheet beginning at cell A1. like this: ActiveChart. the Location method specifies that the chart should be embedded in the active worksheet: ActiveChart.Orientation = xlUpward End With End Sub The above procedure uses ActiveX Data Objects (ADO) to retrieve data from an Access database query. or xlLocationAutomatic.Axes(xlValue).AxisTitle. In this procedure. The Where argument is required. xlLocationAsObject. a chart is added with the Add method.SetSourceData Source:=mySheet.

or an SQL statement. you can resort to a tedious manual method to have the data transferred. You can create an embedded chart programmatically with VBA based on the data retrieved from a Microsoft Access table. a query.15. Prior to moving your Excel data to Access. Once in a database format. The remaining sections of this chapter demonstrate how to link and import Excel worksheets to an Access database. or you can use your recently acquired VBA programming skills to automatically turn your worksheets into database tables. it is a . TRANSFERRING THE EXCEL WORKSHEET TO AN ACCESS DATABASE Many of the world’s biggest databases began as spreadsheets. the latter requires that you possess database application design skills). When the time comes to build a database application from your worksheet.Figure 16. your Excel data can be used in advanced company-wide reports or as a standalone application (needless to say.

Prepare the worksheet data as shown in Figure 16. and each column will function as a table field.16. (Refer to the “Retrieving Data with the TransferSpreadsheet Method” section earlier in this chapter for the details on working with this method. Hands-On 16. Insert a new sheet into the Practice_Excel16. If the first column of your data contains the field names. Linking an Excel Worksheet to an Access Database 1. If the data you want to transfer represents a large number of columns. you should print your data first and examine it so that there are no surprises later.18. Keep in mind that each worksheet row you’ll be transferring will become a record in a table. the first row of the worksheet range that you are planning to transfer to Access should contain field names.) The example procedure shown below links the worksheet shown in Figure 16. For this reason.xlsm workbook and rename it mySheet. The key to smooth data import is to make your spreadsheet look as close as possible to a database table. your data should be contiguous. .good idea to clean up your data as much as possible so that the transfer operation goes smoothly. it is recommended that you use the built-in Transpose feature to reposition your data so that the data goes down rather than from left to right. Linking an Excel Worksheet to an Access Database You can link an Excel spreadsheet to a Microsoft Access database by using the TransferSpreadsheet method.16 to the Northwind database. 2. There should be no gaps between the columns of data that you want to transfer. In other words.

In the ExcelToAccess module Code window. enter the LinkExcel_ToAccess procedure as shown below: Sub LinkExcel_ToAccess() Dim objAccess As Access.Path strBookName = strPath & "\Practice_Excel16. 4. Switch to the Visual Basic Editor screen and insert a new module into the AccessFromExcel VBA project.Application Dim strTableName As String Dim strBookName As String Dim strPath As String On Error Resume Next strPath = ActiveWorkbook. Rename this module ExcelToAccess.Figure 16.16. The LinkExcel_ToAccess VBA procedure links this worksheet to the Northwind database in Microsoft Access.xlsm" strTableName = "Linked_ExcelSheet" . 3.

When the procedure finishes execution. Notice that the True argument in the DoCmd statement indicates that the first row of the spreadsheet contains column headings. If you need to perform these operations. 5.xls file format. _ acSpreadsheetTypeExcel12Xml. _ strTableName. . open the Northwind 2007 database and take a look at the linked table. Run the LinkExcel_ToAccess procedure. make the required changes.DoCmd. change.OpenCurrentDatabase "C:\Excel2013_HandsOn\" & _ "Northwind 2007.Set objAccess = New Access. strBookName. "mySheet!A1:D7" .17.xls spreadsheet file. You cannot add. shown in Figure 16.Visible = True End With Set objAccess = Nothing End Sub After opening the Access database with the OpenCurrentDatabase method. or delete the data in Access tables that are linked to Excel workbooks in Access.TransferSpreadsheet acLink. True. and then export the data to Excel in the . the procedure uses the TransferSpreadsheet method of the Microsoft Access DoCmd object to create a linked table named Linked_ExcelSheet from the specified range of cells (A1:D7) located in the mySheet worksheet in the Practice_Excel16. you should import the Excel data to Access.accdb" .Application With objAccess .

simply modify the name. Importing your worksheet data is just as easy. you learned how to link your Excel worksheet to an Access database.17. change the table name.Figure 16.16 (see “Linking an Excel Worksheet to an Access Database”). The Microsoft Excel spreadsheet is linked to a Microsoft Access database. You can even use the same VBA procedure you used for linking with only minor changes. Placing Excel Data in an Access Table What if. . you wanted to create an Access table from scratch and load it with the data sitting in a worksheet? Using several programming techniques that you’ve already acquired in this book. Close the Linked_ExcelSheet table in Access and exit the application. replace the acLink constant with acImport. and you are done. you can easily accomplish this task. Let’s write a VBA procedure that dynamically creates an Access table based on the Excel worksheet presented in Figure 16. Importing an Excel Worksheet to an Access Database In the previous section. rather than linking or importing your Excel worksheet. 6.

mdb.ActiveConnection = conn Set myTbl = New ADOX.Hands-On 16.Append myTbl ' add fields (columns) to the table .Recordset Dim rowCount As Integer Dim i As Integer On Error GoTo ErrorHandler ' connect to Access using ADO Set conn = New ADODB.Table Dim rstAccess As ADODB.Connection Dim cat As ADOX.16).4.Table myTbl.Catalog Dim myTbl As ADOX.Connection conn.19." ' create an empty Access table Set cat = New Catalog cat. 1." & _ "Data Source = C:\Excel2013_HandsOn\Northwind.Tables.Open "Provider = Microsoft.OLEDB. enter the AccessTbl_From_ ExcelData procedure as shown below: Sub AccessTbl_From_ExcelData() Dim conn As ADODB.Jet. In the ExcelToAccess module Code window.18 (see Figure 16. Creating an Access Table and Populating It with the Worksheet Data This Hands-On requires the worksheet data prepared in Hands-On 16.0.Name = "TableFromExcel" cat.

Rows. adVarWChar. 20 End With Set cat = Nothing MsgBox "The table structure was created. adVarWChar.Open myTbl.LockType = adLockOptimistic .Name End With ' now transfer data from Excel worksheet range With Worksheets("mySheet") rowCount = Range("A2:D7").ActiveConnection = conn .Fields("School No") = Cells(i.With myTbl.Append "Manufacturer".AddNew ' add a new record to an Access table .Text . 7 .Append "School No"." ' open a recordset based on the newly created ' Access table Set rstAccess = New ADODB.Append "Serial Number".Columns .Value .Append "Equipment Type".Fields("Serial Number") = Cells(i. adVarWChar.count For i = 2 To rowCount + 1 With rstAccess . 1).CursorType = adOpenKeyset . . 2).Fields("Equipment Type") = Cells(i. 15 . 15 .Recordset With rstAccess . adVarWChar.

Close conn.Description Resume AccessTbl_From_ExcelDataExit End Sub Notice that this procedure connects to the Access database using ActiveX Data Objects (ADO)." ' close the Recordset and Connection object and remove them ' from memory rstAccess. Next." AccessTbl_From_ExcelDataExit: Exit Sub ErrorHandler: MsgBox Err. the procedure creates a new Access table by using the Catalog and Table objects from the ADOX object library.Value . the fields are added to the table based on the names of the worksheet columns. If the worksheet cell’s length is larger than the specified field size. 4).Fields("Manufacturer") = Cells(i. After the connection is established.Number & ": " & Err. Each text field specifies the maximum number of characters that it can accept.Close Set rstAccess = Nothing Set conn = Nothing MsgBox "Open the Northwind database to view the table.3).Update ' update the table record End With Next i End With MsgBox "Data from an Excel worksheet was loaded into the table.Value . the error-handling routine will display the Access built-in message .

You learned how to control an Access application from an Excel VBA procedure. Open the Northwind.mdb database file to view the procedure results. the procedure opens a recordset based on the newly created table. The final task in the procedure is the data transfer operation. This chapter completes Part VI. you will learn how event programming can help you build spreadsheet applications that respond to or limit user actions. running select and parameter queries. CHAPTER SUMMARY This chapter presented numerous examples of getting Excel data into a Microsoft Access database and retrieving data from Microsoft Access into a worksheet. Because we need to add records to the table.appropriate for this error and the procedure will end. imported. placing information found in each worksheet cell into the corresponding table field. . query tables. The For…Next loop is used to move through the Excel data rows. “Controlling Other Applications with VBA. 2. After copying data from all cells in each row. In addition. Run the AccessTbl_From_ExcelData procedure. You also learned how to place Excel data in an Access database by using linked. and charts from the Access data. creating new forms. and dynamic Access tables. this chapter has shown you techniques for creating text files. the procedure uses the Update method of the Recordset object to save the table record. 3. and calling Access built-in functions. To perform this task. Notice that a new record is added to an Access table with the AddNew method of the Recordset object. the procedure uses an adOpenKeyset cursor type. performing such tasks as opening Access forms and reports.” In the next chapter.

.Part 7 Enhancing The User Experience Chapter 17 Event-Driven Programming Chapter 18 Event-Driven Programming Chapter 19 Creating Custom Forms Chapter 20 Formatting Worksheets with VBA Chapter 21 Formatting Worksheets with VBA Excel 2013 offers users the Ribbon interface enhanced with additional tools that enable you to create superb-looking worksheets. You will also learn how to format spreadsheets with VBA and control Excel with event-driven programming. In this part of the book. you learn how to create desired interface elements for your users via Ribbon customizations and how to create dialog boxes and custom forms.

But what if this particular built-in response isn’t appropriate under certain conditions? You may want to entirely disallow rightclicking in a worksheet or perhaps ensure that a custom menu appears on a cell shortcut menu when the user right-clicks any cell. how can you trigger an event? Suppose you right-clicked a worksheet cell.Chapter 17 Event-Driven Programming How do you disable a built-in shortcut menu when a user clicks on a worksheet cell? How do you display a custom message before a workbook is opened or closed? How can you validate data entered in a cell or range of cells? To gain complete control over Microsoft Excel. Once you learn about events in Excel. An event is an action recognized by an object. Events can be triggered by an application user (such as you). or the system itself. Learning how to program events will allow you to implement your own functionality in an Excel application. So. An event is something that happens to objects that are part of Microsoft Excel. The good news is you can use VBA to write code that can react to events as they occur. allowing you to quickly access the most frequently used commands related to worksheet cells. The first thing you need to know about this subject is what an event is. you will find it easier to understand events that occur to objects in Word or any other Microsoft Office application. another program. This particular action would display a built-in shortcut menu for a worksheet cell. you must learn how to respond to events. The following Microsoft Excel objects can respond to events: Worksheet Chart sheet Query table .

while others can be more complex. [[Figure 17.1 illustrates how objects that respond to events display a list of events in the Procedure drop-down list in the Code window. Before you can write an event procedure to react to an Excel event. and worksheet events are available for any open sheet or workbook. The place where you should put the event code. The programmer cannot change the name of the event procedure. Event procedures have names. which are created in the following way: ObjectName_EventName() In the parentheses after the name of the event. or the Application object. While workbook. Some events are coded in a standard module. Also. Some events may require a single line of code. This procedure contains VBA code that handles a particular event. is used to react to specific events. you must first create a new object using the With Events keywords in the class module. . INTRODUCTION TO EVENT PROCEDURES A special type of VBA procedure. as shown in Figure 17. chart sheet. you need to know: The names of the particular object and event to which you want to respond.Workbook ApplicationYou can decide what should happen when a particular event occurs by writing an event procedure. an event procedure. others are stored in a class module.2. to create event procedures for an embedded chart. query table. you can place parameters that need to be sent to the procedure. you can use the Object Browser to find out the names of the events.

You can find out the event names in the Code window.1. .Figure 17.

You can also find out the event names in the Object Browser. WRITING YOUR FIRST EVENT PROCEDURE .2.Figure 17.

xlsm workbook to Test. Once this event procedure is written. 3. double-click ThisWorkbook in the Microsoft Excel Objects folder under VBAProject (Practice_Excel17.At times you will want to trigger a certain operation when a user invokes an Excel command. enter the following Workbook_BeforeSave event procedure: Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean. its code will run automatically when a user attempts to save the workbook file in which the procedure is located. save it as 2. _ Cancel As Boolean) If MsgBox("Would you like to copy " & vbCrLf _ & "this worksheet to " & vbCrLf _ & "a new workbook?". 6. Change the name of Sheet1 in the Practice_Excel17.xlsm). In the ThisWorkbook Code window. For example. Please note files for the “Hands-On” project may be found on the companion CDROM.xlsm . Open a new workbook and C:\Excel2013_ByExample\Practice_Excel17. Switch to the Visual Basic Editor screen. vbQuestion + vbYesNo) . Hands-On 17.1. Type anything in cell A1 and press Enter. Writing an Event Procedure 1. 4. when the user attempts to save a workbook you may want to present him with the opportunity to copy the active worksheet to another workbook. 5. Your first event procedure in this chapter explores this scenario. In the Project Explorer.

But what if you wanted to copy the worksheet file to another workbook and also save the original workbook file? Let’s modify our Workbook_BeforeSave procedure to make sure the workbook file is saved regardless of whether the user answered Yes or No to the message.Name). Click the File tab and choose Save to save Practice_Excel17. Click Yes to the message box. however. The original workbook file will not be saved. 7. The Workbook_BeforeSave event procedure that you wrote in Step 6 will be triggered at this time. the file format. the Excel built-in save event will be triggered.xlsm.= vbYes Then Sheets(ActiveSheet. and its location.Copy End If End Sub The above event procedure uses a MsgBox function to display a two-button dialog box asking the user whether the current worksheet should be copied to another workbook. If the workbook has never been saved before. Switch to the Microsoft Excel application window. If.xlsm workbook. and choose Save. Change the Workbook_BeforeSave procedure as follows: Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean. Excel will open a new workbook with the copy of the current worksheet. click the File tab. Notice that the workbook file is now being saved. Notice that again you are prompted with the dialog box. Visual Basic will open a new workbook and copy the active worksheet to it. 10. _ Cancel As Boolean) Dim wkb As Workbook Set wkb = ActiveWorkbook Cancel = False . Close the workbook file created by Excel without saving any changes. 8. 9. Click No to the message. the user clicks No. you will be presented with the Save As dialog box where you can specify the filename. If the user clicks the Yes button. Do not close the Practice_Excel17.

If you’d rather call your own saving procedure. This will trigger the Excel built-in save event.If MsgBox("Would you like to copy " & vbCrLf _ & "this worksheet to " & vbCrLf _ & "a new workbook?". vbQuestion + vbYesNo) = vbYes Then Sheets(ActiveSheet. Here’s a short event procedure example: Private Sub Workbook_BeforeSave(ByVal SaveAsUI _ As Boolean. Because copying will move the focus to the new workbook that does not contain the customized Workbook_BeforeSave procedure.Activate End If End Sub To continue with the saving process. We can get back pretty easily to the original workbook by setting a reference to it at the beginning of the event procedure and then issuing the wkb. you need to set the Cancel argument to False.Copy wkb.Name). set the Cancel property to True and type the name of your custom save procedure. _ Cancel As Boolean) ' abort the built-in save event Cancel = True ' call your own saving procedure MyCustomSaveProcedure End Sub . you need to activate the original workbook after performing the copy.Activate statement.

Excel proceeds to save the workbook file (you should see the flashing message in the status bar). In cases when the file has not yet been saved or the user wants to save the workbook with a different filename. 12. When you click Yes or No in response to the message box. Type anything in the Test worksheet in the Practice_Excel17. After all these tasks are completed. then click the Save button on the Quick Access toolbar. If you answered Yes in the previous step. vbQuestion + vbYesNo) = vbYes Then Sheets(ActiveSheet. Excel also copies the Test worksheet to another workbook.Name). close the workbook file created by Excel without saving any changes.Copy wkb. the default Save As dialog box will pop up and the user will not be bothered with the copy prompt. Now that you know how to use the Cancel argument.Activate . The following step takes this situation into consideration. 13.11.xlsm workbook. Modify the Workbook_BeforeSave event procedure as follows: Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean.xlsm file. _ Cancel As Boolean) If SaveAsUI = True Then Exit Sub Dim wkb As Workbook Set wkb = ActiveWorkbook Cancel = False If MsgBox("Would you like to copy " & vbCrLf _ & "this worksheet to " & vbCrLf _ & "a new workbook?". Do not close Practice_Excel17. This argument allows you to handle the situation when the user chooses the Save As option. Excel activates the Practice_Excel17.xlsm. If you clicked Yes. let’s look at the other argument of the Workbook_BeforeSave event—SaveAsUI. Suppose that in our procedure example we want to prompt the user to copy the current worksheet to another workbook only when the Save option is selected.

Range("A1:B1") .xlsm application window. Instead.xlsm file because it already contains the Worksheet_BeforeSave event procedure we want to block in this demonstration. enter the following EnterData procedure: Sub EnterData() With ActiveSheet. and choose Save As | Excel Macro-Enabled Workbook. we will write a procedure in a standard module that will save the workbook after making some changes in the active sheet.2. ENABLING AND DISABLING EVENTS You can use the Application object’s EnableEvents property to enable or disable events.1. Hands-On 17. click the File tab.Value = 15 End With . 1. Excel proceeds to run its own built-in Save As process. Switch to the Practice_Excel17.xlsm) and rename it StandardProcedures. Notice that you are not prompted to copy the current worksheet to another workbook.Color = vbRed .Font. set the EnableEvents property to False. We will continue working with the Practice_Excel17. In the module’s Code window. Disabling a Custom Event Procedure This Hands-On requires prior completion of Hands-On 17. Choose Insert | Module to add a standard module to VBAProject (Practice_Excel17.End If End Sub 14. If you are writing a VBA procedure and don’t want a particular event to occur. To demonstrate how you can prevent a custom event procedure from running. When the Save As dialog box appears. click Cancel. 2.

you are not prompted to copy the worksheet before saving. This indicates that the code you entered in the Hands-On 17. select EnterData and click Run.1. This will prevent the Workbook_BeforeSave event procedure from running when Visual Basic encounters the statement to save the workbook. EVENT SEQUENCES Events occur in response to specific actions.EnableEvents = True End Sub Notice that prior to calling the Save method of the ActiveWorkbook property.EnableEvents statement set to True. and closing the workbook. When Visual Basic has completed the saving process. adding a new worksheet to a workbook. Notice that when you run the EnterData procedure.Application. We don’t want the user to be prompted to copy the worksheet while running the EnterData procedure.Save Application.1 demonstrates the sequence of events that occur while opening a new workbook. Events also occur in a predefined sequence. In the Macro dialog box. so we enable the events with the Application. Switch to the Practice_Excel17.1 Workbook_BeforeSave event procedure is not running. 4. Close the Practice_Excel17. Table 17.EnableEvents = False ActiveWorkbook. 3. Table 17.xlsm workbook.xlsm application window and choose View | Macros | View Macros. we want the system to respond to the events as we programmed them. we have disabled events by setting the EnableEvents property to False. Event sequences .

2 lists some of the events to which the Worksheet object can respond.2.WORKSHEET EVENTS A Worksheet object responds to such events as activating and deactivating a worksheet. Table 17. Worksheet events (a partial listing) . and double-clicking or right-clicking a worksheet. Table 17. calculating data in a worksheet. making a change to a worksheet.

Open a new workbook and save it as Practice_WorksheetEvents.Let’s try out these events to get the hang of them. 2.Name . 4. Switch to the Visual Basic Editor window. Worksheet_Activate() This event occurs upon activating a worksheet.xlsm) in the Microsoft Excel Objects folder. Insert a new worksheet to the current workbook.3. Writing the Worksheet_Activate() Event Procedure 1. Hands-On 17. enter the code shown below: Dim shtName As String Private Sub Worksheet_Activate() shtName = ActiveSheet. double-click Sheet2 under VBAProject (Practice_WorksheetEvents. 3.xlsm in your Excel2013_ByExample folder. In the Sheet2 Code window. In the Project Explorer window. 5.

3.Name & ". Switch to the Microsoft Excel application window and click the Sheet2 tab. the selection is moved to cell B2." End Sub The example procedure displays a message when Sheet2 is deactivated. 6. We will need this value as we work with other event procedures in this section. Switch to the Microsoft Excel application window and activate Sheet2. In the Sheet2 Code window. Switch to the Visual Basic Editor window. enter the Worksheet_Deactivate procedure as shown below: Private Sub Worksheet_Deactivate() MsgBox "You deactivated " & _ shtName & ". Excel also stores the sheet name in the shtName variable that was declared at the top of the module. 7. Worksheet_Deactivate() This event occurs when the user activates a different sheet in a workbook." & vbCrLf & _ "You switched to " & _ ActiveSheet. Writing the Worksheet_Deactivate() Event Procedure This Hands-On exercise uses the Practice_WorksheetEvents workbook created in Hands-On 17. Notice that when Sheet2 is activated. 2.Range("B2").4. 1.3 will run . The Worksheet_Activate procedure that you created in Hands-On 17. Hands-On 17.Select End Sub The example procedure selects cell B2 each time the sheet is activated. Notice that the shtName variable is declared at the top of the module.

double-click Sheet3 under VBAProject (Practice_WorksheetEvents. In the Sheet3 Code window. Target) If Not myRange Is Nothing Then MsgBox "Data entry or edits are not permitted. 3. Now click any other sheet in the active workbook. Hands-On 17. Excel will select cell B2 and store the name of the worksheet in the shtName global variable declared at the top of the Sheet2 code module.first.5. In the current workbook. enter the Worksheet_SelectionChange procedure as shown below: Private Sub Worksheet_SelectionChange(ByVal Target _ As Excel. 2.Range) Dim myRange As Range On Error Resume Next Set myRange = Intersect(Range("A1:A10"). Worksheet_SelectionChange() This event occurs when the user selects a worksheet cell. 3. Switch to the Visual Basic Editor window.xlsm) in the Microsoft Excel Objects folder. Notice that Excel displays the name of the worksheet that you deactivated and the name of the worksheet you switched to." . insert a new worksheet. Writing the Worksheet_SelectionChange() Event Procedure 1. In the Project Explorer window.

2. Click on any cell within the specified range A1:A10.Range) Application. In the Sheet1 Code window. .EnableEvents = True End Sub The example procedure changes what you type in a cell to uppercase.AutoFit Application. Switch to the Microsoft Excel application window and activate Sheet3. Writing the Worksheet_Change() Event Procedure 1. The column where the target cell is located is then autosized. activate the Project Explorer window and doubl e. In the Visual Basic Editor window. Notice that Excel displays a message whenever you click a cell in the restricted area.xlsm. Hands-On 17. Worksheet_Change() This event occurs when the user changes a cell formula. enter the Worksheet_Change event procedure as shown below: Private Sub Worksheet_Change(ByVal Target As Excel.Column). 4.cl i ck Sheet1 in the Microsoft Excel Objects folder of Practice_WorksheetEvents.6.EnableEvents = False Target = UCase(Target) Columns(Target.End If End Sub The example procedure displays a message if the user selects any cell in myRange.

. and double-click the sheet you added in Step 1. Switch to the Microsoft Excel application window and activate Sheet1. Excel changes the text you typed to uppercase and autosizes the column. Switch to the Microsoft Excel application window and modify the entry in cell B2 on the sheet you added in Step 1 by typing any number. activate the Project Explorer window. Worksheet_Calculate() This event occurs when the user recalculates the worksheet. In cell A2 of this newly added sheet." End Sub 4.7. Enter the following formula in cell C2: = A2+B2. Worksheet_BeforeDoubleClick(ByVal Target As Range. enter 1. Notice that as soon as you press the Enter key. Notice that after leaving Edit mode. enter the code of the Worksheet_Calculate procedure as shown below: Private Sub Worksheet_Calculate() MsgBox "The worksheet was recalculated. 3. 2. and in cell B2. In the Code window. Writing the Worksheet_Calculate() Event Procedure 1. the Worksheet_Calculate event procedure is triggered and you are presented with a custom message. Enter any text in any cell. Hands-On 17.3. Switch to the Visual Basic Editor window. Cancel As Boolean) This event occurs when the user double-clicks a worksheet. Add a new sheet to the Practice_WorksheetEvents workbook. enter 2.

" Cancel = True Else MsgBox "You may edit this cell. Hands-On 17. please. Cancel As Boolean) This event occurs when the user right-clicks a worksheet cell. 4. When writing event procedures that restrict access to certain program features. In the Visual Basic Editor window. 3.9. type the code of the procedure as shown below: Private Sub Worksheet_BeforeDoubleClick(ByVal _ Target As Range. In the Sheet2 Code window.Address = "$C$9" Then MsgBox "No double-clicking." End If End Sub The example procedure disallows in-cell editing when cell C9 is double-clicked. However. 2. Double-click Sheet2. write additional code that prevents any workaround. and the user is not allowed to edit the data inside the cell. activate the Project Explorer window and open the Microsoft Excel Objects folder.8. Switch to the Microsoft Excel application window and double-click cell C9 on Sheet2. Writing the Worksheet_BeforeDoubleClick() Event Procedure 1. Worksheet_BeforeRightClick(ByVal Target As Range. Enter any data in cell C9 on Sheet2 of the Practice_WorksheetEvents workbook. Writing the Worksheet_BeforeRightClick() Event Procedure . The Worksheet_BeforeDoubleClick event procedure cancels the built-in Excel behavior.Hands-On 17. Cancel As Boolean) If Target. the user can get around this restriction by clicking on the formula bar or pressing F2.

In the Visual Basic Editor window.Count > 1 Then With .Controls. _ before:=1.Rows. temporary:=True) .CommandBars("Cell") .Add(Type:=msoControlButton.Show arg12:=1 End Sub The PrintMe procedure is called by the Worksheet_BeforeRightClick event when .1. enter the code of the Worksheet_BeforeRightClick procedure as shown below: Private Sub Worksheet_BeforeRightClick(ByVal _ Target As Range. 2.Columns.OnAction = "PrintMe" End With End If End With End Sub The example procedure adds a Print option to the cell shortcut menu when the user selects more than one cell on the worksheet. activate the Project Explorer window and double-click Sheet2 in the Microsoft Excel Objects folder..Count > 1 Or _ Target. Cancel As Boolean) With Application.Reset If Target. In the Sheet2 Code window. 3.Dialogs(xlDialogPrint). Insert a new module into the current project and enter the PrintMe procedure as shown below: Sub PrintMe() Application.Caption = "Print." ..

the CommandBar object was the only way to create. The Worksheet_BeforeRightClick event procedure relies on the CommandBar object to customize Excel’s built-in context menu. modify. Notice that the Show method of the Dialogs collection is followed by a named argument: arg12:=1. WORKBOOK EVENTS Workbook object events occur when the user performs such tasks as opening. Now select at least two cells in the Sheet2 worksheet and right-click the selected area. Save and close the Practice_WorksheetEvents.” 6. deactivating. however. saving. 5. Switch to the Microsoft Excel application window and right-click on any single cell in Sheet2. To write code that responds to a particular workbook you can: Double-click the ThisWorkbook object in the Visual Basic Editor’s Project Explorer. Before Excel 2010. printing.the user selects the Print option from the shortcut menu.” the Print dialog displays “Print Selection. 4. or disable context menus. and closing a workbook. you should rely on the RibbonX model (as discussed in Chapter 21) to add your own customizations to context menus. Excel dialog boxes are covered in the next chapter. You should see the Print option as the first menu entry. This argument will display the Print dialog box with the preselected option button “Selection” in the Print area of the dialog box. activating. Excel 2013 still supports CommandBars for compatibility. . Notice that the shortcut menu appears with the default options. Workbook events are not created in a standard VBA module. Click the Print option and notice that instead of the default “Print active sheet.xlsm workbook file.

The selected event procedure stub will appear in the Code window as shown below: Private Sub Workbook_Open() place your event handling code here End Sub Table 17. Workbook events (a partial listing) . select the event you want. Table 17.In the Code window that appears.3. In the Procedure drop-down list (the one on the right).3 lists some of the events to which the Workbook object can respond. open the Object drop-down list on the lefthand side and select the Workbook object.

10. Switch to the Visual Basic Editor window.xlsm in your C:\Excel2013_ByExample folder.Count & " sheets. Open a new workbook and save it as Practice_WorkbookEvents. In the ThisWorkbook Code window. Hands-On 17. 3." End Sub The example procedure displays the total number of worksheets when the user . double-click ThisWorkbook in the Microsoft Excel Objects folder. type the Workbook_Activate procedure as shown below: Private Sub Workbook_Activate() MsgBox "This workbook contains " & _ ThisWorkbook.Let’s try out the above events to get the hang of them. Workbook_Activate() This event occurs when the user activates the workbook.Sheets. This event will not occur when the user activates the workbook by switching from another application. In the Project Explorer window. Writing the Workbook_Activate() Event Procedure 1. 2.

Excel should display the total number of sheets in this workbook. In the Visual Basic Editor window. This event does not occur when the user switches to a different application. In the ThisWorkbook Code window. type the Workbook_Deactivate procedure as shown below: Private Sub Workbook_Deactivate() Dim cell As Range For Each cell In ActiveSheet.Address & ":" & cell. Activate the Practice_WorkbookEvents workbook. 4. Writing the Workbook_Deactivate() Event Procedure 1.activates the workbook containing the Workbook_Activate event procedure.xlsm). Switch to the Microsoft Excel application window and open a new workbook.UsedRange If Not IsEmpty(cell) Then Debug. Hands-On 17.Print cell. Workbook_Deactivate() This event occurs when the user activates a different workbook within Excel.11.Value End If Next End Sub The example procedure will print to the Immediate window the addresses and values of cells containing entries in the current workbook when the user activates a different workbook. 2. . activate the Project Explorer window and double-click ThisWorkbook in the Microsoft Excel Objects folder under VBAProject (Practice_WorkbookEvents. 5.

Writing the Workbook_Open() Event Procedure 1.12.Value = Format(Now(). Save and close Practice_WorkbookEvents. Switch to the Microsoft Excel application window and make some entries on the active sheet. When you open the workbook file again.Range("A1").xlsm and then reopen it. activate a different workbook. "mm/dd/yyyy") Columns("A"). This action will trigger the Workbook_Deactivate event procedure. 3.3. Cancel As Boolean) . the Workbook_Open event procedure will be triggered and the current date will be placed in cell A1 on the active sheet. Workbook_BeforeSave(ByVal SaveAsUI As Boolean.xlsm). type the Workbook_Open procedure as shown below: Private Sub Workbook_Open() ActiveSheet. Double-click the ThisWorkbook object in the Microsoft Excel Objects folder under VBAProject (Practice_WorkbookEvents.AutoFit End Sub The example procedure places the current date in cell A1 when the workbook is opened. Next. 2. 4. In the ThisWorkbook Code window. Switch to the Visual Basic Editor screen and open the Immediate window to see what entries were reported. Hands-On 17. Workbook_Open() This event occurs when the user opens a workbook.

Hands-On 17. Writing the Workbook_BeforeSave() Event Procedure 1. 2. In the ThisWorkbook Code window." & vbCrLf _ & "The Save As dialog box will be displayed. In the Visual Basic Editor screen. the value of SaveAsUI is True. it is False. The user will need to .13. If the workbook has not been saved. otherwise.xlsm). The SaveAsUI argument is read-only and refers to the Save As dialog box.Path = vbNullString Then MsgBox "This document has not yet " _ & "been saved. Double-click ThisWorkbook. The procedure will not let the user save the workbook under a different name—the SaveAs operation will be aborted by setting the Cancel argument to True." ElseIf SaveAsUI = True Then MsgBox "You are not allowed to use " _ & "the SaveAs option.This event occurs before the workbook is saved. " Cancel = True End If End Sub The example procedure displays the Save As dialog box if the workbook hasn’t been saved before. activate the Project Explorer window and open the Microsoft Excel Objects folder under VBAProject (Practice_WorkbookEvents. type the Workbook_BeforeSave procedure as shown below: Private Sub Workbook_BeforeSave(ByVal _ SaveAsUI As Boolean. The workbook’s pathname will be a null string (vbNullString) if the file has not been saved before. Cancel As Boolean) If SaveAsUI = True And _ ThisWorkbook.

and the ElseIf clause gets executed. 2. Writing the Workbook_BeforePrint() Event Procedure 1. In the ThisWorkbook Code window. Make an entry in any cell of this workbook. Switch to the Microsoft Excel application window and activate any sheet in the Practice_WorkbookEvents. The Workbook_BeforeSave event procedure will be activated. 3. _ vbYesNo) If response = vbYes Then .xlsm workbook.xlsm). 4.14. Notice that you are not allowed to save the workbook by using the SaveAs option. activate the Project Explorer window and double-click the ThisWorkbook object in the Microsoft Excel Objects folder under VBAProject (Practice_WorkbookEvents. Workbook_BeforePrint(Cancel As Boolean) This event occurs before the workbook is printed and before the Print dialog appears. click the File tab. In the Visual Basic Editor window. and choose Save As | Excel Macro-Enabled Workbook.choose the Save option to have the workbook saved. type the Workbook_BeforePrint event procedure as shown below: Private Sub Workbook_BeforePrint(Cancel As Boolean) Dim response As Integer response = MsgBox("Do you want to " & vbCrLf & _ "print the workbook’s full name in the footer?". Hands-On 17.

15. Writing the Workbook_BeforeClose() Event Procedure 1.LeftFooter = "" End If End Sub The example procedure places the workbook’s full name in the document footer prior to printing if the user clicks Yes in the message box. 2. type the Workbook_BeforeClose event procedure as shown below: Private Sub Workbook_BeforeClose(Cancel As Boolean) . In the ThisWorkbook Code window. In the Visual Basic Editor window. Workbook_BeforeClose(Cancel As Boolean) This event occurs before the workbook is closed and before the user is asked to save changes. 4. Switch to the Microsoft Excel application window and activate any sheet in the Practice_WorkbookEvents.xlsm). Click the File | Print.PageSetup.LeftFooter = _ ThisWorkbook. 5. Enter anything you want in any worksheet cell. Hands-On 17.xlsm workbook.FullName Else ActiveSheet.ActiveSheet. 3.PageSetup. activate the Project Explorer window and double-click ThisWorkbook in the Microsoft Excel Objects folder under VBAProject (Practice_WorkbookEvents. and click the Print button. Excel will ask you if you want to place the workbook’s name and path in the footer.

type the Workbook_NewSheet event procedure as shown below: .xlsm workbook.Show End If End Sub The example procedure displays the Properties dialog box if the user responds Yes to the message box. double-click ThisWorkbook in the Microsoft Excel Objects folder under VBAProject (Practice_WorkbookEvents2. or abort the closing operation altogether.xlsm in your C:\Excel2013_ByExample folder. 2. Upon closing. 3. If there are any changes that you have not yet saved.xlsm). you are given the chance to save the workbook. Switch to the Visual Basic Editor window.Dialogs(xlDialogProperties). After viewing or modifying the workbook properties. In the ThisWorkbook Code window. the procedure closes the workbook. and in the Project Explorer window. cancel the changes. Open a new workbook and save it as Practice_WorkbookEvents2. _ vbYesNo) = vbYes Then Application. Switch to the Microsoft Excel application window. and close the Practice_WorkbookEvents. Workbook_NewSheet(ByVal Sh As Object) This event occurs after the user creates a new sheet in a workbook. you should see a message box asking you to view the Properties dialog box prior to closing.If MsgBox("Do you want to change " & vbCrLf _ & " workbook properties before closing?". Hands-On 17. 3. Writing the Workbook_NewSheet() Event Procedure 1.16.

Switch to the Microsoft Excel application window and click the New Sheet Button (+) (at the bottom of the screen). 4. Writing the Workbook_WindowActivate() Event Procedure . Hands-On 17.Sheets( _ ThisWorkbook.Sheets(1) Else Sh.Move before:=ThisWorkbook. vbYesNo) = vbYes Then Sh.Count) MsgBox Sh.Private Sub Workbook_NewSheet(ByVal Sh As Object) If MsgBox("Do you want to place " & vbCrLf _ & "the new sheet at the beginning " & vbCrLf _ & "of the workbook?".Name & _ " is now the last sheet in the workbook. Let’s try out some of the events related to operations on workbook windows.Sheets. Workbook_WindowActivate(ByVal Wn As Window) This event occurs when the user shifts the focus to any window showing the workbook.Move After:=ThisWorkbook." End If End Sub The example procedure places the new sheet at the beginning of the workbook if the user responds Yes to the message box. Excel will ask where to place the new sheet.17. otherwise. the new sheet is placed at the end of the workbook.

Switch to the Microsoft Excel application window and open a new workbook. Arrange Microsoft Excel workbooks vertically on the screen.GridlineColor = vbYellow End Sub The example procedure changes the color of the worksheet gridlines to yellow when the user activates the workbook containing the code of the Workbook_WindowActivate procedure.xlsm). Select the Vertical option button and click OK. In the ThisWorkbook Code window. When you activate the worksheet of the workbook in which you entered the code of the Workbook_WindowActivate event procedure. by choosing View | Arrange All to open the Arrange Windows dialog. 2.xlsm).18. 4. Workbook_WindowDeactivate(ByVal Wn As Window) This event occurs when the user shifts the focus away from any window showing the workbook. In the Visual Basic Editor window. the color of the gridlines should change to yellow. enter the Workbook_WindowActivate event procedure as shown below: Private Sub Workbook_WindowActivate(ByVal Wn As Window) Wn. activate the Project Explorer window and double-click the ThisWorkbook object in the Microsoft Excel Objects folder under VBAProject (Practice_WorkbookEvents2. In the ThisWorkbook Code window. In the Visual Basic Editor window. enter the Workbook_WindowDeactivate . Hands-On 17. Writing the Workbook_WindowDeactivate() Event Procedure 1. activate the Project Explorer window and double-click the ThisWorkbook object in the Microsoft Excel Objects folder under VBAProject (Practice_WorkbookEvents2. 3. 2.1.

enter the Workbook_WindowResize procedure as shown below. or minimizes any window showing the workbook.WindowState < > xlMaximized Then Wn. Private Sub Workbook_WindowResize(ByVal Wn As Window) If Wn. 3.xlsm). maximizes.procedure as shown below: Private Sub Workbook_WindowDeactivate(ByVal Wn As Window) MsgBox "You have just deactivated " & Wn. Workbook_WindowResize(ByVal Wn As Window) This event occurs when the user opens. Hands-On 17. Excel displays the name of the deactivated workbook in a message box. resizes.Left = 0 Wn. 2. In the Visual Basic Editor window. activate the Project Explorer window and double-click the ThisWorkbook object in the Microsoft Excel Objects folder under VBAProject (Practice_WorkbookEvents2.Caption End Sub The example procedure displays the name of the deactivated workbook when the user switches to another workbook from the workbook containing the code of the Workbook_WindowDeactivate procedure.19. Switch to the Microsoft Excel application window and open a new workbook.Top = 0 End If . Writing the Workbook_WindowResize() Event Procedure 1. In the ThisWorkbook Code window.

Move the Practice_WorkbookEvents2.xlsm window to the middle of the screen by dragging its title bar.4. Table 17. An Excel workbook can respond to a number of other events. Switch to the Microsoft Excel application and activate the Practice_ WorkbookEvents2. Additional workbook events .xlsm workbook window to its full size. Change the size of the active window by dragging the window borders in or out. 3. the workbook window should automatically jump to the top left-hand corner of the screen. 6.4. 7. 5. as shown in Table 17. Click the Restore Window button to the right of the menu bar. As you complete the sizing operation.xlsm workbook. Click the Maximize button to restore the Practice_WorkbookEvents2. 4.End Sub The example procedure moves the workbook window to the top left-hand corner of the screen when the user resizes it.

Table 17. Chapter 23. Workbook events related to PivotTable reports .” will get you started writing VBA code for creating and manipulating PivotTables and PivotCharts. By rotating rows and columns of a PivotTable report. PivotTable reports provide a powerful way of analyzing and comparing large amounts of information stored in a database. you can see different views of the source data or see details of the data that interests you the most. You will find it easier to delve into the PivotTable event programming after working through Chapter 23.5. If you haven’t worked with PivotTables programmatically. When working with PivotTable reports programmatically. Table 17. “Programming PivotTables and PivotCharts.5 lists events related to PivotTable reports. you can determine when a PivotTable report opened or closed the connection to its data source by using the PivotTableOpenConnection and PivotTableCloseConnection workbook events and determine when the PivotTable was updated via the SheetPivotTableUpdate event.PIVOTTABLE EVENTS In Excel.

.

Creating Charts for Trying Out Chart Events . perform the tasks in Hands-On 17. Before you try out selected chart events. Hands-On 17.20. In this section.20. you can create charts in Excel that are embedded in a worksheet or located on a separate chart sheet. you will learn how to control chart events no matter where you’ve decided to place your chart.CHART EVENTS As you know.

3. In the Insert dialog box.3. 2. change the chart type to Line chart with Markers by choosing the Change Chart Type button in the Chart . select Chart and click OK.5. On the Design tab in the Chart Tools group. At this point.1. click the Select Data button.3. To add a new chart sheet.xlsm. Now. Column chart embedded in a worksheet. Figure 17. Excel will fill in the Chart data range box in the dialog box as in Figure 17. 3. Using the same data. 5. right-click any sheet tab in the workbook and choose Insert.4. click the Sheet1 tab and select cells A1:D5. Select cells A1:D5. create a line chart on a separate chart sheet. Excel will display the Select Data Source dialog box. and choose Insert | Charts | Insert Column Chart | 2-D | Clustered Column. 4. Size the chart as shown in Figure 17. Enter sample data as shown in Figure 17. Open a new Excel workbook and save it as Practice_ChartEvents. Click OK to complete the chart. as shown in Figure 17.

. Creating a chart in a chart sheet. Figure 17.Tools Design tab. Click OK to close the dialog box. In the Change Chart Type dialog box. Change the name of the chart sheet to Sales Analysis Chart. 6. select Line chart in the left pane. and click the button representing the Line chart with Markers.4.

” .5.6.3 require using the WithEvents keyword and are explained in the section titled “Writing Event Procedures for Embedded Charts. Table 17. Chart events We will start by writing event procedures that control a chart placed on a separate chart sheet as shown in Figure 17. Writing Event Procedures for a Chart Located on a Chart Sheet Excel charts can respond to a number of events. Events for a chart embedded in a worksheet like the one in Figure 17.5.6. Line chart placed in a chart sheet.Figure 17. as shown in Table 17.

ByVal y As Long) This event occurs when a mouse button is pressed while the pointer is over a chart.Chart_Activate() This event occurs when the user activates the chart sheet. ByVal Arg1 As Long. 4 – Alt was selected. For example. y arguments specify the mouse pointer coordinates. Ctrl. The x. 2 – right button. Chart_Deactivate() This event occurs when the user deactivates the chart sheet. while the axis type is specified by Arg2. Chart_Calculate() This event occurs when the user plots new or changed data on the chart. 2 – Ctrl was selected. which can be one of the following three values: 0 – Category Axis. ByVal Arg2 As Long) This event occurs when the user selects a chart element.21. Writing Event Procedures for a Chart Sheet . T h e Button argument determines which mouse button was pressed (MouseDown event) or released (MouseUp event): 1 – left button. ElementID returns a constant representing the type of the selected chart element. the chart axis (ElementID = 21) can be specified as Main Axis (Arg1 = 0) or Secondary Axis (Arg1 = 1). Chart_MouseDown(ByVal Button As Long. Hands-On 17. Arguments Arg1 and Arg2 are used in relation to some chart elements. ByVal Shift As Long. and Alt keys: 1 – Shift was selected. Chart_Select(ByVal ElementID As Long. The Shift argument specifies the state of the Shift. and 3 – Series Axis. ByVal x As Long. and 4 – middle button. 1 – Value Axis. Chart_BeforeRightClick() This event occurs when the user right-clicks the chart.

ByVal Arg2 As Long) If Arg1 < > 0 And Arg2 < > 0 Then MsgBox ElementID & ".1." ElseIf ElementID = 12 Then MsgBox "You’ve selected the legend key." ElseIf ElementID = 24 Then MsgBox "You’ve selected the chart legend. " & Arg2 End If If ElementID = 4 Then MsgBox "You’ve selected the chart title." . activate the Project Explorer window and open the Microsoft Excel Objects folder under VBAProject (Practice_ChartEvents. In the Visual Basic Editor window." End Sub Private Sub Chart_Select(ByVal ElementID As Long. Double-click the chart object Chart1 (Sales Analysis Chart)." End Sub Private Sub Chart_Deactivate() MsgBox "It looks like you want to leave the " _ & "chart sheet. enter the code of the following event procedures: Private Sub Chart_Activate() MsgBox "You’ve activated the chart sheet. " & Arg1 & ".xlsm). 2. 3. _ ByVal Arg1 As Long. In the Code window." ElseIf ElementID = 13 Then MsgBox "You’ve selected the legend entry.

Your chart has been updated. ByVal y As Long) If Button = 1 Then MsgBox "You pressed the left mouse button. ByVal x As Long." Else MsgBox "You pressed the middle mouse button. Writing Event Procedures for Embedded Charts ." End If End Sub 4.End If End Sub Private Sub Chart_Calculate() MsgBox "The data in your spreadsheet has " & vbCrLf _ & "changed." End Sub Private Sub Chart_BeforeRightClick(Cancel As Boolean) Cancel = True End Sub Private Sub Chart_MouseDown(ByVal Button As Long. click the chart legend and notice that this action triggers two events: Chart_MouseDown and Chart_Select. Activate the chart sheet and perform the actions that will trigger the event procedures that you’ve written. For example." ElseIf Button = 2 Then MsgBox "You pressed the right mouse button. _ ByVal Shift As Long.

Declaring an object variable using the WithEvents keyword exposes all of the events defined for that particular object type. 5. The Public keyword will make the object variable xlChart available to all modules in the current VBA project. Open the Object drop-down listbox and select the xlChart variable. The Code window should now show the skeleton of the xlChart_Activate event procedure: Private Sub xlChart_Activate() . In the Class Modules folder. After typing the above declaration. and the events associated with this object variable appear in the Procedure dropdown listbox in the upper-right corner of the Code window. In the following example procedure. In the Project Explorer. In the Properties window. 4.To capture events raised by a chart embedded in a worksheet.20. you must first create a new object in the class module using the keyword WithEvents.xlsm). Choose Insert | Class Module. the xlChart object variable is added to the drop-down Object list in the upper-left corner of the Code window. Writing the Chart_Activate() Event Procedure for an Embedded Chart 1. This keyword can only be used in class modules in the declaration section.22.Chart The above statement declares an object variable that will represent the events generated by the Chart object. Hands-On 17. type the following declaration: Public WithEvents xlChart As Excel. select VBAProject (Practice_ChartEvents. Activate the Visual Basic Editor window. In the clsChart class module Code window. 2. we will learn how to use the WithEvents keyword to capture the Chart_Activate event for the embedded chart you created in Hands-On 17. 3. you will see a module named Class1. The WithEvents keyword allows you to specify an object variable that will be used to respond to events triggered by an ActiveX object. rename Class1 to clsChart.

End Sub 6. you must write a VBA procedure that initializes it (see Step 8). 7. and enter in the first line of the ThisWorkbook Code window the statement to create a new instance of the class named clsChart: Dim myChart As New clsChart This instruction declares an object variable named myChart. Enter the following procedure in the ThisWorkbook Code window to initialize the object variable myChart: Sub InitializeChart() ' you must run this procedure before event procedures ' written in clsChart class module can be triggered for ' the chart embedded in Sheet1 ' connect the class module with the Excel chart object . you need to inform Visual Basic that you are planning on using it (see Step 7). your VBA procedure should look like the following: Private Sub xlChart_Activate() in MsgBox "You’ve activated a chart embedded " & _ ActiveSheet. 8.Name & ". This variable will refer to the xlChart object located in the class module clsChart. In this example. In the Project Explorer window. Add your VBA code to the event procedure." End Sub After entering the code of the event procedure. The New keyword tells Visual Basic to create a new instance of the specified object. After adding this statement. Before you can use the myChart object variable. double-click the object named ThisWorkbook. we will add a statement to display a message box.

the xlChart_Activate event procedure that you entered in Step 6 above should be triggered. Similar to an embedded chart. the event procedures entered in the clsChart class module will be triggered in response to a particular event. Later on you may want to write in the clsChart class module additional event procedures to capture other events for your embedded chart. At this time. Table 17.ChartObjects(1).7. Application events . Events for the Application object are listed in Table 17. 10. After running this procedure.xlChart = _ Worksheets("Sheet1").Chart End Sub 9.7.xlsm workbook file. event procedures for the Application object require that you create a new object using the WithEvents keyword in a class module. Run the InitializeChart procedure. Event procedures for the Application object have a global scope. EVENTS RECOGNIZED BY THE APPLICATION OBJECT If you want your event procedure to execute no matter which Excel workbook is currently active. Save and close the Practice_ChartEvents. Recall that right now the clsChart class module contains the Chart_Activate event procedure. 11. This means that the procedure code will be executed in response to a certain event as long as the Microsoft Excel application remains open. you need to create the event procedure for the Application object. Activate the Microsoft Excel application window and click the embedded chart in Sheet1.Set myChart.

.

.

Let’s try a couple of event procedures for the Application object.23. Writing Event Procedures for the Application Object . Hands-On 17.

ByVal SaveAsUI As Boolean. Switch to the Visual Basic Editor window.xlsm in C:\Excel2013_ByExample.1. Choose Insert | Class Module.xlsm). Open a new workbook and save it as Practice_ApplicationEvents. and in the Project Explorer window select VBAProject (Practice_ApplicationEvents.FileFormat = xlCSV Then If MsgBox("Do you want to save this " & vbCrLf _ & "file as an Excel workbook?". 3. _ . 2.SaveAs FileFormat:=xlWorkbookNormal End If End If End Sub Private Sub App_WorkbookBeforeSave(ByVal _ Wb As Workbook. 6. _ "Original file format: " _ & "comma delimited file") = vbYes Then Wb. 4. In the clsApplication Code window. enter the event procedures as shown below: Private Sub App_WorkbookOpen(ByVal Wb As Workbook) If Wb. 5. vbYesNo. type the following declaration statement: Public WithEvents App As Application This statement uses the WithEvents keyword to declare an Application object variable. change the class module name to clsApplication. In the Properties window. Below the declaration statement.

Name Resume Next End Sub .Cancel As Boolean) If Wb. Cancel As Boolean) Dim r As Integer Dim p As Variant Sheets.Item(p. Cancel As Boolean) Wb. 1).PrintOut Copies:=2 End Sub Private Sub App_WorkbookBeforeClose(ByVal _ Wb As Workbook.Name).Value r = r + 1 Next Exit Sub ErrorHandle: Cells(r. 1).Caption = Wb.BuiltinDocumentProperties On Error GoTo ErrorHandle Cells(r.Value = p.BuiltinDocumentProperties _ .Add r = 1 For Each p In Wb.Name & " = " & _ ActiveWorkbook.Path < > vbNullString Then ActiveWindow.Value = p.FullName & _ " [Last Saved: " & Time & "]" End If End Sub Private Sub App_WorkbookBeforePrint(ByVal _ Wb As Workbook.

ByVal Wn As Window) Wn.StatusBar = Target. 9.Count < 2 And _ IsEmpty(Target.Value)) Then Application.Address Else Application. After you’ve entered the code of the above event procedures in the class module.Address & _ "(" & Target.App = Application End Sub Recall that you declared the App object variable to point to the Application object in Step 5 above. In the newly inserted standard module. choose Insert | Module to insert a standard module into your current VBA project. ByVal Target As Range) If Selection.DisplayFormulas = True End Sub 7.Private Sub App_SheetSelectionChange(ByVal Sh _ As Object. Now place the mouse pointer within the InitializeAppEvents procedure and press F5 to run it.StatusBar = Target.Value & ")" End If End Sub Private Sub App_WindowActivate(ByVal _ Wb As Workbook. as shown below: Dim DoThis As New clsApplication Public Sub InitializeAppEvents() Set DoThis. 8.Count > 1 Or _ (Selection. create a new instance of the clsApplication class and connect the object located in the class module clsApplication with the object variable App representing the Application object. .

Every time you save this workbook file. Take a look at the code in other event procedures you entered in Step 6 and perform actions that will trigger these events. the code of the event procedures written in the class module will not be automatically executed when a specific event occurs. Close the Practice_ApplicationEvents. When you run the CancelAppEvents procedure. From now on.xlsm file and other workbooks if they are currently open. Click the File tab and choose Save As. Click the File tab and choose New. the code of the event procedures you’ve entered in the class module will be executed.xlsx. If you don’t want to respond to events generated by the Application object. Notice that Excel writes the full name of the workbook file and the time the workbook was last saved in the workbook’s title bar as coded in the WorkbookBeforeSave event procedure (see Step 6). QUERY TABLE EVENTS .xlsx workbook and save this workbook. when a specific event occurs. you release the memory and break the connection between the object variable and the object to which this variable refers. you can break the connection between the object and its object variable by entering in a standard module (and then running) the following procedure: Public Sub CancelAppEvents() Set DoThis. Switch to the Practice_ApplicationEvents workbook in the Excel application window. Excel will update the last saved time in the workbook’s title bar. Type anything in Sheet1 of the TestBeforeSaveEvent.As a result of running the InitializeAppEvents procedure. 11. and click Create. 10. Save the workbook opened in Step 10 as TestBeforeSaveEvent. 13. Select Blank Workbook. 14. the App object in the class module will refer to the Excel application. Now let’s proceed to try triggering the application events you coded in the class module. 12.App = Nothing End Sub When you set the object variable to Nothing.

” When you retrieve data from an external data source such as Access or SQL Server using the controls available on the Excel 2013 Ribbon’s Data tab.24. click the From Other Sources button and choose From Microsoft Query. 5. or a text file. such as an SQL Server database. 6. This exercise assumes that you have Microsoft Access and its sample Northwind 2007. *. The 2013 version of Excel can create a query table as a standalone object or as a list object whose data source is a query table.A query table is a table in an Excel worksheet that represents data returned from an external data source.accdb database installed on your computer. In Step 3 of the Create New Data Source dialog box. 3. The list object is discussed in detail in Chapter 24. Open a new Microsoft Excel workbook and save it as Practice_QueryTableEvents. “Using and Programming Excel Tables.accdb) from the drop-down list. Choose the Data tab. enter SampleDb as the data source name. 2. In Step 1 of the Create New Data Source dialog box. The resulting table is easier to use thanks to a number of built-in data management features available on the Ribbon. 4. a Microsoft Access database. select Microsoft Access Driver (*. These events are triggered before or after the query table is refreshed. click the Connect button. select < New Data Source > and click OK. In Step 2 of the Create New Data Source dialog box. Excel provides two events for the QueryTable object: BeforeRefresh and AfterRefresh.6. The next Hands-On demonstrates how to create a query table associated with a list object and enable the QueryTable object’s BeforeRefresh and AfterRefresh events. Writing Event Procedures for a Query Table 1. Excel creates a query table that is associated with a list object. a Web page. as shown in Figure 17. In the Choose Data Source dialog box.xlsm in your C:\Excel2013_ByExample folder. In the Get External Data group. . Hands-On 17.mdb.

7.6. Use the Create New Data Source dialog box to specify the data source that will provide data for the query table. 9. In the Select Database dialog box. then click OK to close the Select Database dialog box. In Step 4 of the Create New Data Source dialog box. select the Inventory on Order table in the drop-down listbox. In the ODBC Microsoft Access Setup dialog box.Figure 17.accdb file. click the Select button. navigate to the C:\Excel2013_HandsOn folder and select the Northwind 2007. 8.7. as shown in Figure 17. .

In the Query Wizard–Choose Columns dialog box. 10. click the button with the greater than sign ( >) to move all the fields from the Inventory on Order table to the Columns in your query box. Click OK to close the Create New Data Source dialog box. Click OK. the SampleDb data source name should now be highlighted. 11. In the Choose Data Source dialog box.7.Figure 17. Use Step 4 of the Create New Data Source dialog to specify a default table for your data source. . 12.

Next. make sure the Return Data to Microsoft Excel option button is selected and click Finish. In the Properties window. Switch to the Visual Basic Editor window and insert a class module into VBAProject (Practice_QueryTableEvents. rename the class module clsQryTbl. 18. 15. Let’s continue. enter the two event procedures shown below: Private Sub qryTbl_BeforeRefresh(Cancel As Boolean) Dim Response As Integer Response = MsgBox("Are you sure you " _ & " want to refresh now?". Excel will display the Connection Properties dialog box. 14. the data from the Inventory on Order table in the Northwind 2007 database should be placed in the active worksheet. vbYesNoCancel) If Response = vbNo Then Cancel = True End Sub Private Sub qryTbl_AfterRefresh(ByVal Success . In the Import Data dialog box. Click the Next button until you get to the Query Wizard–Finish dialog box. In the wizard’s Finish dialog box. the current worksheet cell is selected. type the following declaration statement: Public WithEvents qryTbl As QueryTable After you’ve declared the new object (qryTbl) by using the WithEvents keyword. Click cell A1 in the current worksheet to change the cell reference. After completing the above steps. 20.xlsm).xlsm workbook. 17. you must create a class module and declare a QueryTable object by using the WithEvents keyword. Click OK to exit the Import Data dialog box. In the clsQryTbl Code window. 19. click the Properties button. Check Refresh the data when opening the file and click OK. 16. In the clsQryTbl Code window. it appears in the Object drop-down listbox in the class module.13. Save the changes in the Practice_QueryTableEvents. To write event procedures for a QueryTable object.

you must connect the object that you declared in the class module (qryTbl) to the specified QueryTable object." Else MsgBox "The query failed.As Boolean) If Success Then MsgBox "The data has been refreshed. enter the declaration line and the procedure as shown below: Dim sampleQry As New clsQryTbl Public Sub Auto_Open() ' connect the class module and its objects with the Query object Set sampleQry. A query table associated with a list object can only be accessed through the ListObject. 22. 21. In the QueryTableListObj Code window. The AfterRefresh event occurs after a query is completed or canceled.QueryTable property.qryTbl = ActiveSheet." End If End Sub The BeforeRefresh event of the QueryTable object occurs before the query table is refreshed. This is done in a standard module as shown in Step 21. This query table is not a part of the Worksheet. To find out whether a query table .QueryTable End Sub This procedure creates a new instance of the QueryTable class (clsQryTbl) and connects this instance with the first list object on the active worksheet.QueryTables collection.ListObjects(1). Insert a standard module into VBAProject (Practice_QueryTableEvents. The Success argument is True if the query was completed successfully. Before you can trigger these event procedures.xlsm) and rename it QueryTableListObj.

25. the object that you declared in the class module points to the specified QueryTable object. be sure to check both the QueryTables and ListObjects collections.Count ?ActiveSheet. Excel will then trigger the qryTbl_AfterRefresh event procedure and another custom message will be displayed. 24.ListObjects. These events are accessed using the methods of the Application Object: OnTime and OnKey.Count 23. Switch to the Microsoft Excel application window. you won’t need to run the Auto_Open procedure.xlsm workbook file. In the future when you want to work with the QueryTable object in this workbook file. Close the Practice_QueryTableEvents. Run the Auto_Open procedure. Excel will now trigger the qryTbl_BeforeRefresh event procedure and you should see the custom message box. In the worksheet where you placed the Inventory on Order table from the Microsoft Access database. If you click Yes. This procedure will run automatically upon opening the workbook file. After you run this initialization procedure.QueryTables. OnTime Method . This can be done easily by entering in the Immediate window the following statements: ?ActiveSheet. OTHER EXCEL EVENTS There are two events in Excel that are not associated with a specific object: the OnTime and OnKey events. choose Data | Refresh All. the data in the worksheet will be refreshed with the existing data in the database.exists on a worksheet.

_ Procedure.OnTime(EarliestTime.OnTime DateSerial(2014. Therefore. 7..OnTime Now + TimeValue("00:05:00"). Again. LatestTime.OnTime TimeValue("4:00PM").m. type the following statement on one line in the Immediate window and press Enter: Application. _ "YourProcedureName" The Now function returns the current time. Set this parameter to False to cancel the event. The default value for Schedule is True. 4) + + TimeValue("00:00:01"). Schedule) The Procedure parameter is the name of the VBA procedure to run. use the following code: Application. 2014. _ .The OnTime event uses the OnTime method of the Application object to trigger an event at a specific time. "YourProcedureName" To cancel the above event. you need to set the value of the EarliestTime parameter to: Now + TimeValue(time) To trigger your procedure on July 4. you can have Excel run the specified procedure at 4:00 p. False To schedule the procedure five minutes after the current time. as shown below: Application.m. at 12:01 a. Use the TimeValue function to specify time as shown in the examples below. The EarliestTime parameter is the time you would like the procedure to run. "YourProcedureName". _ . The syntax is: Application. For example. to schedule the procedure to occur in the future (a certain amount from the current time). you can use the TimeValue function to specify a time for this parameter. run the following code: Application. The Schedule parameter allows you to clear a previously set OnTime event. LatestTime is an optional parameter that allows you to specify the latest time the procedure can be run.OnTime TimeValue("4:00PM").

.4 (Chapter 15). call the OnKey method without the Procedure parameter: Application. {Down}. See the list of keycodes in Table 15. you would write the following statement: Application. keep in mind that reassigning frequently used Excel shortcuts (such as Ctrl+P for Print) to perform other customized processes may make you an unpopular developer among your users. If you pass an empty string (“”) as the second parameter for the OnKey method. {F1}. {Backspace}."YourProcedureName" OnKey Method You can use the Application object’s OnKey method to trigger a procedure whenever a particular key or key combination is pressed. Procedure) where Key is a string indicating the key to be pressed and Procedure is the name of the procedure you want to execute. "YourProcedureName" Special keys are entered using curly braces: {Enter}. When using the OnKey events. and/or Ctrl. percent sign (%) for Alt. {Home}. The syntax of the OnKey method is as follows: Application.OnKey "%{F10}". Alt. use the following code: Application. Excel will ignore the keystroke.OnKey "%{F10}" The above code will return the key combination Alt+F10 to its default function in Excel. use that character. While using the OnKey method is a quick way to assign a shortcut to execute a VBA procedure or macro. use the plus sign (+) for Shift. To specify a key combination. "NewFolder" To cancel an OnKey event and return the key to its normal function. For example. For example. which is to display the Selection and Visibility pane on the right side of the Excel screen. {Esc}. or {Right}. or any other character key. and caret (^) for Ctrl in front of the keycode. For a letter. to run your procedure when you press Ctrl-a.OnKey(Key.OnKey "^a". to run the procedure named “NewFolder” when the user presses AltF10. The key parameter can specify a single key or any key combined with Shift. a better way is to use the Options button in the Macro dialog to assign a Ctrl+key combination to a procedure.

CHAPTER SUMMARY In this chapter. application. worksheet. or more complex with code including decision-making statements and other programming structures that allow you to change the flow of your program when a particular event occurs. By writing event procedures. Visual Basic will simply run an appropriate event procedure instead of responding in the standard way. You’ve also learned that you can enable or disable events using the EnableEvents property. In the final section of this chapter. The next chapter takes you through the process of accessing Excel dialog boxes with VBA. . whether you are planning to create spreadsheet applications for others to use or simply automating your worksheet daily tasks. You’ve learned that some event procedures are written in a standard module (workbook. and query table) require that you create a new object using the WithEvents keyword in a class module. These are invaluable skills. Your event procedures can be as simple as a single line of code displaying a custom message. you gained hands-on experience with events and event-driven programming in Excel. Excel provides many events to which you can respond. you can change the way objects respond to events. When a certain event occurs. and standalone chart sheet) while others (embedded chart. you also learned how to use two Application object methods to execute procedures at a specific time or in response to the user pressing a key or a key combination.

some of which are listed in Table 18. xlDialogFont. are Microsoft Excel objects that belong to the built-in collection of dialog boxes.1. Microsoft Excel has a special collection of built-in dialog boxes that are represented by constants beginning with xlDialog. But what if your procedure requires more data at runtime? The user may want to supply all the data at once or make appropriate selections from a list of items. you learned how to use the built-in InputBox function to collect single items of data from the user during the execution of your VBA procedure. Each Dialog object represents a built-in dialog box. you should spend some time learning how to take advantage of dialog boxes that are built into Excel and are therefore ready for you to use. you will design your own custom forms from scratch.Chapter 18 Using Dialog Boxes In Chapters 4 and 5. This chapter teaches you how to display the built-in dialog boxes from your VBA procedures. but how to call these dialog boxes from your own VBA procedures. I’m not talking about your ability to manually select appropriate options. EXCEL DIALOG BOXES Before you start creating your own forms. xlDialogDefineName. In Chapter 19. such as xlDialogClear. you can: Use the collection of built-in dialog boxes Create a custom form. . and xlDialogOptionsView. These built-in dialog boxes. If your procedure must collect data.

. the following statement displays the Fonts dialog box: Application.1.Show For example.Table 18. Frequently used built-in dialog boxes To display a dialog box. which is available in the Object Browser window after selecting the Excel library and searching for xlDialog.Dialogs(constant).Dialogs(xlDialogFont).Show Figure 18.1 shows a list of constants identifying Excel built-in dialog boxes. use the Show method in the following format: Application.

. Let’s practice displaying some of the Excel dialog boxes straight from the Immediate window. Please note files for the “Hands-On” project may be found on the companion CDROM. Constants prefixed with “xlDialog” identify Excel built-in dialog boxes.Figure 18.1.

type the following statement and press Enter: Application. type the following statement and press Enter: Application. 5. After displaying a built-in dialog box. Press Close to exit the Define Name dialog box. In the Immediate window. 3. 2.Show The above statement displays the Define Name dialog box where you can define a name for a cell or a range of cells. VBA will display the dialog box with its default settings.Show The above instruction displays the Format Cells dialog box with the Font tab active. you can select an appropriate option.xlsm. you can decide which initial setting the built-in dialog box will display when you show it from your VBA procedure. 6. and Excel will format the selected cell or range.Hands-On 18. 8. Open a new workbook and save it as C:\Excel2013_ByExample\Practice_ Excel18. . Although you can’t modify the looks or behavior of a built-in dialog box. 7. 4.Dialogs(xlDialogFont).Dialogs(xlDialogDefineName). In the Immediate window. Press Cancel to exit the Format Cells dialog box. Switch to the Visual Basic Editor window and open the Immediate window. In the Immediate window.Show The above instruction displays the Fonts dialog box. Using Excel Dialog Boxes from the Immediate Window 1. or the entire sheet.1. If you don’t change the initial settings. Press Cancel to exit the Fonts dialog box.Dialogs(xlDialogFontProperties). type the following statement and press Enter: Application.

9. the Contents option button is selected when Excel displays this dialog box. But what if you wanted to invoke this dialog with . Type the following statement in the Immediate window and press Enter: Application. Contents.Dialogs(xlDialogClear).Dialogs(xlDialogOptionsView). 10. In the Immediate window.Show The above instruction opens the Excel Options dialog box with the Advanced options displayed. 11. The advanced settings available in the Excel Options dialog box are identified by the xlDialogOptionsView constant. and Comments. Formats. Press Cancel to exit the Excel Options dialog box. type the following statement and press Enter: Application. Figure 18.2. Normally.2. as shown in Figure 18.Show Excel shows the Clear dialog box with four option buttons: All.

type the following instruction in the Immediate window and press Enter: Application. Microsoft Excel built-in dialog box arguments list.15). Contents = 3.3.com/enus/library/office/ff838781(v=office. To display the Fonts dialog box in which the Arial 14-point font is already selected.Dialogs(xlDialogFont). 13. . and Hyperlinks = 5.Dialogs(xlDialogClear). Arguments are entered after the Show method.3). to display the Clear dialog box with the first option button (All) selected. Comments = 4. you can include a list of arguments.Show 1 Excel often numbers the available options.microsoft. The built-in dialog box argument lists are available at http://msdn.Show "Arial". Therefore. Application. 12. 14 14. Press Cancel to close the Fonts dialog box. Formats = 2. Figure 18. All = 1. For example.a different option selected as the default? To do this. you would enter the following statement.aspx (see Figure 18. Press Cancel to close the Clear dialog box.

"=$A$1" The above statement displays the Define Name dialog box. . Because the FileDialog object is a part of the Microsoft Office 15.Dialogs(xlDialogFont). it is available to all Office applications. Using the FileDialog Object from the Immediate window 1. Press Cancel to close the File Open dialog box. 17.2. enter a comma in the position of the first argument: Application. Let’s practice using the FileDialog object from the Immediate window. To display the File Open dialog box. FILE OPEN AND FILE SAVE AS DIALOG BOXES FileDialog is a very powerful dialog object.Show "John". Press Cancel to close the Fonts dialog box. type the following statement in the Immediate window and press Enter: Application. You can also use two methods of the Application object (GetOpenFilename and GetSaveAsFilename) to display File Open and File Save As dialog boxes without actually opening or saving any files (this is discussed later in this chapter). enters “John” in the Names in workbook text box. To specify only the font size. Type the following instruction in the Immediate window and press Enter: Application. Hands-On 18. and places the reference to cell A1 in the Refers to box.15.FileDialog(msoFileDialogOpen).Dialogs(xlDialogDefineName).Show 2. 18. The Show method returns True if you click OK and False if you cancel. 8 16.Show .0 object library. This object allows you to display the File Open and File Save As dialog boxes from your VBA procedures. Press Close to close the Define Name dialog box.

The Browse dialog box lets users select one or more files. Press Cancel to close the File Save dialog box.Show Excel displays a dialog box with a list of directories.3. type the following statement and press Enter: Application.FileDialog(msoFileDialogFolderPicker). 6. To display the File Save As dialog box. Let’s take a quick look at these dialog boxes. 5. In addition to File Open and File Save As dialog boxes.4.Show Figure 18.FileDialog(msoFileDialogFilePicker). and shows Browse in the titlebar.4: Application. This dialog box displays a list of files and folders. the FileDialog object is capable of displaying a dialog box with a list of files or a list of files and folders. . 7.FileDialog(msoFileDialogSaveAs). Press Cancel in the dialog box to return to the Immediate window. Type the following statement in the Immediate window and press Enter: Application.Show 4. Type the following statement in the Immediate window and press Enter to display the Browse dialog box shown in Figure 18.

2. You can control the types of files that are displayed in this window via the dropdown box located to the right of the File name drop-down box.2. If the filter you need is not listed in the Open dialog. Filters are stored in the FileDialogFilters collection for the FileDialog object. you can add it to the filters list. you will create a simple procedure that returns the list of default file filters to an Excel worksheet. The constants that the FileDialog object uses are listed in Table 18. Table 18.xlsm) project and rename it DialogBoxes. In the Project Explorer window. Excel displays the Open dialog box listing all Excel files. Hands-On 18. 2.8. FileDialog object’s constants FILTERING FILES When you choose File | Open.3. 3. or you can do this programmatically by using the Filters property. Writing a List of Default File Filters to an Excel Worksheet 1. Insert a new module into the VBA_Dialogs (Practice_Excel18. In the Properties window. rename the project VBA_Dialogs. Press Cancel in the dialog box to return to the Immediate window. The “mso” prefix denotes that the constant is a part of the Microsoft Office object model. select VBAProject (Practice_Excel18. In the following Hands-On.xlsm). .

5.Count For Each fltr In fdf Selection.Filters Workbooks. . Next. 0). 0). The fdf object variable returns a reference to the FileDialogFilters collection of the FileDialog object.Offset(1. In the DialogBoxes Code window.Offset(1. and the fltr object variable stores a reference to the FileDialogFilter object.Select Next MsgBox c & " filters were written to a worksheet.Add Cells(1. When the procedure completes. the procedure iterates through the FileDialogFilters collection and retrieves the description and extension of each defined filter. The Count property of the FileDialogFilters collection returns the total number of filters." End With End Sub The above procedure declares two object variables. 1). Run the ListFilters procedure.Select Selection.Formula = "List of Default filters" With fdf c = .Formula = fltr. enter the ListFilters procedure as shown below: Sub ListFilters() Dim fdf As FileDialogFilters Dim fltr As FileDialogFilter Dim c As Integer Set fdf = Application.Description & _ ": " & fltr.FileDialog(msoFileDialogOpen). you should see a list of preset filters in the worksheet of a new workbook.Extensions Selection.4.

tmp) has indeed been added to the list of filters in the drop-down list.Add "Temporary Files".Add Cells(1.Select Next MsgBox c & " filters were written to a worksheet. The following modified ListFilters procedure (ListFilters2) demonstrates how to add a filter to filter out temporary files (*." & vbCrLf _ & "Check for yourself. 0). Sub ListFilters2() Dim fdf As FileDialogFilters Dim fltr As FileDialogFilter Dim c As Integer Set fdf = Application.Count MsgBox "There are now " & c & " filters.FileDialog(msoFileDialogOpen).Extensions Selection.Using the Add method of the FileDialogFilters collection.Formula = fltr.tmp".Show . 1 c = . 0).Formula = "List of Default filters" With fdf c = .Count For Each fltr In fdf Selection. you can easily add your own filter to the default filters. 1).Select Selection.Offset(1. "*.Filters Workbooks.FileDialog(msoFileDialogOpen). The last statement in this procedure will open the File Open dialog box so that you can check for yourself that the custom filter Temporary files (*." Application.tmp)." .Offset(1.Description & _ ": " & fltr.

End With End Sub You can remove all the preset filters using the Clear method of the FileDialogFilters collection. The user will be allowed to select more than one file.FileDialog(msoFileDialogOpen) With fd . SELECTING FILES When you select a file in the Open File dialog box.tmp). For example. and the first filename will be highlighted. In the DialogBoxes module Code window. the selected filename and path is placed in the FileDialogSelectedItems collection. The selected files will then be loaded into the listbox control. a user can select one or more files by holding down the Shift or Control keys while clicking filenames.4. The following procedure demonstrates how to use the above-mentioned properties. Use the SelectedItems property to return the FileDialogSelectedItems collection. enter the ListSelectedFiles procedure as shown below: Sub ListSelectedFiles() Dim fd As FileDialog Dim myFile As Variant Dim lbox As Object Application. Loading Files into a Worksheet Listbox Control 1.Filters. Hands-On 18. This procedure will open a new workbook and insert a listbox control.FileDialog(msoFileDialogOpen). you could modify the ListFilters2 procedure to clear the built-in filters prior to adding the custom filter—Temporary files (*.Cl Set fd = Application. By setting the AllowMultiSelect property of the FileDialog object to True.

Add Set lbox = Worksheets(1).Formula = _ "You’ve selected the following " & _ lbox. This method does not open the files selected by the user.ListCount & " files:" lbox. Top:=60.ListIndex = 1 End If End With End Sub The above procedure uses the following statement to clear the list of filters in the File Open dialog box to ensure that only the preset filters are listed: Application.Shapes. _ Left:=20.Show Then Workbooks.FileDialog(msoFileDialogOpen) Prior to displaying the File Open dialog box. we set the AllowMultiSelect property to True so that users can select more than one file.ControlFormat. .SelectedItems lbox. the reference to the FileDialog object is stored in the object variable fd: Set fd = Application. Next.AllowMultiSelect = True If .ControlFormat. the names of the files are retrieved from the SelectedItems collection via the SelectedItems property and placed in a listbox on a worksheet. When the user clicks the Open button. Width:=300) lbox.Clea Next.ControlFormat. the Show method is used to display the File Open dialog box. _ AddFormControl(xlListBox.MultiSelect = xlNone For Each myFile In .AddItem myFile Next Range("B4").FileDialog(msoFileDialogOpen).Filters.. Height:=40.ControlFormat.

The selected files are not opened.5). select a couple of files (hold down the Shift or Ctrl key to choose contiguous or nonadjacent files).5. Sub OpenRightAway() Dim fd As FileDialog Dim myFile As Variant Set fd = Application. The procedure simply loads the names of the files you selected in a listbox control that has been added to a worksheet (see Figure 18. User-selected files are loaded into a listbox control placed in a worksheet by the ListSelectedFiles procedure. Figure 18. The OpenRightAway procedure shown below demonstrates how to open the user-selected files right away. If you’d like to immediately carry out the File Open operation when the user clicks the Open button.FileDialog(msoFileDialogOpen) With fd . switch to the Excel2013_ByExample folder. you must use the Execute method of the FileDialog object.AllowMultiSelect = True If .Show Then . When the File Open dialog box appears on the screen. and then click Open.2. Run the ListSelectedFiles procedure.

The GetSaveAsFilename method shows the Save As dialog box.For Each myFile In .SelectedItems .Execute Next End If End With End Sub GETOPENFILENAME AND GETSAVEASFILENAME METHODS For many years now. where you can select the name of a file to open. The most often used are the first and third arguments. The GetOpenFilename method gets a filename from the user without actually opening the specified file.GetOpenFilename The above statement displays the Open dialog box where you can select a file. This method has four optional arguments. The GetOpenFilename method displays the Open dialog box.5. Arguments of the GetOpenFilename method . Table 18. shown in Table 18. Type the following statement in the Immediate window and press Enter: Application. These methods are available only in Excel and can still be used in Excel 2013 if backward compatibility is required. Hands-On 18. Excel has offered its programmers two handy VBA methods for displaying the File Open and File Save As dialog boxes: GetOpenFilename and GetSaveAsFilename. Let’s try out these methods from the Immediate window. Using the GetOpenFilename Method Let’s open a file using the GetOpenFilename method.3. Using the GetOpenFilename Method 1.3.

.GetOpenFilename("excel macroenabled files( " & _ "*. Notice that Excel did not open the selected file.GetOpenFilename This statement displays the Open dialog box. 5. All it did is remember its name in the yourFile variable. To see how arguments are used with the GetOpenFilename method. Let’s check this out. In the Immediate window. Let’s see how this is done. enter the following statement in the Immediate window (be sure to enter it on one line and press Enter): Application.xlsm"). The file you select while this dialog box is open will be stored in the yourFile variable. 6. *. The GetOpenFilename method returns the name of the selected or specified file. type the following statement and press Enter: yourFile = Application. Select an Excel file and click Open. 3. Click Cancel to close the dialog box opened in Step 3. Click Cancel to close the dialog box opened in Step 1. This name can be used later by your VBA procedure to open the file.."Highlight the File" Notice that the Open dialog box now has the text “Highlight the File” in the titlebar. Also. 4.xlsm).2. the Files of type drop-down listbox is filtered to display only the specified file type.

2.GetSaveAsFilename The above statement displays the Save As dialog box. 9. type the following statement and press Enter: ?yourFile Excel prints the name of the selected file in the Immediate window. 8.Open Filename:=yourFile Notice that the file you picked is now opened in Excel. type the following statement and press Enter. type the following statement and press Enter: Workbooks. Using the GetSaveAsFilename Method Now that you know how to open a file using the GetOpenFilename method. Open a new workbook and switch to the Visual Basic Editor window. let’s examine a similar method that allows you to save a file. Now that you have a filename you can write a statement to actually open this file (see the next step). Close the file you opened in Step 8. The GetOpenFilename method returns False if you cancel the dialog box by pressing the Esc key or clicking Cancel. Hands-On 18. Using the GetSaveAsFilename Method 1. We will continue to work in the Immediate window. yourFile = Application. In the Immediate window. The suggested filename .6.7. In the Immediate window. In the Immediate window.

we have saved it with the “xlsx” extension instead of using the macroenabled file format (xlsm). as demonstrated in the next step..xlsx".xlsx.xlsx".xlsx in the File name box and click Save. type the following statement in the Immediate window and press Enter: Workbooks("Test1. type the following statement and press Enter: ActiveWorkbook. you can specify the filename. 4.xlsx file. the GetSaveAsFilename method will store the filename and its path in the yourFile variable. In the Immediate window. Type Test1. When using the GetSaveAsFilename method."Name of your file") CHAPTER SUMMARY . file filter.xlsx).xlsx"). 5. You can check out the value of the yourFile variable in the Immediate window by entering the following statement and pressing Enter: ?yourFile To actually save the file you have to enter a different statement.SaveAs yourFile Now the workbook file opened in Step 1 has been saved as Test1. *. The filename that the user enters in the File name box will be stored in the yourFile variable. To close the Test1. The GetSaveAsFilename method is convenient for obtaining the name of the file the workbook should be saved as. and custom title for the dialog box: yourFile = Application.GetSaveAsFilename("Test1. 3. When you click the Save button.Close Because the file we are working with does not contain any VBA code. _ "Excel files(*.is automatically entered in the File name box at the bottom of this dialog box.

You ended this chapter by familiarizing yourself with older methods of displaying the File Open and File Save As dialog boxes that you will encounter often in VBA procedures written in older versions of Excel. You also learned how to select files by using the FileDialog object. . In the next chapter. you will learn how to create and display your custom dialog boxes with user forms. you learned how to use VBA statements to display various built-in dialog boxes.In this chapter.

if you’re looking to provide a custom interface. For example. and write VBA procedures that respond to form and control events. Press Alt-F11 or select Developer | Visual Basic to switch to the Visual Basic Editor window. . which ones to remove. 2. Forms are separate objects that you add to a VBA project by choosing Insert | UserForm from the Visual Basic Editor. and which ones to move around. you can’t control the dialog box’s appearance. CREATING FORMS A user form is like a custom dialog box. A new folder called Forms appears in the Project Explorer window. Forms can be shared across applications. To create a custom form. Therefore. Apart from displaying a dialog box on the screen and specifying its initial settings. Choose Insert | UserForm. the built-in dialog boxes will not meet all of your VBA application’s requirements. you can’t change the size of a built-in dialog box. Also.1). The work area automatically displays the form and the Toolbox with the necessary tools for adding controls (see Figure 19. This folder contains a blank UserForm object. You can add various controls to the form. you can reuse the form you designed in Microsoft Excel in Microsoft Word or any other application that uses Visual Basic Editor.Chapter 19 Creating Custom Forms Although ready to use and convenient. you need to create a user form. follow these steps: 1. set properties for these controls. You can’t decide which buttons to add.

After adding a new form to your VBA project. Behavior.1.1) displays seven properties that you can set: Appearance. The Properties window (see Figure 19. Before dragging a form to a different VBA application. Misc. Font. A new form can be added to the open VBA project by selecting UserForm from the Insert menu. and Scrolling. All VBA applications that use the Visual Basic Editor share features for creating custom forms. click the property name and press F1. .Figure 19. You can also set the form’s title by using the Caption property. Picture. Position. To import or export a form file. You can share your forms by exporting and importing form files or by dragging a form object to another project. click the Categorized tab in the Properties window. Before you export a form file. choose File | Import File or File | Export File. you should assign a unique name to it by setting the Name property. The online help will be launched with the property description topic. To list form properties by category. To find out information about a specific property. be sure to select it in the Project Explorer window.

These controls can respond to specific user actions. you insert appropriate controls on it to make it useful.2) contains standard Visual Basic buttons for all the controls that you can add to a form. such as clicking a control or changing its value. then drop the form on the name of another project in the Project Explorer. Controls available in the Toolbox are known as ActiveX controls.arrange the VBE windows so that you can see the Project Explorer window in both applications. The Toolbox (Figure 19. TOOLS FOR CREATING USER FORMS When you design a form. . It may also contain additional controls that have been installed on your computer.

.Figure 19. If you have other applications installed on your computer that contain ActiveX controls that you’d like to use. Let’s take a few minutes and add a Date and Time Picker ActiveX control to the Toolbox. The Toolbox displays the controls that can be added to your custom form. You will learn how to use the Toolbox controls throughout the remaining sections of this chapter.2. you can also place them in the Toolbox.

If this option is not available.1.xlsm. In the Caption box. make sure you are right-clicking the New Page tab. 9. Choose Insert | UserForm to add a new form to the selected project. Right-click the Controls tab in the Toolbox and choose New Page from the shortcut menu. make sure you are right- . Right-click anywhere within the new page area and choose Additional Controls from the shortcut menu. Click OK to return to the Toolbox. Please note files for the “Hands-On” project may be found on the companion CDROM. type the following description: A dditional ActiveX Controls. Hands-On 19. 4. 3.0 located in the MSCOMCT2. Use the Properties window to rename the project VBA_Forms. Open a new workbook and C:\Excel2013_ByExample\Practice_Excel19.OCX file. 8. In the Control Tip Text box. 1. A New Page tab appears in the Toolbox. Adding an ActiveX Date and Time Picker Control to the Toolbox. A default user form named UserForm1 appears with the accompanying Toolbox. save it as 2. type Extra Controls as the new name. 7.xlsm) in the Project Explorer window.This control is one of several controls included in the Microsoft Windows Common Controls 6. 5. If this option is not available. Switch to the Visual Basic Editor window and select VBAProject (Practice_Excel19. Right-click the New Page tab in the Toolbox and choose Rename. 6.

3). The DTPicker control now appears on the Extra Controls page in the Toolbox (see Figure 19.3. Figure 19. 11. You will use many of these controls in this chapter’s Hands-On projects.0. 10. Use it to resize or move a control that has already been drawn on a form. The standard Visual Basic controls are described below. as shown in Figure 19. Click OK to close the Additional Controls dialog box. Select Objects Select Objects is the only item in the Toolbox that doesn’t draw a control. .clicking the page area in the Toolbox and not the Extra Controls tab itself. When the Additional Controls dialog box appears.3. You can add to the Toolbox additional ActiveX controls that are installed on your computer. click the checkbox next to Microsoft Date and Time Picker Control 6.

If you want to limit the number of characters the user can enter in a text box. EnterFieldBehavior. Setting this property to 1 (fmEnterFieldBehaviorRecallSelect) will only select the text that the user selected the last time he activated this field. by pressing Alt and a specified letter. By changing the setting of the MultiLine property. The text lines can automatically wrap when you set the WordWrap property. You will learn how to use the Tab Order dialog box later in this chapter (see Figure 19. Text Box Text boxes are the most popular form controls because they can be used to either display or request data from the user. Another property. you can do this by specifying the exact number of characters in the MaxLength property. Frame . To add a title or a keyboard shortcut to an existing control. choose View | Tab Order. you can enter more than one line of text in a text box. you can activate the control that was added to the form immediately after adding the Label control and setting its Accelerator property. numbers. listboxes. titles.6). You can use the label to assign a title to those controls that don’t have the Caption property (for example. Next. You can define an accelerator (shortcut) key for the label. and explanations to your forms. or formulas in them. Setting this property to 0 (fmEnterFieldBehaviorSelectAll) will select the text within the field. For example. you’ll be able to start a new line in the text box by pressing Enter. and make sure that the name of the label appears before the name of the control that you want to activate with the assigned keyboard shortcut. determines whether the text is selected when the user selects the text field. You can enter text. add a Label control and type a letter from its caption in its Accelerator property in the Properties window. headings. and spin buttons). If you set the EnterKeyBehavior property to True when the MultiLine property is also set to True. cell references. scrollbars.Label The Label control is often used to add captions. text boxes.

you will learn how to execute VBA procedures from command buttons. Check Box Checkboxes are used for turning specific options on and off. True means that the option is activated. Toggle Button A toggle button looks like a command button and works similarly to an option . the previously selected option button is automatically deselected. its Value property is set to False. you can select one or more checkboxes.Frames allow you to visually organize and logically group various controls placed on the form. Unlike option buttons. False indicates that the option is deactivated. To activate or deactivate an option button. If the checkbox is selected. set its Value property to True or False. if the checkbox is not selected. its Value property is set to True. Only one option button can be selected. Command Button A command button carries out a command when it is clicked. When you select a new option button.4). the second frame groups the checkboxes related to the computer type (see Figure 19. Option Button An option button lets you select one of a number of options. you will find an example of the Info Survey form that uses two frames. One of them organizes Hardware and Software option buttons into one logical group. In this chapter. Later in this chapter. Option buttons usually appear in groups of two or more buttons surrounded by a frame control.

the button stays pressed. The pressed toggle button has its Value property set to True. The user may enter a new value if you set the MatchRequired property to False. The user may select more than one item in the listbox if the MultiSelect property set to True. sometimes it’s better to present a list of available choices from which to select. The next click on the button returns it to the normal (unpressed) state. ColumnHeads. The listbox can display one or more columns when you set the ColumnCount property. can be set to True to display the column titles in the listbox. Another property. The unpressed toggle button has its Value property set to False. Combo Box The combo box is a control that combines a text box with a listbox.button. the reference $A$1: $B$8 will display in the listbox the contents of the specified range of cells. The listbox reduces the possibility of data entry errors. When you click a toggle button. The RowSource property indicates the source of data displayed in the listbox. For example. To let the user select an item from the list. Set the Style property to 2 (fmStyleDropDownList) to limit the user’s selection to the items available in the combo box. Listbox Instead of prompting the user to enter a specific value in a text box. the box will drop open to reveal a number of items from which to choose. use 0 (fmStyleDropDownCombo). When the user clicks the down arrow located to the right of the combo box. The Style property determines the type of combo box. The listbox entries can be typed in a worksheet. The ListRows property determines how many items will appear when the user drops down the list. This control is often used to save space on the form. . or they can be loaded directly from a VBA procedure using the AddItem method.

This property has three settings:0 (fmPictureSizeModeClip) crops the part of a picture that does not fit within the picture frame: 1 (fmPictureSizeModeStretch) stretches the picture horizontally or vertically until it fills the entire frame area. *.wmf. The Min property determines the minimum value.bmp. Image Control The image control lets you display a graphical image on a form. The user can then type the exact value in the text box or select a value by using the arrows. *. This control supports the following file formats: *.jpg. You can click an arrow to increment or decrement a value. Like other controls in the Toolbox. *.cur. Although normally used to navigate windows. For example.Scrollbar This control allows you to place horizontal and vertical scrollbars on your form. Spin Button The spin button works similarly to a scrollbar. scrollbars can be used on your form to enter values in a predefined range. The scrollbar’s Max property lets you set its maximum value. The current value of the scrollbar is set or returned by the Value property. The LargeChange property determines by what value the Value property should change when the user clicks inside the scrollbar. The spin button is often used with a text box. don’t forget to set the SmallChange property that determines how the Value property changes when you click one of the scroll arrows. 3 (fmPictureSizeModeZoom) enlarges the picture without distorting its . and *. the image control has a number of properties that you can set. *gif. you can control the appearance of the picture with the PictureSizeMode property.ico. The technique of using the spin button with a text box is discussed later in this chapter. When programming the behavior of the scrollbar.

See Hands-On 19. You can place a different set of controls on each form page to make the data more readable. Each subject can be placed on a separate page (tab). It’s much easier to click a form tab than move around in a long form using scrollbars.proportions. Only the data in these controls will change. By default. and each tab will contain the same controls to collect data. The TabStrip (see Figure 19. For example. TabStrip Control Although the TabStrip and MultiPage controls look almost alike. Using the MultiPage control. Each tab acts as a separate page. When you activate any subject tab. each MultiPage control appears on your form with two pages. each has a different function. The last Hands-On exercise in this chapter demonstrates how to use this control to keep track of students’ exam grades. as it allows you to select a cell or a range of cells in a worksheet and pass it to your VBA procedure. Suppose that the form shows students’ exams. you will see the same controls. New pages can be added by using the shortcut menu or the Add method from within a VBA procedure. you can design forms that contain two or more pages. You can see how this control works by taking a look at some of the built-in dialog boxes in Excel. such as the grade received and the date of the exam. Each student has to pass an exam in the same subjects.10) lets you use the same controls for displaying multiple sets of the same data.16 for an example of how to use the TabStrip control. the Consolidate dialog box accessed from the Data tab’s . RefEdit Control This control is specific to forms created in Microsoft Excel.9). MultiPage Control The MultiPage control displays a series of tabs at the top of the form (see Figure 19.

2. PLACING CONTROLS ON A FORM When you create a custom form. The Form Grid Settings area lets you turn off the grid. SAMPLE APPLICATION 1: INFO SURVEY . Visual Basic adjusts the control so that it aligns with the form’s grid. The Toolbox display can be toggled on and off by choosing View | Toolbox. double-click the text box control in the Toolbox and then click three times on the form. you place various controls that are available in the Toolbox on an empty form. To access grid options: 1. the Select Object button (represented by the arrow) becomes the active control in the Toolbox. For example.You can also change its size. click the button on the right of the RefEdit control. first click the control image in the Toolbox and then click the form or draw a frame. The type of control you select depends on the type of data the control will have to store and the functionality of your form. Choose Tools | Options. To add a new control to a form. adjust the grid size. You can set the grid to your liking by using the Options dialog box.Data Tools group has a RefEdit control labeled Reference that lets you specify the range of data that you want to consolidate. For example. The standard settings of each control can be looked up in the Properties window. Clicking on a form (without drawing a frame) will place a control in its default size. the standard text box size is 18 x 72 points (see the Height and Width properties of the text box). and decide whether you want the controls aligned to the grid. The Toolbox can be moved around on the screen. Click the General tab in the Options dialog box. To temporarily hide the dialog box while selecting a range of cells. Setting Grid Options When you drag a control on a form. or close it when all controls are already on the form and all you want to do is work with their properties. After placing a control on a form. to quickly place three text boxes on your form. you can draw as many instances of that control as you want. When you double-click a control in the Toolbox.

you will create a custom form for a coworker who requested that you streamline the tedious process of entering survey data into a spreadsheet. . While working with this form (Figure 19. The Info Survey custom form allows the user to quickly enter data by making appropriate selections from various controls placed on the form. Figure 19. Also. you will learn how to transfer data from your custom form to a worksheet (Figure 19.5).4.4). In this section. the best way to understand a complex feature is to apply it in a real-life project. you will have the chance to experiment with many controls and their properties.As you already know.

1d): Adjust other properties of the form and its controls.1b): Adjust the size of the form so that all controls required by the application can be easily placed on the form and the form does not look crowded. Step 4 (Custom Project 19.Figure 19. 4. Each time the Info Survey form is used. The tasks listed below are described in Custom Project 19. 3. .5.1c): Place the required controls on the form. Setting Up the Custom Form Before you can begin programming.1: 1.1e): Set the tab order of the controls on the form. Step 2 (Custom Project 19. Step 3 (Custom Project 19. 5. Step 5 (Custom Project 19. 2. you need to perform several tasks. the user’s selections are written to the worksheet.1a): Insert a new form into your VBA project and set up this form’s initial properties like the Name and Caption properties that will allow you to identify the form. Step 1 (Custom Project 19.

Double-click the Caption property and type the new title for the form: Info Survey The name Info Survey will appear in your form’s titlebar. Step 9 (Custom Project 19. Step 10 (Custom Project 19.6. 3. In the Properties window. 2. Step 7 (Custom Project 19.1g): Display the completed custom form. 10.1h): Write a procedure to initialize the form. 8.xlsm) project. Step 14 (Custom Project 19. Step 6 (Custom Project 19. 13. .1n): Start using the completed InfoSurvey application. 14. double-click the Name property and type InfoSurvey to change the default form name. Hands-On 19.1m): Write a procedure that transfers data to a worksheet. Inserting a New Form and Setting Up the Initial Properties Follow the step below to get started with the Info Survey application.1a. Cho o s e Insert | UserForm to add a blank form to the VBA_Forms (Practice_Excel19. 7.1i): Write a procedure that populates the listbox control. Step 12 (Custom Project 19. 9. 12.1k): Write a procedure that synchronizes text box with the spin button control. Step 8 (Custom Project 19.1l): Write a procedure that closes the form. 11. Step 13 (Custom Project 19. Step 11 (Custom Project 19.1j): Write procedures that control option buttons.1f): Prepare a worksheet to receive the data. Inserting a New Form (Step 1) 1. We will use this name later on to refer to this UserForm object in VBA procedures.

we need to adjust the size of the form so that all the controls that we need to place on this form will fit nicely. Place the mouse pointer over any selection handle located in the middle of a side. you can change its size by using the mouse or by setting the form properties in the Properties window. Changing the Size of the Form When a default form inserted in your project is too large or too small to fit all the controls properly. In the Properties window. To avoid extra work. double-click the Height property and enter a new value. Do the same for the Width property if you need to adjust the form’s width as well. click the Palette tab. Release the mouse button. Click in the form’s title bar. One point equals 1/72 inch. Double-click the BackColor property. and then release the mouse button. and select a color for the form background. you will need to enter new values for the form’s Height and Width. figure out how much space you really need and resize the form before adding the desired controls. You can also place the mouse pointer over the selection handle located at the undocked corner and drag the handle to the position you want. To resize the form using the Properties window. Adjusting the Size of the Form (Step 2) . To resize the form with the mouse. click on an empty part of the form. The form’s dimensions are in points. drag the handle to the position you want. Hands-On 19. Notice that several selection handles appear around the form. After setting the initial properties for our custom form Info Survey. Each new form has a default size of 180 x 240.4.1b.

1. Point to the upper left-hand side of the form. Frame1. various selection handles will appear in its sides.75. and Other Controls to a Form Now we are ready to proceed with placing the required controls on the Info Survey form. In the Properties window. The mouse pointer changes to a cross accompanied by the symbol of the selected control. Adding Buttons. Click the Frame control in the Toolbox. In the Properties window. Hands-On 19. Checkboxes.4. double-click the Height property and enter the value 252. Checkboxes. centering a control horizontally or vertically. Click the form’s titlebar (where the words “Info Survey” appear). then click and drag the mouse to draw a small rectangle. such as making controls the same size. aligning control edges. Next. click inside the Main Interest frame that you’ve just added to your form. We will model this form after Figure 19. with Main Interest. 4. and Other Controls to a Form (Step 3) 1. you will see a small rectangle titled Frame1. In the Properties window. double-click the Width property and enter the value 405. When the frame is selected. 3. Click and drag the mouse to . The UserForm toolbar contains a number of useful shortcuts for working with forms. 3.75.1c. Adding Buttons. double-click the Caption property and replace the selected default caption. and grouping and ungrouping controls. and the Properties window’s titlebar will display Properties-Frame1. Click the Option Button control in the Toolbox. 2. 2. When you release the mouse button. choose View | Toolbars | UserForm. To display this toolbar.

The checkbox can be checked. 7. change the option button’s Caption property to Hardware. Change the Caption property of this option button to Software. 6. The option buttons are used whenever the user has to select one choice from a group of mutually exclusive choices. The mouse pointer will change to a cross accompanied by the symbol of the selected control. Add two option buttons inside this frame. 8. Insert a frame below the listbox. Click the Frame control in the Toolbox and draw a rectangle to the right of the frame labeled Main Interest. which are mutually exclusive. Use the Caption property to assign the following titles to these checkboxes: Notebook/Laptop and Macintosh. checkboxes allow the user to activate one or more options simultaneously. Click the Check Box control in the Toolbox. 12.4. 14. Unlike option buttons.4). Click the List Box control in the Toolbox. 13. checkboxes are used. 5. Figure 19. If the user can select more than one choice. Change the Caption property of the CheckBox1 control to IBM/Compatible. and click inside the empty frame that you have just added. and change the first button’s Caption property to Male and the second one to Female (see Figure 19. The CheckBox1 control should appear inside the frame. or unavailable at a particular time.the right until you see a rectangle with the default label OptionButton1. 9. Use the method presented in Step 4 to add another option button to the Main Interest frame. unchecked. Change the frame’s Caption property to Gender. you will see a white rectangle. The checked box . Change the Caption property of the new frame to Computer Type. and drag the mouse down and to the right to draw a listbox. Place two more checkboxes inside the frame labeled Computer Type. In the Properties window.4 shows the listbox populated with hardware entries. Click below the Main Interest frame. When you release the mouse button. An unavailable checkbox has its label grayed out and is therefore inactive (cannot be selected). 11. The final result should match Figure 19. 10.

A text box is . Use checkboxes to have the user select any number of options that apply. 17. Click the Spin Button control in the Toolbox. Click on the empty part of the form just below the Used at combo box. Click the Label control in the Toolbox. The spin button has the same properties as the scrollbar. Click the empty space below the frame labeled Computer Type. 24. 21. and it lacks the LargeChange property. A default size spin button will appear. The Label1 control should appear. Click the Combo Box control in the Toolbox. 23. Although the user can only see one element of the list at a given time. 19. 20. 16. and the minimum value is set with the Min property. Click the Text Box control in the Toolbox. Click the empty space below the Used at label and drag the mouse to draw a rectangle. Use option buttons when only one option can be selected at a given time. the current selection can be quickly changed by clicking on the arrow button. 15. The combo box is sometimes referred to as a drop-down list and is used to save valuable space on the screen. 18. The maximum value is determined by the setting of the Max property. and then click to the right side of the text box control. Release the mouse button. Click the Label control in the Toolbox. Click to the right of the Percent (%) Used label control to place a default size text box. Change the Caption property of Label1 to Used at. The checkbox that has the focus is indicated by a dotted line around the caption. with two differences.has an x in front of its caption. Change the Caption property for this label to Percent (%) Used. A label control will appear. The final result is shown in Figure 19. The combo box displays a list of available choices only after you click the down arrow placed at the right of this control.4. The spin button does not have a scroll box. The spin button has two arrows that are used to increment or decrement a value in a given range. 22.

and repeat Steps 31 and 32. 30. or click on any empty area of the form to select it. 27. Click the mouse below the Cancel button. you indicate that you want to create more than one control using the selected tool. The images will be loaded by a VBA procedure. Most custom forms have two command buttons. 31. 25. . Change the Caption property of CommandButton1 to OK and CommandButton2 to Cancel. To make the buttons respond to user actions. In this example. The user will be able to click the Cancel button when he’s done inputting the data. the OK button will transfer the data entered on the form to a worksheet. and drag the mouse to draw a rectangle. Click the titlebar. CommandButton2 will appear. 28.usually placed next to the spin button. you will write appropriate VBA procedures later in this chapter. If the spin button has to work with the text box. Visual Basic switches to the active sheet in the Microsoft Excel window and displays the custom form you designed. Release the mouse button. Press F5 or choose Run | Run Sub/UserForm to display the form as the user will see it. which enable the user to accept the data entered on the form or dismiss the form. 32. The final result is shown in Figure 19. Click below CommandButton1. In this example.4. Double-click the Command Button control in the Toolbox. you will use the spin button to indicate the percent of interest that the user has in the selected hardware or software product. 29. OK and Cancel. 26. Click in the top right-hand corner of the form. Close the dialog box. If you forget to select the form. The form will display a different picture depending on whether the Hardware or Software option button is selected. This will cause CommandButton1 to appear. your VBA procedure must ensure that the value of the text box and the spin button are synchronized. Recall that by double-clicking the control in the Toolbox. This allows the user to enter a value directly into the text box or use the spin buttons to determine the value. the Macro dialog box will appear. Click the Image control in the Toolbox.

click the Select Objects tool in the Toolbox and start drawing a rectangle around the group of controls that you want to move together. For example. Click the Close button (x) in the top right-hand corner of the form to close the form and return to the Visual Basic Editor. use the mouse or the Format menu commands to adjust the alignment and spacing of the controls. Drag the pointer to the position you want. They require VBA procedures to make them work. Assigning meaningful names to the controls placed on your form makes VBA procedures referencing these controls much more readable. When you release the mouse button. here’s how you can quickly copy and move controls: To copy a control. (You can also select more than one control by holding down the Ctrl key while clicking each of the controls you want to select—don’t just read about it. Then change the control’s Caption property. and press the left mouse button. Note that the OK and Cancel buttons placed on the form aren’t functional yet. you should assign your own names to the controls. click the Select Objects tool in the Toolbox and select the control (a selected control will have handles at its sides). Changing Control Names and Properties After you have placed controls on your form but before you begin to write procedures to control the form. To select an entire group of controls. Before you change the Name property. and so on). The Info Survey form design is now completed. hold down the Ctrl key. click within the selected area and drag the mouse to the desired position. these names are difficult to distinguish in a procedure that may reference objects of the same class that have almost identical names. After you’ve added controls to the form.33. position the mouse pointer inside the control. and release the mouse button. Although Visual Basic automatically assigns a default name to each control (OptionButton1. When working with controls. From now on you should feel comfortable designing any form you want. try it now!) To move the selected group of controls to another position on the form. all the controls will be selected. it is worthwhile to learn some shortcuts. make sure that the titlebar of the . OptionButton2.

perform these steps: Click the appropriate control on the form. To assign a new name to a control. Naming Form Controls (Step 4) 1. Assign names to the controls placed on the Info Survey form as shown below. For example. . on the Info Survey form. When the Properties window displays “Properties-Frame1. Hands-On 19. the default name of the frame control is Frame1. it is the name of the control that will be used in the code of your VBA procedures to make things happen. The control’s title can be changed by setting the Caption property.Properties window displays the correct type of the control. For example. Double-click the Name property in the Properties window. While the control’s caption allows the user to identify the purpose of the control and may suggest the type of data ex