Event Procedures

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):

  1. Open the Object Browser in the VBE (press F2 or choose Object Browser from the View menu).
  2. In the “Classes” list on the left hand, scroll down and select Worksheet.
  3. Right-click anywhere in the primary window and choose “Group Members” on the pop up menu.
  4. 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.
  5. Select the Change event and press F1 for help on that event.

Change event

To write an event procedure and the set of tasks to be performed when the event occurs, do the following steps on VBE:

  1. Open the VBA code module associated to one of the spreadsheets. In that code window you will see two dropdown boxes at the top.
  2. 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.
  3. 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.

When you select an event from the dropdown box, VBE will automatically insert the procedure declaration in the code module.

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()

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.