Excel VBA Events (A Complete Guideline) - ExcelDemy (2024)

What Is an Event and Event Handler in Excel VBA?

To understand an Event and Event Handler, we will illustrate with an example.

  • Prepare a dataset according to your preference. We have prepared one with the information of the Order List of 8 customers with Product ID and Price.

Excel VBA Events (A Complete Guideline) - ExcelDemy (1)

  • Go to the Developer tab and select Insert.
  • Choose Command Button from the ActiveX Controlssection.

Excel VBA Events (A Complete Guideline) - ExcelDemy (2)

  • Right-click on the Command Button and select Properties.

Excel VBA Events (A Complete Guideline) - ExcelDemy (3)

  • Customize the Caption and ForeColor according to your preference.

Excel VBA Events (A Complete Guideline) - ExcelDemy (4)

  • Insert this code and run it.
Private Sub CommandButton1_Click() Range("B5").Interior.Color = vbBlueEnd Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (5)

  • You will see the following output.

Excel VBA Events (A Complete Guideline) - ExcelDemy (6)

In this example, Clicking on the Command Button is an Event. The Subprocedure will depend on the code you entered. This Subprocedure is an Event Handler as it executes when someone clicks on the Command Button.

Where to Insert Event-Related Code in Excel?

Based on the type of event, we need to know where to enter the code related to that object. Following are the five ways to operate it:

Method 1 – In Worksheet Code Window

For worksheet code, here is the process to insert code based on the specific object.

  • Select the worksheet object in your VBA Project.

Excel VBA Events (A Complete Guideline) - ExcelDemy (7)

  • Double-click on it and select Worksheet from the top-left corner of the window.

Excel VBA Events (A Complete Guideline) - ExcelDemy (8)

  • Select any event from the Selection Change list according to your object.

Excel VBA Events (A Complete Guideline) - ExcelDemy (9)

  • Insert your code as per the image below:

Excel VBA Events (A Complete Guideline) - ExcelDemy (10)

Method 2 – In ThisWorkbook Code Window

ThisWorkbook also works like the Worksheet code in the VBA project.

  • Select ThisWorkbook from the worksheet object list.

Excel VBA Events (A Complete Guideline) - ExcelDemy (11)

  • Choose Workbook from the top-left corner panel.

Excel VBA Events (A Complete Guideline) - ExcelDemy (12)

  • Select the type from the options and place your code.

Excel VBA Events (A Complete Guideline) - ExcelDemy (13)

Method 3 – In UserForm Code Window

In case you want to create a UserForm in Excel, you can apply the UserForm code.

  • Right-click on any worksheet object and select UserForm from the Insertsection.

Excel VBA Events (A Complete Guideline) - ExcelDemy (14)

  • You will see the new window to insert the UserFormobject.

Excel VBA Events (A Complete Guideline) - ExcelDemy (15)

Method 4 – In Chart Code Window

  • Select the Chart Sheet name from the worksheet object list.

Excel VBA Events (A Complete Guideline) - ExcelDemy (16)

  • Select Chart from the drop-downmenu.

Excel VBA Events (A Complete Guideline) - ExcelDemy (17)

  • Select any event according to your code and insert your code.

Excel VBA Events (A Complete Guideline) - ExcelDemy (18)

Method 5 – In Class Module

We can insert VBA code in the Class Module from the Insert section in any worksheet object.

Excel VBA Events (A Complete Guideline) - ExcelDemy (19)

Different Types of VBA Events in Excel

1. Workbook Open Event

When a user tries to open a certain workbook holding the following code that event is the Workbook Open event. It will generally work as a welcome note.

Private Sub Workbook_Open()MsgBox "Your Workbook"End Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (20)

Read More: Excel VBA Open Workbook Event

2. Workbook NewSheet Event

This event triggers the opening of a new worksheet in Excel. It also allows a certain number of users in a shared workbook to avoid mess.

Private Sub Workbook_NewSheet(ByVal Obj As Object)Application.DisplayAlerts = FalseIf Application.UserName <> "Maria" Then Obj.DeleteEnd IfApplication.DisplayAlerts = TrueEnd Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (21)

Read More: Excel VBA: Workbook Level Events and Their Uses

