O'Reilly logo

Excel® VBA: 24-Hour Trainer by Tom Urtis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 11. Automating Procedures with Worksheet Events

For the most part, the macros you have seen in this book have been run by pressing a set of shortcut keys, or by going to the Macro dialog box, selecting the macro name, and clicking the Run button. You can take several other actions to run a macro, as you learn in future lessons. The common theme of all these actions is that you have to manually do something, whatever it may be, to run a macro.

The question becomes, can a VBA procedure simply know on its own when to run itself, and then just go ahead and do so automatically, without you needing to "do something" to make it run? The answer is yes, and it leads to the subject of event programming, which can greatly enhance the customization and control of your workbooks.

Note

So far, this book has used the term "macro" to refer to VBA subroutines. When referring to event code, the term "procedure" is used to differentiate it from macro code.

WHAT IS AN "EVENT"?

In the Excel object model, an event is something that happens to an object, and is recognized by the computer so an appropriate action can be taken. Recall that the Excel application is made up of objects, such as workbooks, worksheets, cells, charts, pivot tables, and so on. Even the entire Excel application is an object.

Virtually everything you do in Excel is in some way invoking an event upon an object. A few examples of events are as follows:

  • Double-clicking a cell

  • Adding a worksheet

  • Activating a worksheet

  • Changing a cell ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required