我使用的是Office 2007.我有一个PowerPoint宏,它使用Excel工作表来执行vLookup。我为vLookup创建了一个公共函数。当正确提供所有值时,它运行良好。现在,我试图捕获无法找到查找值的条件的错误。功能代码是:
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)
此代码在没有错误时效果很好。问题是,当查找失败时,我将调入指向
的Debug varResult = objExcelAppVL.Application.WorksheetFunction.VLookup
..声明。当出现vlookup错误时,它永远不会进入If IsError(varResult)...
语句。如何正确捕获vLookup错误?
答案 0 :(得分:5)
WorksheetFunction object不会将错误值传递回变体;它只是呛到它们。使用没有WorksheetFunction的Excel Application object可以使用错误值。您已经创建了一个Excel.Application对象;用那个。
通过使对象变量声明为静态,可以避免重复调用构造(并销毁)具有CreateObject function的应用程序对象。这在可以在长列中复制的UDF中特别有用。
编写本机工作表VLOOKUP function以允许完整的列引用而不会受到惩罚;截断对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中接收值的最佳方式。