use*_*025 5 error-handling vba excel-formula vlookup powerpoint-vba
我正在使用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
Run Code Online (Sandbox Code Playgroud)
我使用以下语句从主宏调用此函数:
varGatherNumber = v_lookup(varDateTime, Lit_Sched_Table_Lookup, 5, vbFalse)
Run Code Online (Sandbox Code Playgroud)
没有错误时,此代码很有效.问题是,当查找失败时,我被抛入Debug指向,
varResult = objExcelAppVL.Application.WorksheetFunction.VLookup
Run Code Online (Sandbox Code Playgroud)
..声明.If IsError(varResult)...当出现vlookup错误时,它永远不会出现在语句中.如何正确捕获vLookup错误?
小智 5
所述WorksheetFunction对象不传递误差值回的变体; 它只是呛到它们.使用不带WorksheetFunction 的Excel Application对象可以使用错误值.您已经创建了一个Excel.Application对象; 用那个.
通过使对象变量声明为静态,可以避免使用CreateObject函数重复调用构造(和销毁)应用程序对象.这在可以沿长列复制的UDF中特别有用.
编写本机工作表VLOOKUP函数以允许完整的列引用而不会受到惩罚; 截断对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
Run Code Online (Sandbox Code Playgroud)
我看到你特意传回一个字符串,所以数字和日期将是他们的文本等价物.我认为这是在PowerPoint中接收值的最佳方式.