Use VLOOKUP in code

User avatar
agibsonsw
SilverLounger
Posts: 2403
Joined: 05 Feb 2010, 22:21
Location: London ENGLAND

Use VLOOKUP in code

Post by agibsonsw »

Hello. Excel 2003.

I'm using Application.WorksheetFunction.Vlookup in my code. But how can I catch the #N/A error?
I can do so with error handling code but this is not very elegant.

Thanks, Andy.
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.

User avatar
HansV
Administrator
Posts: 78665
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Use VLOOKUP in code

Post by HansV »

Use Application.VLookup instead of Application.WorksheetFunction.VLookup. If there is no match, Application.VLookup doesn't raise an error, but it returns an error value instead. You must declare the receiving variable as a Variant:

For example:

Code: Select all

Dim varLookup As Variant
varLookUp = Application.VLookup(3, Range("A1:B200"), 2, False)
If IsError(varLookup) Then
  ' code to run if VLookup returns an error
  ...
Else
  ' do something with varLookup
  ...
End If
Best wishes,
Hans

User avatar
agibsonsw
SilverLounger
Posts: 2403
Joined: 05 Feb 2010, 22:21
Location: London ENGLAND

Re: Use VLOOKUP in code

Post by agibsonsw »

Thank you.
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.