- •About the Author
- •About the Technical Editor
- •Credits
- •Is This Book for You?
- •Software Versions
- •Conventions This Book Uses
- •What the Icons Mean
- •How This Book Is Organized
- •How to Use This Book
- •What’s on the Companion CD
- •What Is Excel Good For?
- •What’s New in Excel 2010?
- •Moving around a Worksheet
- •Introducing the Ribbon
- •Using Shortcut Menus
- •Customizing Your Quick Access Toolbar
- •Working with Dialog Boxes
- •Using the Task Pane
- •Creating Your First Excel Worksheet
- •Entering Text and Values into Your Worksheets
- •Entering Dates and Times into Your Worksheets
- •Modifying Cell Contents
- •Applying Number Formatting
- •Controlling the Worksheet View
- •Working with Rows and Columns
- •Understanding Cells and Ranges
- •Copying or Moving Ranges
- •Using Names to Work with Ranges
- •Adding Comments to Cells
- •What Is a Table?
- •Creating a Table
- •Changing the Look of a Table
- •Working with Tables
- •Getting to Know the Formatting Tools
- •Changing Text Alignment
- •Using Colors and Shading
- •Adding Borders and Lines
- •Adding a Background Image to a Worksheet
- •Using Named Styles for Easier Formatting
- •Understanding Document Themes
- •Creating a New Workbook
- •Opening an Existing Workbook
- •Saving a Workbook
- •Using AutoRecover
- •Specifying a Password
- •Organizing Your Files
- •Other Workbook Info Options
- •Closing Workbooks
- •Safeguarding Your Work
- •Excel File Compatibility
- •Exploring Excel Templates
- •Understanding Custom Excel Templates
- •Printing with One Click
- •Changing Your Page View
- •Adjusting Common Page Setup Settings
- •Adding a Header or Footer to Your Reports
- •Copying Page Setup Settings across Sheets
- •Preventing Certain Cells from Being Printed
- •Preventing Objects from Being Printed
- •Creating Custom Views of Your Worksheet
- •Understanding Formula Basics
- •Entering Formulas into Your Worksheets
- •Editing Formulas
- •Using Cell References in Formulas
- •Using Formulas in Tables
- •Correcting Common Formula Errors
- •Using Advanced Naming Techniques
- •Tips for Working with Formulas
- •A Few Words about Text
- •Text Functions
- •Advanced Text Formulas
- •Date-Related Worksheet Functions
- •Time-Related Functions
- •Basic Counting Formulas
- •Advanced Counting Formulas
- •Summing Formulas
- •Conditional Sums Using a Single Criterion
- •Conditional Sums Using Multiple Criteria
- •Introducing Lookup Formulas
- •Functions Relevant to Lookups
- •Basic Lookup Formulas
- •Specialized Lookup Formulas
- •The Time Value of Money
- •Loan Calculations
- •Investment Calculations
- •Depreciation Calculations
- •Understanding Array Formulas
- •Understanding the Dimensions of an Array
- •Naming Array Constants
- •Working with Array Formulas
- •Using Multicell Array Formulas
- •Using Single-Cell Array Formulas
- •Working with Multicell Array Formulas
- •What Is a Chart?
- •Understanding How Excel Handles Charts
- •Creating a Chart
- •Working with Charts
- •Understanding Chart Types
- •Learning More
- •Selecting Chart Elements
- •User Interface Choices for Modifying Chart Elements
- •Modifying the Chart Area
- •Modifying the Plot Area
- •Working with Chart Titles
- •Working with a Legend
- •Working with Gridlines
- •Modifying the Axes
- •Working with Data Series
- •Creating Chart Templates
- •Learning Some Chart-Making Tricks
- •About Conditional Formatting
- •Specifying Conditional Formatting
- •Conditional Formats That Use Graphics
- •Creating Formula-Based Rules
- •Working with Conditional Formats
- •Sparkline Types
- •Creating Sparklines
- •Customizing Sparklines
- •Specifying a Date Axis
- •Auto-Updating Sparklines
- •Displaying a Sparkline for a Dynamic Range
- •Using Shapes
- •Using SmartArt
- •Using WordArt
- •Working with Other Graphic Types
- •Using the Equation Editor
- •Customizing the Ribbon
- •About Number Formatting
- •Creating a Custom Number Format
- •Custom Number Format Examples
- •About Data Validation
- •Specifying Validation Criteria
- •Types of Validation Criteria You Can Apply
- •Creating a Drop-Down List
- •Using Formulas for Data Validation Rules
- •Understanding Cell References
- •Data Validation Formula Examples
- •Introducing Worksheet Outlines
- •Creating an Outline
- •Working with Outlines
- •Linking Workbooks
- •Creating External Reference Formulas
- •Working with External Reference Formulas
- •Consolidating Worksheets
- •Understanding the Different Web Formats
- •Opening an HTML File
- •Working with Hyperlinks
- •Using Web Queries
- •Other Internet-Related Features
- •Copying and Pasting
- •Copying from Excel to Word
- •Embedding Objects in a Worksheet
- •Using Excel on a Network
- •Understanding File Reservations
- •Sharing Workbooks
- •Tracking Workbook Changes
- •Types of Protection
- •Protecting a Worksheet
- •Protecting a Workbook
- •VB Project Protection
- •Related Topics
- •Using Excel Auditing Tools
- •Searching and Replacing
- •Spell Checking Your Worksheets
- •Using AutoCorrect
- •Understanding External Database Files
- •Importing Access Tables
- •Retrieving Data with Query: An Example
- •Working with Data Returned by Query
- •Using Query without the Wizard
- •Learning More about Query
- •About Pivot Tables
- •Creating a Pivot Table
- •More Pivot Table Examples
- •Learning More
- •Working with Non-Numeric Data
- •Grouping Pivot Table Items
- •Creating a Frequency Distribution
- •Filtering Pivot Tables with Slicers
- •Referencing Cells within a Pivot Table
- •Creating Pivot Charts
- •Another Pivot Table Example
- •Producing a Report with a Pivot Table
- •A What-If Example
- •Types of What-If Analyses
- •Manual What-If Analysis
- •Creating Data Tables
- •Using Scenario Manager
- •What-If Analysis, in Reverse
- •Single-Cell Goal Seeking
- •Introducing Solver
- •Solver Examples
- •Installing the Analysis ToolPak Add-in
- •Using the Analysis Tools
- •Introducing the Analysis ToolPak Tools
- •Introducing VBA Macros
- •Displaying the Developer Tab
- •About Macro Security
- •Saving Workbooks That Contain Macros
- •Two Types of VBA Macros
- •Creating VBA Macros
- •Learning More
- •Overview of VBA Functions
- •An Introductory Example
- •About Function Procedures
- •Executing Function Procedures
- •Function Procedure Arguments
- •Debugging Custom Functions
- •Inserting Custom Functions
- •Learning More
- •Why Create UserForms?
- •UserForm Alternatives
- •Creating UserForms: An Overview
- •A UserForm Example
- •Another UserForm Example
- •More on Creating UserForms
- •Learning More
- •Why Use Controls on a Worksheet?
- •Using Controls
- •Reviewing the Available ActiveX Controls
- •Understanding Events
- •Entering Event-Handler VBA Code
- •Using Workbook-Level Events
- •Working with Worksheet Events
- •Using Non-Object Events
- •Working with Ranges
- •Working with Workbooks
- •Working with Charts
- •VBA Speed Tips
- •What Is an Add-In?
- •Working with Add-Ins
- •Why Create Add-Ins?
- •Creating Add-Ins
- •An Add-In Example
- •System Requirements
- •Using the CD
- •What’s on the CD
- •Troubleshooting
- •The Excel Help System
- •Microsoft Technical Support
- •Internet Newsgroups
- •Internet Web sites
- •End-User License Agreement
CHAPTER
Working with
Excel Events
In the preceding chapters, I presented a few examples of VBA eventhandler procedures. These procedures are the keys to making your Excel applications interactive. This chapter provides an introduction to the concept of Excel events and includes many examples that you can
adapt to meet your own needs.
Understanding Events
Excel can monitor a wide variety of events and execute your VBA code when a particular event occurs. This chapter covers the following types of events.
•Workbook events: These occur for a particular workbook. Examples include Open (the workbook is opened or created), BeforeSave (the workbook is about to be saved), and NewSheet (a new sheet is added). VBA code for workbook events must be stored in the ThisWorkbook code module.
•Worksheet events: These occur for a particular worksheet. Examples include Change (a cell on the sheet is changed), SelectionChange (the cell pointer is moved), and Calculate (the worksheet is recalculated). VBA code for worksheet events must be stored in the code module for the worksheet (for example, the module named Sheet1).
•Events not associated with objects: The final category consists of two useful application-level events: OnTime and OnKey. These work differently from other events.
IN THIS CHAPTER
Understanding events
Using workbook-level events
Working with worksheet events
Using non-object events
873
Part VI: Programming Excel with VBA
Entering Event-Handler VBA Code
Every event-handler procedure must reside in a specific type of code module. Code for workbooklevel events is stored in the ThisWorkbook code module. Code for worksheet-level events is stored in the code module for the particular sheet (for example, the code module named Sheet1).
In addition, every event-handler procedure has a predetermined name. You can declare the procedure by typing it, but a much better approach is to let the VB Editor do it for you, by using the two drop-down controls at the top of the window.
Figure 43.1 shows the code module for the ThisWorkbook object. Select this code module by double-clicking it in the Project window. To insert a procedure declaration, select Workbook from the objects list in the upper left of the code window. Then select the event from the procedures list in the upper right. When you do, you get a procedure “shell” that contains the procedure declaration line and an End Sub statement.
FIGURE 43.1
The best way to create an event procedure is to let the VB Editor do it for you.
For example, if you select Workbook from the objects list and Open from the procedures list, the VB Editor inserts the following (empty) procedure:
Private Sub Workbook_Open()
End Sub
Your event-handler VBA code goes between these two lines.
874
Chapter 43: Working with Excel Events
Some event-handler procedures contain an argument list. For example, you may need to create an event-handler procedure to monitor the SheetActivate event for a workbook. (This event is triggered when a user activates a different sheet.) If you use the technique described in the previous section, the VB Editor creates the following procedure:
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
End Sub
This procedure uses one argument (Sh), which represents the activated sheet. In this case, Sh is declared as an Object data type rather than a Worksheet data type because the activated sheet also can be a chart sheet.
Your code can, of course, make use of information passed as an argument. The following example displays the name of the activated sheet by accessing the argument’s Name property. The argument becomes either a Worksheet object or a Chart object.
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
MsgBox Sh.Name & “ was activated.”
End Sub
Several event-handler procedures use a Boolean argument named Cancel. For example, the declaration for a workbook’s BeforePrint event is
Private Sub Workbook_BeforePrint(Cancel As Boolean)
The value of Cancel passed to the procedure is FALSE. However, your code can set Cancel to TRUE, which cancels the printing. The following example demonstrates this:
Private Sub Workbook_BeforePrint(Cancel As Boolean)
Msg = “Have you loaded the 5164 label stock? “
Ans = MsgBox(Msg, vbYesNo, “About to print... “)
If Ans = vbNo Then Cancel = True
End Sub
The Workbook_BeforePrint procedure executes before the workbook prints. This procedure displays a message box asking the user to verify that the correct paper is loaded. If the user clicks the No button, Cancel is set to TRUE, and nothing prints.
Using Workbook-Level Events
Workbook-level events occur for a particular workbook. Table 43.1 lists the most commonly used workbook events, along with a brief description of each. Keep in mind that workbook event-han- dler procedures must be stored in the code module for the ThisWorkbook object.
875
Part VI: Programming Excel with VBA
TABLE 43.1
|
Workbook Events |
Event |
Action That Triggers the Event |
|
|
Activate |
The workbook is activated. |
|
|
AddinInstall |
The workbook is installed as an add-in. |
|
|
AddinUninstall |
The workbook is uninstalled as an add-in. |
|
|
BeforeClose |
The workbook is about to be closed. |
|
|
BeforePrint |
The workbook (or anything in it) is about to be printed. |
|
|
BeforeSave |
The workbook is about to be saved. |
|
|
Deactivate |
The workbook is deactivated. |
|
|
NewSheet |
A new sheet is created in the workbook. |
|
|
Open |
The workbook is opened. |
|
|
SheetActivate |
Any sheet in the workbook is activated. |
|
|
SheetBeforeDoubleClick |
Any worksheet in the workbook is double-clicked. This event occurs |
|
before the default double-click action. |
|
|
SheetBeforeRightClick |
Any worksheet in the workbook is right-clicked. This event occurs |
|
before the default right-click action. |
|
|
SheetCalculate |
Any worksheet in the workbook is calculated (or recalculated). |
|
|
SheetChange |
Any worksheet in the workbook is changed by the user. |
|
|
SheetDeactivate |
Any sheet in the workbook is deactivated. |
|
|
SheetFollowHyperlink |
Any hyperlink in the workbook is clicked. |
|
|
SheetSelectionChange |
The selection on any worksheet in the workbook is changed. |
|
|
WindowActivate |
Any window of the workbook is activated. |
|
|
WindowDeactivate |
Any workbook window is deactivated. |
|
|
WindowResize |
Any workbook window is resized. |
|
|
The remainder of this section presents examples of using workbook-level events. All the example procedures that follow must be located in the code module for the ThisWorkbook object. If you put them into any other type of code module, they will not work.
Using the Open event
One of the most common monitored events is a workbook’s Open event. This event is triggered when the workbook (or add-in) opens and executes the Workbook_Open procedure. A Workbook_Open procedure is very versatile and is often used for the following tasks:
876
Chapter 43: Working with Excel Events
•Displaying welcome messages.
•Opening other workbooks.
•Activating a specific sheet.
•Ensuring that certain conditions are met; for example, a workbook may require that a particular add-in is installed.
Caution
Be aware that there is no guarantee that your Workbook_Open procedure will be executed. For example, the user may choose to disable macros. And if the user holds down the Shift key while opening a workbook, the workbook’s Workbook_Open procedure will not execute. n
The following is a simple example of a Workbook_Open procedure. It uses the VBA Weekday function to determine the day of the week. If it’s Friday, a message box appears to remind the user to perform a file backup. If it’s not Friday, nothing happens.
Private Sub Workbook_Open()
If Weekday(Now) = 6 Then
Msg = “Make sure you do your weekly backup!”
MsgBox Msg, vbInformation
End If
End Sub
What if you would like to activate a particular Ribbon tab automatically when a workbook is opened? Unfortunately, VBA can’t do much at all with the Excel Ribbon, and there is no direct way to activate a particular Ribbon tab. The next example uses the SendKeys statement to simulate keystrokes. In this case, it sends Alt+H, which is the Excel’s “keytip” equivalent of activating the Home tab of the Ribbon. Sending the F6 keystroke removes the keytip letters from the Ribbon.
Private Sub Workbook_Open()
Application.SendKeys (“%h{F6}”)
End Sub
The following example performs a number of actions when the workbook is opened. It maximizes the Excel window, maximizes the workbook window, activates the sheet named DataEntry, and selects the first empty cell in column A. If a sheet named DataEntry does not exist, the code generates an error.
Private Sub Workbook_Open()
Application.WindowState = xlMaximized
ActiveWindow.WindowState = xlMaximized
Worksheets(“DataEntry”).Activate
Range(“A1”).End(xlDown).offset(1,0).Select
End Sub
877
Part VI: Programming Excel with VBA
Using the SheetActivate event
The following procedure executes whenever the user activates any sheet in the workbook. The code simply selects cell A1. Including the On Error Resume Next statement causes the procedure to ignore the error that occurs if the activated sheet is a chart sheet.
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
On Error Resume Next
Range(“A1”).Select
End Sub
An alternative method to handle the case of a chart sheet is to check the sheet type. Use the Sh argument, which is passed to the procedure.
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
If TypeName(Sh) = “Worksheet” Then Range(“A1”).Select
End Sub
Using the NewSheet event
The following procedure executes whenever a new sheet is added to the workbook. The sheet is passed to the procedure as an argument. Because a new sheet can be either a worksheet or a chart sheet, this procedure determines the sheet type. If it’s a worksheet, it inserts a date and time stamp in cell A1.
Private Sub Workbook_NewSheet(ByVal Sh As Object)
If TypeName(Sh) = “Worksheet” Then _
Range(“A1”) = “Sheet added “ & Now()
End Sub
Using the BeforeSave event
The BeforeSave event occurs before the workbook is actually saved. As you know, choosing Office Save sometimes brings up the Save As dialog box — for example, when the file has never been saved or was opened in read-only mode.
When the Workbook_BeforeSave procedure executes, it receives an argument that enables you to identify whether the Save As dialog box will appear. The following example demonstrates this:
Private Sub Workbook_BeforeSave _
(ByVal SaveAsUI As Boolean, Cancel As Boolean)
If SaveAsUI Then
MsgBox “Use the new file-naming convention.”
End If
End Sub
878