【问题标题】:Unreliable behavior - Excel VBA Code - Precedents.Count Statement [duplicate]不可靠的行为 - Excel VBA 代码 - Precedents.Count 语句 [重复]
【发布时间】:2018-04-21 10:13:07
【问题描述】:

这显然是一个非常简单的 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

如果选择中的单元格具有先例,则消息框单元格地址。如果出错,请继续执行 For 循环中的 Next Cell。

这段代码给出了

运行时错误 1004 '未找到单元格'

尽管有 On Error 语句。具有讽刺意味的是,它在第​​一个实例中正确跳过,但在此 GIF 截图中看到的下一个错误。

Selection C2:C4 C2 =SUM(A1+A2)(消息框),C3 =7+9(正确转义)C4 =7+9

(运行时错误 1004)

我很困惑我在这里犯了什么错误。只需提及它是 Excel 2013 SP1 和 VBA 工具-->选项-->常规-->错误捕获-->在未处理的错误上中断默认选中。任何进一步的帮助都会很棒。谢谢。

GIF 截图

【问题讨论】:

标签: vba excel runtime-error


【解决方案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

【讨论】:

    【解决方案2】:

    问题在于您的错误处理

    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“重置”它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多