【问题标题】:Why doesn't isError( ) work with a vlookup statement in excel VBA为什么 isError() 不适用于 excel VBA 中的 vlookup 语句
【发布时间】:2013-06-18 19:53:39
【问题描述】:

我正在使用 excel 2007 并创建了一个包含三个 vlookup() 语句的 UDF。该函数应该返回所有三个 vlookup 语句的总和。在大多数情况下,只有两个 vlookup() 语句将返回有效值,第三个语句将导致 NA,因为查找值不包含在查找范围内。

我已尝试使用以下方法捕获错误并返回零:

  1. Application.WorksheetFunction.iferror(vlookup(...) ,0)

  2. 使用 If iserror(vlookup()) then ... 的条件句

但我似乎无法采用任何一种方法来工作。如果我注释掉我知道正在创建错误的 vlookup,一切都会按预期工作。

有谁知道为什么 iserror(0 和 iserror() 似乎不起作用,或者可能是另一种可行的方法。

更新:

下面是三个vlookup函数:

product2 = Application.WorksheetFunction.IfError(Application.WorksheetFunction.VLookup(productA, lookuprng, offset, False), 0)

product3 = Application.WorksheetFunction.IfError(Application.WorksheetFunction.VLookup(productB, lookuprng, offset, False), 0)

product4 = Application.WorksheetFunction.IfError(Application.WorksheetFunction.VLookup(productC, lookuprng, offset, False), 0)

【问题讨论】:

  • 你能发布你的代码吗?

标签: excel excel-2007 vba


【解决方案1】:

您可以使用以下方法捕获错误:

Sub HandleVlookupErrors()
    Dim result As Variant

    result = Application.VLookup(productA, lookuprng, offset, False)
    If IsError(result) Then result = 0

End Sub

完整解释请见Error Handling Within Worksheet Functions

【讨论】:

    【解决方案2】:

    您可以考虑编写一个带有错误处理行的 vlookup 函数:

    Public Function v_lookup(lookup_value As String, table_array As Range, col_index_num As Integer, range_lookup As Boolean) As String
    
    Dim result As Variant
    result = Application.VLookup(lookup_value, table_array, col_index_num, range_lookup)
    
    If IsError(result) Then result = ""
    v_lookup = result
    
    End Function
    

    【讨论】:

      【解决方案3】:
      Dim Res as Variant
      Res = Application.WorksheetFunction.VLookup(Vndr, Range("A:a"), 1, False) 'Where Vndr is some unknown
      If Res = Vndr then 
          do xyz
      Else
          do 123
      endif
      

      【讨论】:

      • 没有解释的代码转储很少有用。请编辑您的答案以包含一些上下文。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-04
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 2014-08-14
      • 1970-01-01
      相关资源
      最近更新 更多