How to Use VBA Event Handler (5 Relevant Examples)

What Is the VBA Event Handler in Excel?

We have placed a Command Button in my worksheet like the following figure. We will discuss the detailed process later in this article.

vba event handler

We want that Command Button will do something when it is clicked. Clicking on the CommandButton1 is an event. What this command button will do when it is clicked depends on the underlying subprocedure written by you. We want this when this command button will be clicked, cells in the range B4:D4 will be decorated with the yellow background color. We wrote a code like the following:

Private Sub CommandButton1_Click()
Range("B4:D4").Interior.Color = vbYellow
End Sub

This sub-procedure is called event handler as it executes when someone clicks on the Command Button.
When we click the CommandButton1, cells in the range B4:D4 in my worksheet get yellow as their background color. An event happens and the event handler executes.

vba event handler executes the event


How to Get the Relevant Code Module to Put an Event Handler

If you are working with workbook-related events, then you should place the VBA code you write in the ThisWorkbook code module.

  • Go to the Developer tab.
  • Click on Visual Basic in the Code group.
  • Alternatively, press Alt + F11.

How to Get the Relevant Code Module to Put Event Handler?

  • The Microsoft Visual Basic for Applications window appears.
  • In Project Explorer, double-click on ThisWorkbook.

  • The Code Module pops up.
  • From the left drop-down, select Workbook as the object.

How to Get the Relevant Code Module to Put Event Handler?

  • From the top-right drop-down, select the Open event.
  • The sub-procedure name looks like the one below.

sub-procedure name

Between these two lines, you can enter your Workbook event handlers, i.e., the VBA code.

Alternatively, you can bring up a module for a sheet.

  • Bring up the Microsoft Visual Basic for Applications window like before.
  • Double-click on the Sheet Name in which you want to insert the VBA code. In this case, we clicked on Sheet1.

Worksheet Related Event Handlers

  • From the left drop-down, select Worksheet.

Selecting Worksheet

  • After selecting Worksheet, the SelectionChange event gets selected automatically by default. Additionally, you can choose any other event from the right drop-down according to your preference.

SelectionChange event gets selected automatically


Event Handler Procedures Have Predefined Names

Every event handler (the procedure or VBA code that controls the event) has a predefined name.
For example, the figure below shows the code module for the Sheet3 worksheet. To get this code module.

  • Double-click on Sheet3 (Highlighting Active Row) in Project Explorer.
  • Select Worksheet from the left drop-down list,
  • Click on the Activate event.

We got a sub-procedure with two statements: the first statement is just the name of the sub-procedure, and the second statement is the End Sub statement, like the following figure.

Event Handler Procedures Have Predefined Names

There is no other code inside these two statements. The sub-procedure name is predefined by Excel. We have to write the event handler VBA code between these two lines.


VBA Event Handler: 5 Examples


Example 1 – Opening the Workbook

We want to prompt the user to complete their time tracker each time they open a particular workbook.

Steps:

  • Open the VBA window.

VBA Event Handler to Open Workbook

  • In Project Explorer, double-click on ThisWorkbook.

The Workbook Code Module opens.

  • Select Workbook on the left drop-down.
  • Choose Open events from the right drop-down.
  • The following code appears in the module box automatically.

Selecting Open Event

  • Paste the following code into your module.
Private Sub Workbook_Open()
wkd = Weekday(Date)
If wkd = 5 Then MsgBox "Make Sure to Fill the Time Tracker"
End Sub

Pasting Code into Module

  • Once you open the worksheet (on Thursday) that contains this script, a message box containing the desired message Make Sure to Fill the Time Tracker will appear.
  • Click OK to remove it from the screen.

VBA Event Handler to Open Workbook

Read More: Excel VBA Open Workbook Event


Example 2 – VBA Event Handlers with Arguments

We’ll explain how to work with an event that will display a message when you activate any of the worksheets.

Steps:

  • Bring up the ThisWorkbook code module like Example 1.
  • Select Workbook from the left drop-down.
  • Choose SheetActivate on the left drop-down.

The sub-procedure will automatically get the Sh argument.

VBA Event Handlers with Arguments

  • Paste the following code into the module.
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
MsgBox Sh.Name & “ was activated. ”
End Sub

Pasting Code into Module

This procedure has one argument: Sh. The Sh represents the activated sheet; it means that if you activate Sheet2, the value of Sh will be Sheet2; if you activate Sheet5, the value of Sh will be Sheet5, and so on. The Sh is declared as an Object.
The above code makes use of information passed through the argument Sh. The code finds out the name of the worksheet by accessing the argument’s Name property.

  • Open the working file after downloading it.
  • Move from one worksheet to another.
  • Excel will display the name of the activated worksheet like the following image.

Showing MsgBox in Excel


Example 3 – VBA Event Handler with Boolean Arguments

Some event-handler procedures have a Boolean argument called Cancel. For example, you can use a pop-up message that will display some information when you want to print something related to your workbook.

Steps:

  • Open the ThisWorkbook code module.
  • Insert the following code.
