
Using events to activate objects
The last element in relation to objects that we need to discuss is events. In simple English, an event is what happens when an object does something, such as open a workbook, close a sheet, or print a file. Events are initiated by a user, for example, by clicking a mouse or pressing a key.
In this recipe, we're going to cover only the most basic principles, since an entire chapter is dedicated to events later in this book.
Getting ready
With Excel open, ensure that a blank workbook is available and active.
How to do it…
The first thing to remember about events is that the code is not stored in a module object, but in the workbook object. Place the code anywhere else and it will simply not work.
The steps for this recipe are as follows:
- Press Alt + F11 to activate the VBA Editor.
- In the Project window, double-click on the ThisWorkbook object to open the code window.
- At the top left of the code window, from the drop-down list, select the object that you're coding for; in this case, a workbook:
Figure 3.5 – The object drop-down list in the VBA Editor
- The default event inserted will be Open. If you want to code for another event, select from the drop-down list at the top right of the window:
Figure 3.6 – The Open event code
- Between the opening and closing statements of the Sub procedure, type the following code:
Figure 3.7 – Completed Sub procedure
- Once done, don't just run the code by pressing F5. You need to trigger the event that the Sub procedure is attached to, meaning that you have to save the file and then open it. The event will only be activated when the file is opened.
- Press Alt + F11 to switch back to Excel.
- Save the file as a macro-enabled workbook and close it.
- When you open it now, click on Enable Macros. The event will be initiated, and a message box will be displayed. Click on the OK button to close the message box:

Figure 3.8 – The result of the Open event code Sub procedure
Take note that the message box must be closed before you can do any work on the spreadsheet.
How it works…
Events are initiated by objects that do something. In this case, the event is linked to the opening of a specific workbook. When the workbook is opened, the event is triggered, and as per the instructions in the code, a message box is displayed.