在VBA中使用vlookup的iferror函数

时间:2016-11-18 19:56:03

标签: excel-vba vba excel

我正在尝试使用vlookup函数在单独工作簿中的多个工作表中搜索值。我试图使用vlookup的iferror函数,但我没有正确格式化它。

Sub CommandButton1_Click()

Dim item As String
    item = 8

Dim brange, rbrange, jrange, cdrange, cprange As range
    Set brange = Workbooks("Library_Database.xlsx")_
                 .Worksheets("BOOKS").range("A2:H51")
    Set rbrange = Workbooks("Library_Database.xlsx")_
                  .Worksheets("REFERENCE BOOKS").range("A2:H51")
    Set jrange = Workbooks("Library_Database.xlsx")_
                 .Worksheets("JOURNALS").range("A2:H51")
    Set cdrange = Workbooks("Library_Database.xlsx")_
                  .Worksheets("CDS").range("A2:H51")
    Set cprange = Workbooks("Library_Database.xlsx")_
                  .Worksheets("CONFERENCE PROCEEDINGS").range("A2:H51")

Dim title As String
    title = IfError(VLookup(item, brange, 2, False), _
            IfError(VLookup(item, rbrange, 2, False), _
            IfError(VLookup(item, jrange, 2, False), _
            IfError(VLookup(item, cdrange, 2, False), _
            IfError(VLookup(item, cprange, 2, False), "")))))

End Sub

请帮助!!!

1 个答案:

答案 0 :(得分:0)

试试这个。使用WorksheetFunction后,您需要使用Iferror,并且需要使用Application.VLookup(请在此处阅读:http://dailydoseofexcel.com/archives/2004/09/24/the-worksheetfunction-method/)。 此外VBA VLookup对数据类型很敏感,因此当您定义item as string时,它将无效。相反,您应该使用Variant Dim item As Variant

您还需要将这些范围定义为Range。使用当前代码,您只需将cprange定义为实际范围 请改用: Dim brange As Range, rbrange As Range, jrange As Range, cdrange As Range, cprange As Range

title = Application.WorksheetFunction.IfError(Application.VLookup(item, brange, 2, False), _
Application.WorksheetFunction.IfError(Application.VLookup(item, rbrange, 2, False), _
Application.WorksheetFunction.IfError(Application.VLookup(item, jrange, 2, False), _
Application.WorksheetFunction.IfError(Application.VLookup(item, cdrange, 2, False), _
Application.WorksheetFunction.IfError(Application.VLookup(item, cprange, 2, False), "")))))  

在genrel中,使用Option Explicit是一种好习惯。将它放在模块的绝对第一行(程序之外)。