In my program, the user enters an index code and receives as output information related to the postcode (province, city, district). For this, I use the Vlookup function. So user:
- Creates a zip code on the main sheet
- Search for a program in a database (on another sheet) in which a zip code is associated with a city, province, district.
- When there is a match, it sends the result to the main pages, so the user can get the city, province, district by simply typing the index code. Pretty simple process.
I use this code for this:
If Range("J9").Value <> "N/A" Then 'if there is actually a zip code entered by the user (if not, it will be "N/A") cityZip = Application.WorksheetFunction.VLookup(sMain.Range("J9").Value, sZipCodes.Range("B2:E864"), 3, False) barangayZip = Application.WorksheetFunction.VLookup(sMain.Range("J9").Value, sZipCodes.Range("B2:E864"), 2, False) provinceZip = Application.WorksheetFunction.VLookup(sMain.Range("J9").Value, sZipCodes.Range("B2:E864"), 4, False) sMain.Range("J7").Value = provinceZip sMain.Range("J13").Value = cityZip sMain.Range("J16").Value = barangayZip Else End If
It works great when there is a zip code that is in my database. But if not, it leads to a crash in the program, and I get an error message (for example, "runtime error 1004", unable to read Vlookup ...). How do I change my code to just say that if there is no match, then it just has to do nothing? I do not know how to enter this query into the Vlookup function.
Thanks in advance!
EDIT: here is my new code after Tim Williams' suggestion:
'Using Zip Code If Range("J9").Value <> "N/A" Then provinceZip = Application.Lookup(sMain.Range("J9").Value, sZipCodes.Range("B2:E907"), 4, False) If IsError(provinceZip) = False Then cityZip = Application.Lookup(sMain.Range("J9").Value, sZipCodes.Range("B2:E907"), 3, False) barangayZip = Application.Lookup(sMain.Range("J9").Value, sZipCodes.Range("B2:E907"), 2, False) sMain.Range("J7").Value = provinceZip sMain.Range("J13").Value = cityZip sMain.Range("J16").Value = barangayZip Else 'do nothing End If End If
My error on this line:
provinceZip = Application.Lookup(sMain.Range("J9").Value, sZipCodes.Range("B2:E907"), 4, False)
=> Error 1004, invalid number of arguments