Option Explicit
Public Event Click(ByVal Target As Range)
Private Type POINTAPI
x As Long
y As Long
End Type
Private Type MSG
hwnd As Long
Message As Long
wParam As Long
lParam As Long
time As Long
pt As POINTAPI
End Type
Private Declare Function FindWindow Lib "user32.dll" _
Alias "FindWindowA" _
(ByVal lpClassName As String, _
ByVal lpWindowName As String) As Long
Private Declare Function FindWindowEx Lib "user32.dll" _
Alias "FindWindowExA" _
(ByVal hWnd1 As Long, _
ByVal hWnd2 As Long, _
ByVal lpsz1 As String, _
ByVal lpsz2 As String) As Long
Private Declare Function PeekMessage Lib "user32" _
Alias "PeekMessageA" _
(ByRef lpMsg As MSG, ByVal hwnd As Long, _
ByVal wMsgFilterMin As Long, _
ByVal wMsgFilterMax As Long, _
ByVal wRemoveMsg As Long) As Long
Private Declare Function WaitMessage Lib "user32" _
() As Long
Private Const XL_CLASS_NAME As String = "XLMAIN"
Private Const XLDESK_CLASS_NAME As String = "XLDESK"
Private Const XLBOOK_CLASS_NAME As String = "EXCEL7"
Private Const PM_NOREMOVE As Long = &H0
Private Const WM_LBUTTONDOWN As Long = &H201
Private bStopLoop As Boolean
Private Sub Workbook_Open()
If ActiveSheet Is Sheets(1) Then _
Call SetClickEvent(TargetSheet:=Sheets(1))
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Call StopClickEvent
End Sub
Private Sub SetClickEvent(TargetSheet As Worksheet)
Dim tMsg As MSG
Dim lXlhwnd As Long, lDeskhwnd As Long, lBookhwnd As Long
'hook our target worksheet.
CallByName TargetSheet, "Worksheet_", VbSet, ThisWorkbook
'get the workbook hwnd.
lXlhwnd = FindWindow _
(XL_CLASS_NAME, Application.Caption)
lDeskhwnd = FindWindowEx _
(lXlhwnd, 0, XLDESK_CLASS_NAME, vbNullString)
lBookhwnd = FindWindowEx _
(lDeskhwnd, 0, XLBOOK_CLASS_NAME, vbNullString)
'prevent unintentionnal exit of the
'loop if the cancel key is pressed.
Application.EnableCancelKey = xlErrorHandler
On Error GoTo err_Handler
'reinitialize the boolean flag.
bStopLoop = False
Do
'wait for an input msg.
WaitMessage
'did the user perform a mouse click ?
If PeekMessage _
(tMsg, lBookhwnd, _
WM_LBUTTONDOWN, WM_LBUTTONDOWN, PM_NOREMOVE) Then
'are we on our target sheet ?
If ActiveSheet Is TargetSheet Then
'are we clicking a cell ?
If TypeName _
(ActiveWindow.RangeFromPoint(tMsg.pt.x, tMsg.pt.y)) _
= "Range" Then
'If so,execute our custom sheet click event.
DoEvents
RaiseEvent Click(Selection)
End If
End If
End If
'allow the processing of other msgs.
DoEvents
Loop Until bStopLoop
Exit Sub
err_Handler:
Call SetClickEvent(TargetSheet)
End Sub
Private Sub StopClickEvent()
'set this flag to exit the loop.
bStopLoop = True
'reset the normal cancel key behaviour.
Application.EnableCancelKey = xlInterrupt
End Sub
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
If Sh Is Sheets(1) And bStopLoop Then _
Call SetClickEvent(TargetSheet:=Sheets(1))
If Not Sh Is Sheets(1) Then Call StopClickEvent
End Sub