Marie
Marie

Reputation: 1

IfError function using vlookup in VBA

I am trying to use a vlookup function to search for a value in multiple worksheets that are in a separate workbook.

I am trying to use the IfError function with the vlookup but I am not formatting it correctly.

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

Upvotes: 0

Views: 30850

Answers (1)

Niclas
Niclas

Reputation: 1262

Try this. You need to work with WorksheetFunction when using Iferror and you need to use Application.VLookup (read here: http://dailydoseofexcel.com/archives/2004/09/24/the-worksheetfunction-method/).
Also VBA VLookup is sensitive to datatypes, so when you define item as string it will not work. Instead you should use Variant to be covered in.
Dim item As Variant

Also you need to define these ranges as Range. With your current code, you only define cprange as a actual range.
Use this instead: 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), "")))))  

In generel, it is good practice to use Option Explicit. Put this at the absolute first line in your module (outside your procedure).

Upvotes: 1

Related Questions