Vlookup 和错误

Vlookup and ISERROR

我使用的是 Office 2007。我有一个 PowerPoint 宏,它使用 Excel 工作表来执行 vLookup。我为 vLookup 创建了一个 public 函数。当正确提供所有值时,它会很好地工作。现在,我正在尝试捕获无法找到查找值的那些情况下的错误。函数代码为:

Public Function v_lookup _
            (lookup_value As Variant, _
            table_array As Range, _
            col_index_num As Integer, _
            range_lookup As Boolean) _
            As String

Dim varResult           As Variant
Dim objExcelAppVL       As Object
Set objExcelAppVL = CreateObject("Excel.Application")
objExcelAppVL.Visible = False

varResult = objExcelAppVL.Application.WorksheetFunction.VLookup _
            (lookup_value, _
            table_array, _
            col_index_num, _
            range_lookup)
If IsError(varResult) Then varResult = ""
v_lookup = varResult

objExcelAppVL.Quit
Set objExcelAppVL = Nothing

End Function

我使用以下语句从主宏调用此函数:

varGatherNumber = v_lookup(varDateTime, Lit_Sched_Table_Lookup, 5, vbFalse)

这段代码在没有错误的情况下运行良好。问题是,当查找失败时,我陷入调试,指向

 varResult = objExcelAppVL.Application.WorksheetFunction.VLookup

..声明。当出现 vlookup 错误时,它永远不会到达 If IsError(varResult)... 语句。如何正确捕获 vLookup 错误?

没有 WorksheetFunction 的 WorksheetFunction object does not pass error values back to a variant; it simply chokes on them. Use the Excel Application object 能够处理错误值。您已经创建了一个 Excel.Application 对象;用那个。

通过将对象变量声明设为静态,可以避免使用 CreateObject function 重复调用构造(和破坏)应用程序对象。这在可能被复制到一个长列的 UDF 中特别有用。

本机工作表 VLOOKUP function is written to allow full column referencing without penalty; truncating full column references to the Worksheet.UsedRange 属性 将有助于此功能。

Option Explicit

Public Function v_lookup(lookup_value As Variant, _
                         table_array As Range, _
                         col_index_num As Integer, _
                         Optional range_lookup As Boolean = False) As String

    Dim varResult           As Variant
    Static objExcelAppVL    As Object


    'only create the object if it doesn't exist
    If objExcelAppVL Is Nothing Then
        Set objExcelAppVL = CreateObject("Excel.Application")
        objExcelAppVL.Visible = False
    End If

    'restrict full column references to the worksheet's .UsedRange
    Set table_array = objExcelAppVL.Intersect(table_array.Parent.UsedRange, table_array)

    varResult = objExcelAppVL.VLookup(lookup_value, _
                                      table_array, _
                                      col_index_num, _
                                      range_lookup)

    If IsError(varResult) Then varResult = ""
    v_lookup = varResult

    'do not destruct static vars - they are reused on subsequent calls
    'objExcelAppVL.Quit
    'Set objExcelAppVL = Nothing

End Function

我看到您专门传回了一个字符串,因此数字和日期将是它们的文本等价物。我想这是在 PowerPoint 中接收值的最佳方式。