标签:VBA,类模块
如下图1所示,单击工作簿中任意工作表单元格时,会弹出一个消息框,显示鼠标单击的单元格地址。
图1
在VBE中,插入一个类模块,将其重命名为“C_CellClickEvent”,并输入下面的代码:
Private WithEvents CmBrasEvents As CommandBars
Private WithEvents wbEvents As Workbook
Event CellClick(ByVal Target As Range)
Private Type POINTAPI
x As Long
Y As Long
End Type
Private Type KeyboardBytes
kbByte(0 To 255) As Byte
End Type
#If VBA7 Then
Private Declare PtrSafe Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Declare PtrSafe Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer
Private Declare PtrSafe Function GetActiveWindow Lib "user32" () As LongPtr
Private Declare PtrSafe Function GetKeyboardState Lib "user32" (kbArray As KeyboardBytes) As Long
Private Declare PtrSafe Function SetKeyboardState Lib "user32" (kbArray As KeyboardBytes) As Long
#Else
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer
Private Declare Function GetActiveWindow Lib "user32" () As Long
Private Declare Function GetKeyboardState Lib "user32" (kbArray As KeyboardBytes) As Long
Private Declare Function SetKeyboardState Lib "user32" (kbArray As KeyboardBytes) As Long
#End If
Private kbArray As KeyboardBytes
Private oPrevSelection As Range
Private Sub Class_Initialize()
Set CmBrasEvents = Application.CommandBars
Set wbEvents = ThisWorkbook
GetKeyboardState kbArray
kbArray.kbByte(vbKeyLButton) = 1
SetKeyboardState kbArray
End Sub
Private Sub Class_Terminate()
Set CmBrasEvents = Nothing
Set wbEvents = Nothing
End Sub
Private Sub CmBrasEvents_OnUpdate()
Dim tpt As POINTAPI
On Error Resume Next
GetKeyboardState kbArray
If GetActiveWindow <> Application.hwnd Then Exit Sub
GetCursorPos tpt
If GetKeyState(vbKeyLButton) = 1 Then
If TypeName(ActiveWindow.RangeFromPoint(tpt.x, tpt.Y)) = "Range" Then
If oPrevSelection.Address = ActiveWindow.RangeFromPoint(tpt.x, tpt.Y).Address Then
RaiseEvent CellClick(Selection)
End If
End If
End If
kbArray.kbByte(vbKeyLButton) = 0
SetKeyboardState kbArray
End Sub
Private Sub wbEvents_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
On Error Resume Next
Set oPrevSelection = Target
End Sub
在VBE中,双击工程资源管理器中的“ThisWorkbook”,打开其代码模块,并输入下面的代码:
Private WithEvents Wb As C_CellClickEvent
Private Sub Workbook_Open()
Set Wb = New C_CellClickEvent
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Set Wb = Nothing
End Sub
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
If Wb Is Nothing Then
Set Wb = New C_CellClickEvent
End If
End Sub
'单元格Click事件处理
Private Sub Wb_CellClick(ByVal Target As Range)
With Target
.Font.Bold = True
.Font.Name = IIf(.Value = "", "Wingdings", "calibri")
.Value = IIf(.Value = "", "?", "")
MsgBox "你单击的单元格: " & vbLf & .Address(External:=True), vbInformation
End With
End Sub
欢迎在下面留言,完善本文内容,让更多的人学到更完美的知识。