In the previous lesson, we considered the events related to the whole book. Now we will focus on events related to a single sheet.
To execute event-based instructions for an individual worksheet, select the worksheet in the editor, then Worksheet:
The SelectionChange event will be added by default. This event is fired whenever the content of the range changes:
Private Sub Worksheet_SelectionChange(ByVal Target As Range) End Sub
For example, the following code adds fill colors to one or more selected cells and automatically removes the fill color from the previously selected range when that range changes:
Private Sub Worksheet_SelectionChange(ByVal Target As Range) Static previous_selection As String If previous_selection <> "" Then 'Removing background color from previous selection : Range(previous_selection).Interior.ColorIndex = xlColorIndexNone End If 'Adding background color to current selection : Target.Interior.Color = RGB(181, 244, 0) "Saving the address of the current selection: previous_selection = Target.Address End Sub
This event occurs when a worksheet is activated:
Private Sub Worksheet_Activate() End Sub
This event occurs when another worksheet is activated:
Private Sub Worksheet_Deactivate() End Sub
This event occurs when a worksheet cell is double-clicked:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) End Sub
This event occurs before the right mouse click on the worksheet:
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean) End Sub
This event occurs whenever data in a worksheet is calculated or recalculated:
Private Sub Worksheet_Calculate() End Sub
This event occurs whenever the contents of the cells in the given sheet change:
Private Sub Worksheet_Change(ByVal Target As Range) End Sub
This event occurs when a link (hypertext) is clicked:
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink) End Sub
To execute code without any events, insert it between two lines of code like this:
Application.EnableEvents = False ' => disable events 'Instructions Application.EnableEvents = True ' => re-enable events