Event procedures are sub procedures connected to events or actions of an Excel object, such as a worksheet or a workbook. They allow you to perform a set of tasks when an event occurs, such as changing a cell content, selecting a range or opening a workbook. Each of these events is associated to an event procedure that is called automatically by Excel when that event occurs. This page provides a detailed explanation of event procedures in VBA: Events in Excel VBA.
Events and their procedure declarations are fixed. To see the available events for worksheets follow these steps (do the same for workbook and application objects):
- Open the Object Browser in the VBE (press F2 or choose Object Browser from the View menu).
- In the “Classes” list on the left hand, scroll down and select Worksheet.
- Right-click anywhere in the primary window and choose “Group Members” on the pop up menu.
- Scroll down in the “Members Of Worksheet” list on the right hand until you see items with yellow lightening bolts next to them. These are the events for the Worksheet objects.
- Select the Change event and press F1 for help on that event.
To write an event procedure and the set of tasks to be performed when the event occurs, do the following steps on VBE:
- Open the VBA code module associated to one of the spreadsheets. In that code window you will see two dropdown boxes at the top.
- Choose an object from the object list (left hand) and then choose an event from the event list (right hand). For instance, select the Worksheet object and the Change event. This will automatically add the event procedure declaration for the Change event to the code module.
- Add the code that you want to take place when a cell value is changed. Try adding the code: MsgBox “You changed cell ” & Target.Address.
Typically used event procedures for worksheets and workbooks are:
Click
CommandButton1_Click() ‘ When the spreadsheet contains a button control
Worksheet_BeforeDoubleClick (ByVal Target As Range, Cancel As Boolean)
Change
Worksheet_Change (ByVal Target As Range)
Workbook_SheetChange (ByVal Sh As Object, ByVal Target As Range)
Worksheet_SelectionChange (ByVal Target As Range)
Activate
Worksheet_Activate()
Workbook_Activate()
Open
Workbook_Open()