3. Workbook BeforeSave Event

The BeforeSave event works when you want to save a workbook. Keep in mind that this event triggers in the first place, followed by saving the workbook in C Drive.

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)If SaveAsUI Then MsgBox "Save the File in C Drive"End Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (22)

4. Workbook BeforeClose Event

This event happens just before the workbook is closed by its user.

Private Sub Workbook_BeforeClose(Cancel As Boolean)Dim WkSh As WorksheetFor Each WkSh In ThisWorkbook.WorksheetsWkSh.ProtectNext WkShEnd Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (23)

5. Workbook BeforePrint Event

In excel, when you give the Print command or at least the Print Preview command, the BeforePrint event operates in excel.

Private Sub Workbook_BeforePrint(Cancel As Boolean) For Each WkSh In Worksheets WkSh.Calculate Next WkSh End Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (24)

6. Worksheet Activate Event

This event is triggered when you want to activate a sheet. This code unprotects a sheet just the moment it is activated.

Private Sub Worksheet_Activate()ActiveSheet.Range("B5").SelectEnd Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (25)

7. Worksheet Change Event

This event occurs when you operate a change on your worksheet. However, there are some distinctive situations where this code would be successful. They are:

  • Copy and pasting
  • Clearing formatting
  • Running a spelling check
Private Sub Worksheet_Change(ByVal Trg As Range)MsgBox "Your recent change in Worksheet " & Trg.AddressEnd Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (26)

8. Workbook SelectionChange Event

The SelectChange event is triggered whenever there is any occurrence of a change within selected cells.

Private Sub Worksheet_SelectionChange(ByVal Trg As Range)Application.CalculateEnd Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (27)

9. Workbook DoubleClick Event

This is one of the widely used events in Excel. This happens when you double-click on a specific cell. After this event, that cell will change its font and background color along with the font type.

Private Sub Worksheet_BeforeDoubleClick(ByVal Trg As Range, Cancel As Boolean)Cancel = TrueWith Trg.Interior.Color = vbRed.Font.Color = vbBlue.Font.Bold = TrueEnd WithEnd Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (28)

10. Command Button Click Event

The Command Button tool is incorporated into this event. This is triggered when you press the command button holding a certain VBA code.

Private Sub CommandButton1_Click()Dim BnRet As VariantBnRet = MsgBox("Are you sure?", vbQuestion Or vbYesNo)If BnRet = vbNo Then Exit SubEnd Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (29)

11. Drop Down (Combo Box) Change Event

When a user selects a particular item from the active X drop-down list, the user can decide the choice using this event and afterward write this code for adapting other items of the sheet accordingly.

Private Sub ComboBox1_Change()MsgBox "Your selection" & ComboBox1.TextEnd Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (30)

12. Tick Box (Check Box) Click Event

You can also create a Tick or Check Box by running the following code. It will benefit the user to see if any changes happened in the worksheet. The values returned are either True or False based on whether it has been checked or not.

Private Sub CheckBox_Click()MsgBox CheckBox.ValueEnd Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (31)

13. UserForm Activate Event

This event is used to set up a default value in an Excel form. For example, a default institution name in the name text box.

Private Sub UserForm_Activate()TextBox.Text = "Institution Name"End Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (32)

14. Change Event

In this event, there will be controls on the Excel form for any kind of changes that occur. For instance, this code puts a restriction on the length of names being entered.

Private Sub TextBox_Change()If Len(TextBox.Text) > 50 Then MsgBox "The object is restricted to 50 characters", vbCritical TextBox.Text = "" End IfEnd Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (33)

15. Click Event

This event is triggered when you wish to control the form. Here, an OK button would place a certain value on the spreadsheet for future reference.

Private Sub CommandButton_Click()ActiveSheet.Range("B5").Value = TextBox.TextMe.HideEnd Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (34)

16. Application.OnTime

This event is different from the events that we discussed so far. Because it is stored within a regular VBA mode, not in a specific object. The code runs when it is generated at a specified time.

Sub NotificationTime()Application.OnTime TimeValue("22:00:00"), "ShowNotification"End SubSub ShowNotification()MsgBox "Lunch Time"End Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (35)

17. Application.OnKey

