【问题标题】:VBA - Error handling in a do until loop with VlookupVBA - 使用 Vlookup 执行直到循环中的错误处理
【发布时间】:2017-03-22 07:57:42
【问题描述】:

我有一个 do until 循环,它在另一个工作表中查找匹配项,如果给定单元格与条件匹配,则在另一个工作表中返回一个值。

除了条件匹配但另一张表中没有查找匹配之外,代码工作得非常好(这可能会发生,具体取决于我的数据是如何从原始来源收集的,所以它不会打扰我。)

我如何构建一个错误处理程序,以便如果确实发生这种情况 - 即条件匹配但没有查找匹配 - 那么我的代码只会移动到下一行,即下一个 j

图片是我的代码的sn-p

【问题讨论】:

  • 请将您的代码发布为文本而不是图像。
  • 与直接从 VBE 粘贴代码相比,粘贴该屏幕截图所遇到的麻烦更多。
  • 另外...Error Handling topic on Docs.SO 应该是一个很好的起点。

标签: vba excel error-handling vlookup


【解决方案1】:

你可以这样做:

On error Resume Next

您还可以使用以下方式实现更具体的错误处理程序:

On Error Goto ErrorHandler

然后在错误处理程序中:

ErrorHandler:
'Check the Err.Number value and handle it appropriately
'then do something like
Resume Next

【讨论】:

    【解决方案2】:
    Dim res As Variant '<--| declare a Variant variable to hold the result of VLookups
    
    Do Until j = 26
        If Cells(j, i-1).Value= 0  And ... Then
            res = Application.VLookup(... first VlookUp...) '<--| "try" first lookup and store its result in 'res'
            If Not IsError(res) Then '<--| if Vlookup were successful, go ahead
                Sheets("Main").Range("C" & BlankRow2 + 1).FormulaR1C1 = Application.VLookup(... first VlookUp...)
                Sheets("Main").Range("A" & BlankRow2 + 1).FormulaR1C1 = Application.VLookup(... second VlookUp...)
                Sheets("Main").Range("B" & BlankRow2 + 1).FormulaR1C1 = Application.VLookup(... third VlookUp...)
            End If
        End If
        j = j + 1
    Loop
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-30
      • 2014-08-29
      • 2015-02-18
      • 1970-01-01
      • 2017-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多