为什么应用程序级别的SelectionChange事件不起作用?

时间:2016-06-28 01:48:01

标签: excel vba excel-vba excel-addins

我创建了一个小宏来返回唯一值的数量,并在选择范围时将其显示在Excel的状态栏中。这在文档级别工作正常。但是,当我尝试在应用程序级别运行它时,SelectionChange事件未启动。以下是我所拥有的。

课程模块' 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

的ThisWorkbook

Option Explicit

Dim myobject As New ExcelEventCapture

Sub Workbook_Open()
    Set myobject.ExcelApp = Application
End Sub

我错过了什么?感谢

1 个答案:

答案 0 :(得分:4)

Application课程中不存在

SelectionChange事件。

您可以使用SheetSelectionChange事件,无需检查Target班级名称。

Private Sub ExcelApp_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)    
    Application.StatusBar = "Unique Count: " & CountUnique(Target)
End Sub