JBu*_*ace 15 excel vba excel-vba
我有这个代码:
Dim wsFunc As WorksheetFunction: Set wsFunc = Application.WorksheetFunction
Dim ws As Worksheet: Set ws = Sheets("2012")
Dim rngLook As Range: Set rngLook = ws.Range("A:M")
'within a loop
currName = "Example"
cellNum = wsFunc.VLookup(currName, rngLook, 13, False)
Run Code Online (Sandbox Code Playgroud)
预计VLookup不会总能找到结果; 但是当它没有找到结果时,我甚至可以在错误检查下一行之前将错误输出.
错误:
运行时错误'1004':无法获取WorksheetFunction类的VLookup属性
找到结果时,它工作正常.在这里处理错误的好方法是什么?
Dou*_*ncy 51
而不是WorksheetFunction.Vlookup,你可以使用Application.Vlookup.如果设置Variant等于this,则如果未找到匹配则返回错误2042.然后,您可以测试变种- cellNum在这种情况下-有IsError:
Sub test()
Dim ws As Worksheet: Set ws = Sheets("2012")
Dim rngLook As Range: Set rngLook = ws.Range("A:M")
Dim currName As String
Dim cellNum As Variant
'within a loop
currName = "Example"
cellNum = Application.VLookup(currName, rngLook, 13, False)
If IsError(cellNum) Then
MsgBox "no match"
Else
MsgBox cellNum
End If
End Sub
Run Code Online (Sandbox Code Playgroud)
这些和函数的Application版本允许您在不引发错误的情况下测试错误.如果您使用该版本,则需要进行复杂的错误处理,将代码重新路由到错误处理程序,返回到要评估的下一个语句等.使用这些函数,您可以避免这种混乱.VLOOKUPMATCHWorksheetFunctionApplication
使用该IIF功能可以进一步简化上述内容.这个方法并不总是合适的(例如,如果你必须根据它做更多/不同的过程If/Then)但是在这种情况下你只是想确定在MsgBox中显示什么提示,它应该工作:
cellNum = Application.VLookup(currName, rngLook, 13, False)
MsgBox IIF(IsError(cellNum),"no match", cellNum)
Run Code Online (Sandbox Code Playgroud)
考虑那些方法而不是 On Error ...语句.它们更容易阅读和维护 - 很少有事情比试图遵循一堆GoTo和Resume语句更令人困惑.
有一种方法可以跳过代码中的错误并继续循环,希望它有所帮助:
Sub new1()
Dim wsFunc As WorksheetFunction: Set wsFunc = Application.WorksheetFunction
Dim ws As Worksheet: Set ws = Sheets(1)
Dim rngLook As Range: Set rngLook = ws.Range("A:M")
currName = "Example"
On Error Resume Next ''if error, the code will go on anyway
cellNum = wsFunc.VLookup(currName, rngLook, 13, 0)
If Err.Number <> 0 Then
''error appeared
MsgBox "currName not found" ''optional, no need to do anything
End If
On Error GoTo 0 ''no error, coming back to default conditions
End Sub
Run Code Online (Sandbox Code Playgroud)