不可靠的行为 - Excel VBA代码 - Precedents.Count语句

时间:2017-11-08 16:14:28

标签: vba excel-vba runtime-error excel

我有一个非常简单的Excel VBA Sub。

Public Sub CheckRef()

Dim Cell As Range

For Each Cell In Selection
    On Error GoTo MyNext
    If IsNumeric(Cell.Precedents.Count) Then
        MsgBox (Cell.Address)
    End If

MyNext:
Next Cell

End Sub

如果选择中的单元格具有Precedents,Message Box单元格地址。如果它出错,只需进入For循环中的Next Cell。

此代码提供

  

运行时错误1004'没有找到细胞'

尽管On Error声明。具有讽刺意味的是,它在第​​一个实例中正确地跳过,但是在此屏幕截图中看到GIF时会出现错误。

Selection C2:C4 C2 =SUM(A1+A2)(Msgbox),C3 =7+9(正确逃脱)C4 =7+9

  

(运行时错误1004)

我很困惑我在这里犯了什么错误。仅提及它是Excel 2013 SP1和VBA工具 - >选项 - >常规 - >错误陷印 - >默认情况下选择中断未处理错误。任何进一步的帮助都会很棒。感谢。

GIF

的屏幕截图

Screenshot to GIF

2 个答案:

答案 0 :(得分:1)

另一种方式:

Public Sub CheckRef()

    Dim Cell As Range, qwerty As Range

    For Each Cell In Selection
        Set qwerty = Nothing
        On Error Resume Next
            Set qwerty = Cell.Precedents
        On Error GoTo 0
        If Not qwerty Is Nothing Then
            MsgBox (Cell.Address)
        End If
    Next Cell
End Sub

答案 1 :(得分:0)

问题在于您的错误处理

Public Sub CheckRef()

Dim Cell As Range

For Each Cell In Selection
    On Error GoTo MyNext
    If IsNumeric(Cell.Precedents.Count) Then
        MsgBox (Cell.Address)
    End If
MyNext:
Resume MyNext2:
MyNext2:
Next Cell

End Sub

您的错误处理已在第一个循环中使用,因此上述问题已修复为使用resume“重置”它。