为什么应用程序级别的 SelectionChange 事件不起作用?
Why is SelectionChange event at the application level not working?
我创建了一个小宏来 return 唯一值的数量,并在选择范围时将其显示在 Excel 的状态栏中。这在文档级别工作正常。但是,当我尝试在应用程序级别 运行 时,SelectionChange
事件没有启动。以下是我的。
Class 模块 'ExcelEventCapture'
Option Explicit
Public WithEvents ExcelApp As Application
Private Sub ExcelApp_SelectionChange(ByVal Target As Range)
If TypeName(Target) = "Range" Then
Application.StatusBar = "Unique Count: " & CountUnique(Target)
End If
End Sub
Private Function CountUnique(rng As Range) As Long
Dim dict As Dictionary
Dim cell As Range
Set dict = New Dictionary
For Each cell In rng.Cells
If cell.Value2 <> 0 Then
If Not dict.Exists(cell.Value) Then
dict.Add cell.Value, 0
End If
End If
Next
CountUnique = dict.Count
End Function
本工作簿
Option Explicit
Dim myobject As New ExcelEventCapture
Sub Workbook_Open()
Set myobject.ExcelApp = Application
End Sub
我错过了什么?谢谢
SelectionChange
Application class 中不存在事件。
您可以使用 SheetSelectionChange 事件,无需检查 Target
class 名称。
Private Sub ExcelApp_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
Application.StatusBar = "Unique Count: " & CountUnique(Target)
End Sub
我创建了一个小宏来 return 唯一值的数量,并在选择范围时将其显示在 Excel 的状态栏中。这在文档级别工作正常。但是,当我尝试在应用程序级别 运行 时,SelectionChange
事件没有启动。以下是我的。
Class 模块 'ExcelEventCapture'
Option Explicit
Public WithEvents ExcelApp As Application
Private Sub ExcelApp_SelectionChange(ByVal Target As Range)
If TypeName(Target) = "Range" Then
Application.StatusBar = "Unique Count: " & CountUnique(Target)
End If
End Sub
Private Function CountUnique(rng As Range) As Long
Dim dict As Dictionary
Dim cell As Range
Set dict = New Dictionary
For Each cell In rng.Cells
If cell.Value2 <> 0 Then
If Not dict.Exists(cell.Value) Then
dict.Add cell.Value, 0
End If
End If
Next
CountUnique = dict.Count
End Function
本工作簿
Option Explicit
Dim myobject As New ExcelEventCapture
Sub Workbook_Open()
Set myobject.ExcelApp = Application
End Sub
我错过了什么?谢谢
SelectionChange
Application class 中不存在事件。
您可以使用 SheetSelectionChange 事件,无需检查 Target
class 名称。
Private Sub ExcelApp_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
Application.StatusBar = "Unique Count: " & CountUnique(Target)
End Sub