Kevin -- First: Congrats on finding your own solution! I hope you don't mind if I show you a few things here, based on your original solution.
With something like this problem, there are going to be more than a few ways to do it. Rather than show you other ways, I just wanted to show you a few ways to improve your existing solution.
First and foremost, declare all variables, and type them as strongly as allows. This helps avoid hard-to-find errors. On a related note, using Option Explicit
at the top of each module will help enforce this. While it sometimes seems a PITA to declare everything, it's much more inconvenient to spend hours debugging simply typographical errors.
NOTE: In some other languages like python, a line like this implies that answer
is of type string
.
answer = ""
However, in vba, any undeclared variable is of type Variant
, which can essentially be anything. The following two lines will not raise any errors in VBA:
answer = "hello, world!"
Set answer = CreateObject("Wscript.Shell")
If you must use On Error Resume Next
make sure you also do On Error Goto 0
at the earliest possible line to resume normal error-handling, but it is generally preferable to trap and program around anticipated/known error conditions.
I declare answer
as Variant (not as String) in order to use the Application.Vlookup
function which differs slightly from the WorksheetFunction.Vlookup
. The latter will raise error a 1004 error if the value is not found, whereas Application.Vlookup
will return an error-type value, which can be more aptly tested for than using the clunky On Error Resume Next
.
Dim answer as Variant
Dim aValue as String
Dim myRange as Range
aValue = "ABC Company"
Set myRange = Worksheets("Vendor Lookup").Range("A1:D99")
answer = Application.Vlookup(aValue, myRange, 2, False)
If Not IsError(answer) Then MsgBox answer