18.11.2014 Views

Microsoft Office

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Working with Excel Events<br />

In the preceding chapters, you’ve seen some examples of VBA event-handler<br />

procedures. These procedures are the keys to making your Excel applications<br />

interactive. This chapter provides an introduction to the concept of Excel<br />

events and includes many examples that you can adapt to meet your own needs.<br />

Understanding Events<br />

Excel is capable of monitoring a wide variety of events and executing your VBA<br />

code when a particular event occurs. This chapter covers the following types of<br />

events.<br />

IN THIS CHAPTER<br />

Understanding events<br />

Using workbook-level events<br />

Working with worksheet events<br />

Using non-object events<br />

n<br />

n<br />

n<br />

Workbook events: These occur for a particular workbook. Examples<br />

include Open (the workbook is opened or created), BeforeSave (the<br />

workbook is about to be saved), and NewSheet (a new sheet is<br />

added). VBA code for workbook events must be stored in the<br />

ThisWorkbook code module.<br />

Worksheet events: These occur for a particular worksheet. Examples<br />

include Change (a cell on the sheet is changed), SelectionChange<br />

(the cell pointer is moved), and Calculate (the worksheet is recalculated).<br />

VBA code for worksheet events must be stored in the code module<br />

for the worksheet (for example, the module named Sheet1).<br />

Events not associated with objects: The final category consists of two<br />

useful application-level events: OnTime and OnKey. These work differently<br />

from other events.<br />

Entering event-handler VBA code<br />

Every event-handler procedure must go into a specific type of code module.<br />

Code for workbook-level events goes into the ThisWorkbook code module. Code<br />

for worksheet-level events goes into the code module for the particular sheet (for<br />

example, the code module named Sheet1).<br />

745

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!