将vlookupembedded到excel函数中

我正试图关联从一个巨大的数据库中提取的数据。 我无法控制数据库,所以重命名字段不是一个选项。 我不得不将数据从不同的数据库表中分离出来。 我想在Excel中写一个函数来返回基于单个标准的特定的查找值。 “itemnum”值在列A中,“binnum”值在列K中。我需要能够为具有“itemnum”的19,000个唯一值的工作表使用该函数。 问题是,我不知道在VBA中使用vlookup的语法。 这是我正在尝试做的一个例子:

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 

任何人都可以帮我重写这个,所以它的作品? 我在我头上。 谢谢。

为了弥补你的代码示例和user3423985给出的答案之间的差距,下面是一个变体(假设我理解你正在做的事情):

 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 

你可以像这样使用它:

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

V是一个变体,我正在寻找“A”列A,并在B中返回值