How to Use VBA Event Handler (5 Relevant Examples)

Event handler is an important portion of the VBA code. If you are one of those who want to learn more about VBA macros, this article would obviously come in handy. In this article, we’re going to narrate to you the VBA event handler in Excel.

What Is VBA Event Handler in Excel?

Let’s start with an example. Say, I 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. So here, 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. Say we want this when this command button will be clicked, cells in the range B4:D4 will be decorated with the yellow background color. So, we write 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 I 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 Event Handler?

All event handler procedures, I mean VBA code, must be placed in the relevant code module. If you are working with workbook-related events, then you should place the VBA code you write in the ThisWorkbook code module. Follow the steps below for clarification.

  • At the very beginning, go to the Developer tab.
  • Following this, click on Visual Basic in the Code group.
  • Alternatively, press ALT + F11 to do the same task.

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

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

  • Based on our previous action, the Code Module pops up.
  • Then, from the left drop-down, select Workbook as the object.

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

  • After that, from the top-right drop-down, select the Open event.
  • Thus, the sub-procedure name looks like the one below.

sub-procedure name

Now, between these two lines, you can enter your Workbook event handlers, which means the VBA code. Also,
if you want to add Worksheet related event handlers, just look at the following steps.

  • First of all, bring the Microsoft Visual Basic for Applications window like before.
  • Then, 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

Now, it is ready to take your input between these two lines.

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.

  • First, double-click on Sheet3 (Highlighting Active Row) in Project Explorer.
  • Then, select Worksheet from the left drop-down list,
  • Finally, choose and click on the Activate event.

Therefore, 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

Currently, we’ll discuss some practical VBA event handlers and see how you might use them in your daily life assignment. So, let’s explore them one by one.

Example 01: Opening Workbook

Let’s assume you want to prompt the end user to complete their time tracker each time they open a particular workbook. So, without further delay, let’s see how we do it.

📌 Steps:

  • At the very beginning, move to the Developer tab.
  • Then, select Visual Basic in the Code group.
  • Alternatively, press ALT + F11 to replicate the task in the shortcut.

VBA Event Handler to Open Workbook

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

Thus, the Workbook Code Module opens.

  • Presently, select Workbook on the left drop-down.
  • Also, choose Open events from the right drop-down.
  • Correspondingly, the following code appears in the module box automatically.

Selecting Open Event

  • Now, write some lines of code between these two lines as event handlers.
  • Simply 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

Now, 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.

  • Then, click OK to remove it from the screen.

VBA Event Handler to Open Workbook

Read More: Excel VBA Open Workbook Event

Example 02: VBA Event Handlers with Arguments

Event-handler procedures may also contain arguments. In this example, we’ll explain how to work with an event that will display a message when you activate any of the worksheets. Let’s see the process.

📌 Steps:

  • Firstly, bring up the ThisWorkbook code module like Example 01.
  • Then, select Workbook from the left drop-down.
  • After that, choose SheetActivate on the left drop-down.

Thus, we’ll see the sub-procedure will automatically get the Sh argument.

VBA Event Handlers with Arguments

  • At this moment, 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.

  • First of all, open the working file after downloading it.
  • Then travel from one worksheet to another.
  • When you will travel from one worksheet to another, it will display the name of the activated worksheet like the following image.

Showing MsgBox in Excel

Example 03: VBA Event Handler with Boolean Arguments

Some event-handler procedures have a Boolean argument called Cancel. For example, you may plan for a pop-up message that will display some information when you want to print something related to your workbook. There is an event called the BeforePrint event. Follow the entire process.

📌 Steps:

  • Initially, open the ThisWorkbook code module.
  • Later, write 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.

  • At first, press the CTRL key followed by P on your keyboard.

  • Secondly, click on Print to print the document.

Proceeding to Print

Therefore, you will find a message box like the following image.

Message Alert before Print

Example 04: Highlighting Active Row

If your Excel dataset has a lot of columns, it becomes quite difficult to find data from one end to another end of a row. But if you generate a system in which whenever you select a cell in your dataset, the whole row will be highlighted, then you can easily find data from that row. Here, we’ll discuss this feature here. So, without further delay, let’s dive in!

📌 Steps:

  • As always, open the code module, like before.
  • Here, 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

  • Presently, return to the worksheet.
  • Following this, select cell E7.

Selecting a Cell

Thus, the whole Row 7 gets highlighted in one click.

Highlighting the Row

Example 05: Availing Advantage of Double-Click

In our following example, we’ll learn a remarkably interesting trick. Also, this event is very helpful to lessen your effort. This event sparks when someone double-clicks on a particular cell. Allow me to show the process below.

📌 Steps:

  • As usual, bring up the code module like before.
  • After that, 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.

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

Magically, we can see these cells get changed just by clicking.

Cells Get Changed after Double-clicking

Negative Impact of Event Handler on Undo Stack

I’ll start by explaining what an Undo Stack is.
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. Follow the steps below for a better understanding.

📌 Steps:

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

But, nothing happened this time. The cells remain unchanged.

Negative Impact of Event Handler on Undo Stack

  • Then, select cell D9.
  • After that, make the font Bold.
  • Later, click on the Fill Color dropdown.
  • Next, select Yellow as the background color.

Actually, we make these changes manually instead of using the VBA event.

Subsequently, the cell looks like the one below.

  • Now, press CTRL + Z on your keyboard.

Pressing CTRL+Z

At this time, the actions get undone.

Actions Get Undone

Here is what we are trying to make you understand when we apply some changes through the event handler, the action can’t be undone using the Undo stack.

VBA Change Event

Change is an event of Worksheet. When some changes happen in a cell, the Change event gets triggered. Let’s see this with an example.

📌 Steps:

  • Forthwith, open the code module like before.
  • Following this, 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

  • Secondly, select cell E6. Note that the cell value is 218.

  • Then, change the cell value to 510.
  • Additionally, press ENTER.

Changing the Value of a Cell

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

MSgBox Showing Cell Address

  • Just after clicking OK, another MsgBox appears with a changed cell value of 510.
  • Also, click OK to get rid of the box.

MsgBox Showing Cell Value

VBA Click Event

Actually, the VBA Click event works with the Command Button. When you click on the Command Button, the event triggers itself. Just follow us.

📌 Steps:

  • Primarily, proceed to the Developer tab.
  • Secondarily, click the Insert drop-down on the Controls group.
  • After that, select Command Button (ActiveX Control).

VBA Click Event

  • Later, 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

  • Now, right-click on the button to open the context menu.
  • Hereafter, select View Code from the options.

VBA Command Button Event Handler

The code module window appears before us.

  • Then, place the following code into the module.
Private Sub CommandButton1_Click()
End Sub

VBA Command Button Event Handler

  • Lastly, as we click the CommandButton1, the contents in the B10:H10 range get cleared.

VBA Click Event Handler

So, this was all from me on this topic.

Download Practice Workbooks

You may download the following Excel workbooks for better understanding and practice yourself.


Thank you for reading this article. I hope all the information mentioned above about the VBA event handler will now prompt you to apply them in your Excel spreadsheets more effectively. Don’t forget to download the Practice file. If you have any questions or feedback, please let me know in the comment section.

Related Articles

Get FREE Advanced Excel Exercises with Solutions!


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