Chapter 43Working with Excel Events

IN THIS CHAPTER

  1. Understanding events
  2. Using workbook-level events
  3. Working with worksheet events
  4. Using nonobject events

In the preceding chapters, I presented a few examples of VBA event-handler procedures. These procedures are the keys to making your Excel applications interactive. This chapter introduces the concept of Excel events and includes many examples that you can adapt to meet your own needs.

Understanding Events

Excel can monitor a 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). You must store VBA code for workbook events 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.

Entering Event-Handler VBA Code

Every event-handler procedure must reside in a specific type of code module. Code ...

Get Excel 2016 Bible now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.