VBA Course: Worksheet Events
On the last page, we looked at events related to the entire workbook. on this page, we'll move on to focus on events linked to a single worksheet.
Worksheet_SelectionChange
To execute instructions based on events for a particular worksheet, select the sheet in the editor, and then Worksheet :
The SelectionChange event will be added by default. This event is executed whenever the selection is changed :
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
End Sub
For example, the code below adds background colors to one or more selected cells and automatically removes the background color from the previous selection when the selection is changed :
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
Worksheet_Activate
This event will fire when the worksheet is activated :
Private Sub Worksheet_Activate()
End Sub
Worksheet_Deactivate
This event will fire when another worksheet is activated :
Private Sub Worksheet_Deactivate()
End Sub
Worksheet_BeforeDoubleClick
This event will fire when a cell in the worksheet is double clicked :
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
End Sub
Worksheet_BeforeRightClick
This event will fire when the user right clicks on the worksheet :
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
End Sub
Worksheet_Calculate
This event will fire when the data on the worksheet are calculated or recalculated :
Private Sub Worksheet_Calculate()
End Sub
Worksheet_Change
This event will fire when the contents of cells in the worksheet are changed :
Private Sub Worksheet_Change(ByVal Target As Range)
End Sub
Worksheet_FollowHyperlink
This event will fire when the user clicks on a hypertext link :
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
End Sub
Temporarily deactivate all events
To execute code without firing any events, put it between the following two lines of code :
Application.EnableEvents = False ' => deactivate events
'Instructions
Application.EnableEvents = True ' => reactivate events
'컴퓨터관련' 카테고리의 다른 글
windows PE, RE, WIM...펌 (0) | 2016.10.09 |
---|---|
아래아한글 체크박스, 문자표입력...펌 (0) | 2016.09.21 |
vnc supports only the display, not audio...펌 (0) | 2016.06.08 |
powershell -command quotes, escape by backslash, &"" in powershell...펌 (0) | 2016.05.08 |
powershell escaping quotes, backtick...펌 (0) | 2016.05.08 |