Vba worksheet events in Excel

Just as Workbook has some events associated with it, so does a worksheet .

The Worksheet events occur on a specific action performed on a worsheet.

There are a number of events associated with the worksheet, some of which

are discussed below.

Worksheet Activate event

This event occurs when a worksheet is activated.

This event is helpful when some action has to happen while activating a sheet.

This scenario arises when the user has to be notified of wrong sheet selection.

The following code snippet illustrates this.

  1. Private Sub Worksheet_Activate()
  2. MsgBox "Sheet Q47 has been activated"
  3. End Sub

You might have seen a msgbox while entering into this sheet.its because of its activate event.

  1. Private Sub Worksheet_Change(ByVal Target As Range)
  2. If Target.Address = "$M$17" Then
  3. MsgBox "Worksheet change event occured"
  4. End If
  5. End Sub
  6. Enter any value in Cell M17, the worksheet change event triggers.

WorkSheet Deactivate event

As the name implies, this event occurs, when the sheet is deactivated or left.

The following code illustrates this.

  1. Private Sub Worksheet_Deactivate()
  2. MsgBox "You are leaving this sheet Q47"
  3. End Sub

While leaving this sheet, a msgbox will pop up, meaning that, Deactivate event has triggered.

The screenshot of the above codes in the editor are as shown below:

excel vba worksheet events

There are lot more events associated with the Worksheet, which can be tried on your own as an exercise.

 

You can find similar Excel Questions and Answer hereunder

1) How can I loop through all WorkSheets and get their names using VBA?

2) How do I add a shape using VBA?

3) How to change the color of gridlines in a worksheet in Excel

4) How to print a worksheet in Excel

5) How can I export a WorkSheet as a PDF using VBA?

6) How can I add a background image to a worksheet?

7) How can I identify all cells with Conditional Formatting in my WorkSheet?

8) What are the various functions of the worksheet in Excel VBA

9) How to print a worksheet in Excel VBA

10) How to do worksheet protection with VBA in Excel

 

Here the previous and next chapter