Private Sub Workbook_BeforePrint(Cancel As Boolean)
Msg = "Have you checked your printer connection?"
Ans = MsgBox(Msg, vbYesNo, "About to print...")
If Ans = vbNo Then Cancel = True
End Sub

Writing Code in ThisWorkbook Code Module

The default value of Cancel is FALSE. If you can make the value of Cancel to TRUE then the printing will be canceled.
The Workbook_BeforePrint procedure executes just before the workbook prints. When you try to print something, this event handler procedure will display a message to let you know whether you have checked the printer connection. If you press Yes (Cancel is FALSE), printing will start; if you press No (Cancel is TRUE), nothing will be printed.

  • Press Ctrl + P.

  • Click on Print to print the document.

Proceeding to Print

You will find a message box like the following image.

Message Alert before Print


Example 4 – Highlighting the Active Row

Steps:

  • Open the code module, like before.
  • Put the following code into the module.
Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
Static xRow
If xRow <> "" Then
With Rows(xRow).Interior
.ColorIndex = xlNone
End With
End If
Active_Row = Selection.Row
xRow = Active_Row
With Rows(Active_Row).Interior
.ColorIndex = 6
.Pattern = xlSolid
End With
End Sub

VBA Event Handler to Highlight Active Row

  • Return to the worksheet.
  • Select cell E7.

Selecting a Cell

The whole Row 7 gets highlighted in one click.

Highlighting the Row


Example 5 – Using Double-Click

Steps:

  • Bring up the code module like before.
  • Paste the following code into the module.
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Cancel = True
With Target
.Interior.Color = vbYellow
.Font.Color = vbBlack
.Font.Bold = True
End With
End Sub

VBA Event Handler to Avail Advantage of Double-Click

The above code does the following things:
When you double-click on a cell, it will apply a yellow background color to the cell. Also, it makes the font color black and makes the font Bold.

  • Double-click on cells D6, E8, and H7, one after one.

We can see these cells get changed just by clicking.

Cells Get Changed after Double-clicking


The Negative Impact of the Event Handler on the Undo Stack

Excel continuously tracks your actions while you work. You can always use Ctrl + Z to return to the earlier step if you make a mistake. You can go back two steps by pressing Ctrl + Z twice. The Undo stack contains a record of the actions you’ve taken.
If any event handler changes the worksheet, it can’t be undone by pressing Ctrl + Z. So, the undo stack gets disabled at this time.

Steps:

  • Press Ctrl + Z to undo the highlighting of the cell and get Bold of the fonts.

Nothing happened this time. The cells remain unchanged.

Negative Impact of Event Handler on Undo Stack

  • Select cell D9.
  • Make the font Bold.
  • Click on the Fill Color dropdown.
  • Select Yellow as the background color.

We made these changes manually instead of using the VBA event.

The cell looks like the one below.

  • Press Ctrl + Z on your keyboard.

Pressing CTRL+Z

The actions get undone.

Actions Get Undone


VBA Change Event

When some changes happen in a cell, the Change event gets triggered.

Steps:

  • Open the code module like before.
  • Paste the code into that module.
Private Sub Worksheet_Change(ByVal Target As Range)
MsgBox Target.Address
MsgBox Target.Value
End Sub

VBA Change Event

  • Select cell E6. The cell value is 218.

  • Change the cell value to 510.
  • Press Enter.

Changing the Value of a Cell

  • As soon as the change gets placed, Excel shows a MsgBox with the cell address E6.
  • Click OK.

MSgBox Showing Cell Address

  • Another MsgBox appears with a changed cell value of 510.
  • Click OK to get rid of the box.

MsgBox Showing Cell Value


VBA Click Event

When you click on the Command Button, the event triggers.

Steps:

  • Go to the Developer tab.
  • Click the Insert drop-down on the Controls group.
  • Select Command Button (ActiveX Control).

VBA Click Event

  • Drag the cursor like in the image below to place the button into the sheet.

Here is our CommandButton1 on the worksheet.

Command Button in Sheet

  • Right-click on the button to open the context menu.
  • Select View Code from the options.

VBA Command Button Event Handler

The code module window appears.

  • Place the following code into the module.
Private Sub CommandButton1_Click()
Range("B10:H10").ClearContents
End Sub

VBA Command Button Event Handler

  • When you click the CommandButton1, the contents in the B10:H10 range get cleared.

VBA Click Event Handler


Download the Practice Workbooks


Related Articles

Get FREE Advanced Excel Exercises with Solutions!

Tags:

Kawser Ahmed
Kawser Ahmed

Kawser Ahmed is a Microsoft Excel Expert, Udemy Course Instructor, Data Analyst, Finance professional, and Chief Editor of ExcelDemy. He is the founder and CEO of SOFTEKO (a software and content marketing company). He has a B.Sc in Electrical and Electronics Engineering. As a Udemy instructor, he offers 8 acclaimed Excel courses, one selected for Udemy Business. A devoted MS Excel enthusiast, Kawser has contributed over 200 articles and reviewed thousands more. His expertise extends to Data Analysis,... Read Full Bio

1 Comment

Leave a reply

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo