Please Note: This article is written for users of the following Microsoft Excel versions: 2007, 2010, 2013, 2016, 2019, and Excel in Office 365. If you are using an earlier version (Excel 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Excel, click here: Worksheet Events.

Worksheet Events

by Allen Wyatt
(last updated July 20, 2019)

2

One of the beauties of creating macros for Excel is that they can be event-driven. This means that you can create macros that will run automatically when specific, well-defined events happen within Excel. These events can happen either on a worksheet or a workbook level.

The easiest way to see what worksheet events are available is to follow these steps:

  1. Press Alt+F11 to display the VBA Editor.
  2. In the Project Explorer window (upper-left corner of the VBA Editor), find the project (workbook) that you are working on.
  3. Expand the project, if necessary, by clicking the plus sign to the left of the project name. You should see all the worksheets in the project listed.
  4. Double-click the worksheet you want to work with. A code window should appear for the worksheet.
  5. At the top of the worksheet's code window are two drop-down lists. In the left-hand drop-down list, choose Worksheet.

At this point, the right-hand drop-down list contains all the events that you can "trap" for this worksheet. The available events may vary, according to your version of Excel. The following events are available:

  • Activate
  • BeforeDelete
  • BeforeDoubleClick
  • BeforeRightClick
  • Calculate
  • Change
  • Deactivate
  • FollowHyperlink
  • PivotTableUpdate
  • SelectionChange

The names of the events should be descriptive enough that you can tell what triggers each of them. If you choose one of the events, you can create the macro you want run when the event actually occurs.

Note:

If you would like to know how to use the macros described on this page (or on any other page on the ExcelTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (9545) applies to Microsoft Excel 2007, 2010, 2013, 2016, 2019, and Excel in Office 365. You can find a version of this tip for the older menu interface of Excel here: Worksheet Events.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Using Call to Run VBA Macros

An elegant way to run macros from within macros is to use the Call statement. In order to use it, you need to provide a ...

Discover More

Anchoring Comment Boxes in Desired Locations

Want your comment boxes to appear someplace other than the right side of a cell? You may be out of luck, and here's why.

Discover More

Determining a Worksheet's Number

When you add a new worksheet to a workbook, it receives a meaningful name such as "Sheet4" or "Sheet17." If you want to ...

Discover More

Solve Real Business Problems Master business modeling and analysis techniques with Excel and transform data into bottom-line results. This hands-on, scenario-focused guide shows you how to use the latest Excel tools to integrate data from multiple tables. Check out Microsoft Excel 2013 Data Analysis and Business Modeling today!

More ExcelTips (ribbon)

Making a Cell's Contents Italics within a Macro

You can use macros to process information in your worksheets. You may want to use that macro to apply the italic ...

Discover More

Separating Evens and Odds

If you have a series of values in a column, you might have a need to separate the values into even values and odd values. ...

Discover More

Selecting a Range of Cells Relative to the Current Cell

When processing information in a macro, you often need to select different cells relative to the currently selected ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is eight minus 6?

2019-07-22 05:47:49

David Robinson

As promised here are a couple of examples.

Example 1: a macro that rescales the chart axis.

We all know that sometimes Excel doesn't scale chart axes for maximum impact. Many a time I create a line chart where all the lines are squished together at the top of the chart because Excel insists on starting the axis at zero, even when this is not selected.

I have written a macro to identify when the pivot table that calculates my chart data updates, and scales my chart to the value in cell "MinAxis", which has a formula to calculate a more appropriate minimum value for my y axis.

The pseudocode for "MinAxis" is =20*FLOOR(IFERROR(MIN(values),0)*0.9/20,1)

Private Sub Worksheet_PivotTableUpdate(ByVal TargetPivotTable As PivotTable)
' Set lower limit of chart Y axis to the calculated figure.
ActiveSheet.ChartObjects("MyChart ").Activate
ActiveSheet.ChartObjects("MyChart").Chart.Axes(xlValue).MinimumScale = ActiveSheet.Range("MinAxis").Value
End Sub

Example 2: a macro to align selections in two different pivot tables.

I find that pivot tables based on different pivot caches can't both be controlled by the same slicer. This macro takes the selections in one pivot table and mirrors them in another, so the user can make selections in both pivot tables from one slicer.

Obviously the pivot tables must both have the same set of possible values, and if this isn't the case you should add a dummy entry to use as a fail safe. Here we see the event trigger checking the pivot table is the right one... without this we'd potentially be firing the event macro for every change we make to the target table!

Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
If Target = ActiveSheet.PivotTables("PivotTable10") Then
AlignPivots
End If
End Sub

Sub AlignPivots()
' This aligns pSummary with pDetail. Piv1 is pSummary: this is our SOURCE. Piv2 is pDetail: this is our TARGET.
Dim Pitem As Integer
Dim Plabel As String
Dim Piv1 As PivotTable, Piv2 As PivotTable
Set Piv1 = Sheets("Items").PivotTables("pSummary")
Set Piv2 = Sheets("Details").PivotTables("pDetail")
' Align Product type. Start by setting any of them to visible, so we never try and make our target pivot table
' show nothing. Process the other entries, setting visible true or false as required, and finally process the
' one I set visible to start with. The choice is random, but let's just do the first entry.
With Piv2.PivotFields("Product type")
.PivotItems(1).Visible = True
For Pitem = 2 To .PivotItems.Count
Plabel = .PivotItems(Pitem).Value
.PivotItems(Pitem).Visible = Piv1.PivotFields("Product type").PivotItems(Plabel).Visible
Next Pitem
Plabel = .PivotItems(1).Value
.PivotItems(1).Visible = Piv1.PivotFields("Product type").PivotItems(Plabel).Visible
End With
' Align Site. Again I start by setting the first one to visible and then mopping up at the end.
With Piv2.PivotFields("Site")
.PivotItems(1).Visible = True
For Pitem = 2 To .PivotItems.Count
Plabel = .PivotItems(Pitem).Value
.PivotItems(Pitem).Visible = Piv1.PivotFields("Site").PivotItems(Plabel).Visible
Next Pitem
Plabel = .PivotItems(1).Value
.PivotItems(1).Visible = Piv1.PivotFields("Site").PivotItems(Plabel).Visible
End With
End Sub




2019-07-22 05:46:08

David Robinson

Sorry to be harsh, but I'm afraid I don't find this tip very useful.

For one thing, the uninitiated possibly won't understand terms such as activate/deactivate, Change or Calculate, and also I'm a bit fuzzy on what FollowHyperlink entails (such as, can you use it in deciding whether or not to follow the hyperlink, or is the hyperlinking a done deal?).

For another, the tip says nothing about scope management. By this, I mean checking that the event trigger is relevant, or in other words, say you want to pick up when cell A1 changes, how do you ensure you only run the macro when this cell changes rather than any other cell? Because without scope, and especially if the macro itself affects anything in the workbook, you could find yourself in a seemingly perpetual loop of nested events, each macro firing the trigger for another. The typical way to check the scope is correct is by using the "if Not Interesct (Target, {A1}) Is Nothing" syntax that readers can Google.

Finally, you don't say why you'd want to do this or give any examples. I will provide a couple of examples in a separate post.


This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.