【问题标题】:VBA Lookup function giving incorrect number on ErrorVBA 查找函数在错误时给出不正确的数字
【发布时间】:2020-02-12 19:06:10
【问题描述】:

如果您能在下面的代码上帮助我,我将不胜感激。我正在尝试使用 VBA 查找函数进行查找,当查找的值在表数组中不可用时,它会给出错误 1004。我尝试使用“On resume Resume Next”命令在出现错误时跳过,但不是跳过并给出空白结果,而是在其上抛出以前的值。

Sub x()

Dim d As String

Set src = Range("A1:A5") 'list of names needs to be searched
Set Rng = Range("D1:E5") 'table array

On Error Resume Next

For Each cell In src

d = Application.WorksheetFunction.VLookup(cell.Value, Rng, 2, 0)
cell.Offset(0, 1).Value = d

Next cell

End Sub

【问题讨论】:

  • 这个On Error Resume Next 只是隐藏了错误消息,但错误仍然存​​在。它不能解决任何问题,它只是告诉 VBA “如果有错误,请不要显示任何人”。以后不要在没有完整错误处理的情况下使用该行!您可能会从阅读VBA Error Handling – A Complete Guide 中受益

标签: excel vba


【解决方案1】:

如果您删除Worksheetfunction,则不匹配不会引发运行时错误,您可以改为使用IsError() 测试返回值

Sub x()
    Dim src As Range, cell As Range, Rng As Range
    Dim d as Variant  'not String, because it might need to
                      '  hold an error value if no match

    Set src = Range("A1:A5") 'list of names needs to be searched
    Set Rng = Range("D1:E5") 'table array

    For Each cell In src.Cells

        d = Application.VLookup(cell.Value, Rng, 2, 0)
        cell.Offset(0, 1).Value = IIf(IsError(d), "No Match", d)

    Next cell

End Sub

【讨论】:

    【解决方案2】:

    发生的情况是,当您跳过导致 d = Application.WorksheetFunction.VLookup(cell.Value, Rng, 2, 0) 错误的赋值时,之前的值尚未从 d 变量中清除。

    您可以在这里尝试两种方法:
    1.在每次迭代中初始化字符串:

    On Error Resume Next
    For Each cell In src
        d = vbNullString
        d = Application.WorksheetFunction.VLookup(cell.Value, Rng, 2, 0)
        cell.Offset(0, 1).Value = d
    Next cell
    

    2。通过定义标签而不是Resume Next,跳过将字符串分配给单元格:

    On Error Resume NextCell
    For Each cell In src
        d = Application.WorksheetFunction.VLookup(cell.Value, Rng, 2, 0)
        cell.Offset(0, 1).Value = d
    NextCell:
    Next cell
    

    【讨论】:

      猜你喜欢
      • 2015-07-15
      • 2020-04-20
      • 2010-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多