Haaris Ali
Haaris Ali

Reputation: 31

Setting the table_array in a VLOOKUP in VBA excel

I am trying vlookup in VBA. I am referencing to another sheet within the same workbook but i am getting #NAME? as a result.

Sub MatchNames()

l_row = Worksheets("Lookup").Cells(Rows.Count, 1).End(xlUp).Row
lookup_range = Worksheets("Lookup").Range("A2:E" & l_row)

Final_row = Cells(Rows.Count, 6).End(xlUp).Row

    With Range("BG2:BG" & Final_row)
        .FormulaR1C1 = "=vlookup(RC[-52],lookup_range, 2, False)"

    End With

End Sub

Upvotes: 2

Views: 1123

Answers (1)

user4039065
user4039065

Reputation:

Try,

l_row = Worksheets("Lookup").Cells(Rows.Count, 1).End(xlUp).Row
Set lookup_range = Worksheets("Lookup").Range("A2:E" & l_row)  '<~~one edit here

With Range("BG2:BG" & Final_row)
    .FormulaR1C1 = "=vlookup(RC[-52]," & lookup_range.address(referencestyle:=xlR1C1, external:=true) & ", 2, False)"  '<~~another edit here
End With

The Range.Address property can return the entire path and sheet name. Giving too much is not detrimental.

This might be a better method.

    Dim l_row As Long, f_row As Long, sLookup_Range As String

    With Worksheets("Lookup")
        l_row = .Cells(Rows.Count, "A").End(xlUp).Row
        sLookup_Range = .Range("A2:E" & l_row).Address(ReferenceStyle:=xlR1C1, external:=True)
    End With

    With Worksheets("Sheet1")
        f_row = .Cells(Rows.Count, "G").End(xlUp).Row
        With .Range("BG2:BG" & f_row)
            .FormulaR1C1 = "=vlookup(RC[-52]," & sLookup_Range & ", 2, False)"
        End With
    End With

Upvotes: 1

Related Questions