Excel is made up of objects, such as workbooks, worksheets, cells, charts, pivot tables, and even the entire Excel application is an object. You can write a VBA code snippet for a specific object that will execute when something happened to that object. Excel can monitor several events that can be classified by their object types:
Application events
Events that occur for the Excel itself. For example:NewWorkbook
event (a new workbook created)Chart events
Events that occur for a specific chart. For example:Select
event (something in the chart is selected)UserForm events
Events that occur for a specific UserForm. For example:Click
event (a buttonCommandButton
is clicked).Workbook events
Events that occur for a specific workbook. For example:Open
event (the workbook is opened)Worksheet events
Events that occur for a specific worksheet. For example:Change
event (a cell value changed on the sheet)Other events (
OnTime
andOnKey
events)
Application-level events that are not associated with any Excel object
How and where to write the event procedures
In the Visual Basic Editor (VBE) window (see How to open the VBE), every workbook has a project listed in the Project window
as shown in following figure:
Each of the following objects has its own code module. Double click on a module to open the code window for writing the code:
Microsoft Excel Objects
Sheet objects, for example,
Sheet1
,Sheet2
,Sheet3
and so on
Each worksheet comes with its own built-in module, so you never need to create a module for any worksheet. Use these modules for event-handler code related to the particular worksheet.ThisWorkbook object
Use this module for event-handler code related to the workbook. Each Excel workbook comes withThisWorkbook
module for workbook related coding.Chart objects, for example
Chart1
Each chart sheet (not embeded charts) comes with its own built-in module. Use this module for event-handler code related to the particular chart.
Modules
Modules are containers for the macros that the Macro Recorder (or you) creates. Never put event-handler procedures in a module.Forms, for example
UserForm1
Use this module for event-handler code related to theUserForm
.Class Modules
Use these modules for event-handler code related to the embedded charts events and application level events.