Question

I am trying to correlate data that is pulled from a huge database. I have no control over the database, so renaming fields is not an option. I had to separate data from different database tables onto different sheets. I'm trying to write a function in excel to return specific vlookup values based on a single criteria. The "itemnum" values are in column A and the "binnum" values are in column K. I need to be able to use the function for a sheet that has 19,000 unique values for "itemnum". The problem is, I don't know the syntax for using vlookup in VBA. Here is an example of what I'm trying to do:

Function orders(itemnum, binnum)
If binnum = "ibp" Then
orders = IF(ISNA(VLOOKUP(AllLocations!A2,OpenIBP!A:B,1,FALSE)), 0, VLOOKUP(AllLocations!A2,OpenIBP!A:B,2,FALSE))
Else
orders = =IF(ISNA(VLOOKUP(AllLocations!A2,OpenIST!A:B,1,FALSE)), 0, VLOOKUP(AllLocations!A2,OpenIST!A:B,2,FALSE))
End If

End Function

Can anyone help me rewrite this so it works? I'm in way over my head. Thanks.

Was it helpful?

Solution 2

To bridge the gap between the code sample that you had, and the answer that user3423985 gave, here is a variation (assuming that I understand what you were trying to do):

Option Compare Text
Function orders(itemnum, binnum)
' look up itemnum in either sheet OpenIBP or sheet OpenIST
' depending on the value of binnum

Dim sheetName As String
If binnum = "ibp" Then
  sheetName = "OpenIBP"
Else
  sheetName = "OpenIST"
End If

Dim sh As Worksheet
Set sh = ActiveWorkbook.Sheets(sheetName)

' now we can look up something in the sheet:

Dim value

' Look up the value itemnum
' in column A of sheet sh
' return the corresponding value in column 2
' return exact match only
value = Application.VLookup(itemnum, sh.[A:B], 2, False)

' check for error in lookup
If IsError(value) Then
  MsgBox "Item " & itemnum & " not found!"
Else
  orders = value
End If

End Function

OTHER TIPS

You can use it like this:

V=application.vlookup("A",range("A1:B5"),2,0)
If iserror(v) then
 Msgbox "Fail"
Else
 Msgbox v
End if

V is a variant, I am looking for "A" column A, and return value in B

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top