“Dependents.Count”语句在“Worksheet_SelectionChange”Sub

时间:2016-03-11 05:45:05

标签: excel-vba error-handling onclick dependencies mouseevent

我正在尝试获取所选范围的受抚养人数(如果选择中的单元格数为1)。当我使用下面的代码时,它对所有单元格都没有任何错误(对于没有任何依赖项的单元格和对于具有依赖项的单元格)

'Case 1
Sub Example()
    Dim rng As Excel.Range
    Set rng = Excel.Selection
    If Target.Count = 1 Then
        If HasDependents(rng) Then
            MsgBox rng.Dependents.Count & " dependancies found."
        Else
            MsgBox "No dependancies found."
        End If
    End If
End Sub

Public Function HasDependents(ByVal Something As Excel.Range) As Boolean
    On Error Resume Next
    HasDependents = Something.Dependents.Count
End Function

但是当在Worksheet_SelectionChange中使用相同的逻辑时(如下面的代码所示)

'Case 2
Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
    If Target.Count = 1 Then
        If HasDependents(Target) Then
            MsgBox Target.Dependents.Count & " dependancies found."
        Else
            MsgBox "No dependancies found."
        End If
    End If
End Sub

Public Function HasDependents(ByVal Something As Excel.Range) As Boolean
    On Error Resume Next
    HasDependents = Something.Dependents.Count
End Function

适用于没有任何依赖项的单元格,但对于具有依赖项的单元格“Dependents.Count”重新启动宏。执行后

HasDependents = Something.Dependents.Count

语句,宏重启并执行

Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)

一次。我的问题是为什么宏在执行“Dependents.Count”后重新启动第二种情况?
对于“Worksheet_SelectionChange”,我已将代码区域中的代码放在模块中。

1 个答案:

答案 0 :(得分:2)

要求Dependents property似乎触发了单元格选择事件。此外,每当找不到依赖项时,错误1004:找不到单元格。被抛出。对家属的检索似乎是递归的;进入每个被发现作为依赖者找到另一层家属。

我通过添加一个禁用Application.EnableEvents property的调用来稳定你的过程,这样就不会自己调用例程了。

Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
    If Target.Count = 1 Then
        On Error GoTo bm_Err_Exit
        Dim dc As Long
        Application.EnableEvents = False
        dc = Target.Dependents.Count
        If CBool(dc) Then
            'MsgBox Target.Address(0, 0) & Chr(10) & Chr(10) & _
                    dc & " dependancies found."
            Debug.Print Target.Address(0, 0) & Chr(10) & _
                    dc & " dependancies found."
        Else
            'never reaches here; error 1004 is thrown when no dependents
            'MsgBox "No dependancies found."
            Debug.Print "No dependancies found."
        End If
    End If
bm_Safe_Exit:
    Application.EnableEvents = True
    Exit Sub
bm_Err_Exit:
    Debug.Print Err.Number & ": " & Err.Description
    Application.EnableEvents = True
End Sub

当前选择没有依赖时,基本错误控制报告了1004错误。

¹您可能想要探索DirectDependents property以及Dependents property