Home » excel » vba – Malformed VLookup formula when trying to use Range.Formula property

vba – Malformed VLookup formula when trying to use Range.Formula property

Posted by: admin May 14, 2020 Leave a comment


I have Excel sheets that will have data from many sources that will be grouped together so that what needs to be looked upon is above what you are looking from so there will be many VLookups on separate portions of one sheet.

Sub linkFDCfdv()
Dim doesFDChaveDescription As Boolean
Dim isLastRowFDC As Boolean
Dim myRange As String
Dim firstFDCrow As Long
Dim lastFDCrow As Long
While Len(Selection.Value) > 0

    If Selection.Value = "FDC" Then

        If isLastRowFDC = False Then
            firstFDCrow = ActiveCell.Row

        End If

        isLastRowFDC = True

        ActiveCell.Offset(0, 3).range("A1").Select

        If Len(Selection.Value) > 0 Then
            doesFDChaveDescription = True
            doesFDChaveDescription = False
        End If
        ActiveCell.Offset(0, -3).range("A1").Select
        If isLastRowFDC = True Then
            lastFDCrow = ActiveCell.Row - 1
        End If

    End If

    If Selection.Value = "FDV" Then

        ActiveCell.Offset(0, 10).range("A1").Select

        myRange = "B" & firstFDCrow & ":D" & lastFDCrow

        ActiveCell.Formula = "=VLOOKUP(R[0]C[-2]," & myRange & ",2)"

        ActiveCell.Offset(0, -10).range("A1").Select
    End If

    ActiveCell.Offset(1, 0).range("A1").Select


End Sub

What’s happening is that my macro makes the formula:


If I take out the ' marks the macro works perfectly.

How to&Answers:

That is because you are using a mix of R1C1 style with A1 style. Is this what you are trying?

ActiveCell.Formula = "=VLOOKUP(" & ActiveCell.Offset(,-2).Address & _
                     "," & myRange & ",2)"