The Application.OnKey event happens when you try to use a keystroke on your Excel file.

Sub TestKey()Application.OnKey "g", "TestKey"End SubSub TestKey()MsgBox "You just pressed the key 'g'"End Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (36)

Read More: How to Use VBA OnKey Event in Excel

How to Disable VBA Events in Excel

If you want to turn off any existing event, apply this code to stop it. All you need to do is to incorporate this in disabling the event and re-enable it at the end of the code. Remember that it runs across the whole workbook, not any specific worksheet.

Sub DisableVBAEvents()Application.EnableEvents = FalseApplication.EnableEvents = TrueEnd Sub

Excel VBA Events (A Complete Guideline) - ExcelDemy (37)

Download Practice Workbook

VBA Events.xlsm

Related Article

  • How to Create Calendar Using VBA in Excel
Get FREE Advanced Excel Exercises with Solutions!
Excel VBA Events (A Complete Guideline) - ExcelDemy (2024)

References

Top Articles
How you can Thicken Split Pea Soup - Nutrition | NoahStrength.com
Are Ginger root Cookies Healthy for you - Nutrition | NoahStrength.com
Printable Whoville Houses Clipart
Ffxiv Shelfeye Reaver
Craigslist Portales
Hay day: Top 6 tips, tricks, and cheats to save cash and grow your farm fast!
How do you mix essential oils with carrier oils?
Xrarse
Elden Ring Dex/Int Build
Slay The Spire Red Mask
Carter Joseph Hopf
Scentsy Dashboard Log In
Wildflower1967
065106619
Q Management Inc
Honda cb750 cbx z1 Kawasaki kz900 h2 kz 900 Harley Davidson BMW Indian - wanted - by dealer - sale - craigslist
Saatva Memory Foam Hybrid mattress review 2024
U Break It Near Me
Everything you need to know about Costco Travel (and why I love it) - The Points Guy
Halo Worth Animal Jam
Best Mechanics Near You - Brake Masters Auto Repair Shops
Isaidup
Puretalkusa.com/Amac
Craigslist Lake Charles
Fiona Shaw on Ireland: ‘It is one of the most successful countries in the world. It wasn’t when I left it’
Buhl Park Summer Concert Series 2023 Schedule
Cylinder Head Bolt Torque Values
Www Mydocbill Rada
N.J. Hogenkamp Sons Funeral Home | Saint Henry, Ohio
91 Octane Gas Prices Near Me
La Qua Brothers Funeral Home
Wega Kit Filtros Fiat Cronos Argo 1.8 E-torq + Aceite 5w30 5l
Peter Vigilante Biography, Net Worth, Age, Height, Family, Girlfriend
Log in or sign up to view
Toonily The Carry
Midsouthshooters Supply
Fototour verlassener Fliegerhorst Schönwald [Lost Place Brandenburg]
Ticket To Paradise Showtimes Near Regal Citrus Park
Blackwolf Run Pro Shop
Riverton Wyoming Craigslist
Arigreyfr
Sour OG is a chill recreational strain -- just have healthy snacks nearby (cannabis review)
VerTRIO Comfort MHR 1800 - 3 Standen Elektrische Kachel - Hoog Capaciteit Carbon... | bol
Strange World Showtimes Near Marcus La Crosse Cinema
Makemkv Key April 2023
Hampton Inn Corbin Ky Bed Bugs
Tommy Gold Lpsg
Home | General Store and Gas Station | Cressman's General Store | California
Lake County Fl Trash Pickup Schedule
What Responsibilities Are Listed In Duties 2 3 And 4
Qvc Com Blogs
Latest Posts
Article information

Author: Cheryll Lueilwitz

Last Updated:

Views: 6649

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Cheryll Lueilwitz

Birthday: 1997-12-23

Address: 4653 O'Kon Hill, Lake Juanstad, AR 65469

Phone: +494124489301

Job: Marketing Representative

Hobby: Reading, Ice skating, Foraging, BASE jumping, Hiking, Skateboarding, Kayaking

Introduction: My name is Cheryll Lueilwitz, I am a sparkling, clean, super, lucky, joyous, outstanding, lucky person who loves writing and wants to share my knowledge and understanding with you.