Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to include dynamic VLOOKUP in FormulaR1C1 VBA?

I need to lookup values on another sheet. My formula works great, when i use it manually

=VLOOKUP(TRIM(C2),TRIM('MyDataSheet'!$A$1:$E$500),4,FALSE)

However, I need to be able to plug this formula into a cell dynamically using VBA. This is what I tried:

 Set lookupRange = ThisWorkbook.Sheets("MyDataSheet").Range("A1:E500")
 Set newCol = tbl.ListColumns.Add
 newCol.DataBodyRange.FormulaR1C1 = "=VLOOKUP(TRIM(RC[-16])," & lookupRange.Address(True, True, xlR1C1) & ", 4, FALSE)"

This plugs in formula in Excel like this, BUT completely ignores the different sheet and ignores the second TRIM:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

=VLOOKUP(TRIM(C2),$A$1:$E$500),4,FALSE)

How to write VBA to dynamically insert VLOOKUP as this: =VLOOKUP(TRIM(C2),TRIM('MyDataSheet'!$A$1:$E$500),4,FALSE)

>Solution :

You could do it like this:

Sub Tester()
    
    Dim tbl As ListObject, newCol As ListColumn, c As Range
    
    Set tbl = ActiveSheet.ListObjects(1) 'for example
    Set newCol = tbl.ListColumns.Add
    newCol.Name = "Lookup"

    ' "id" is the column with the values you want to look up
    Set c = tbl.ListColumns("id").DataBodyRange.Cells(1) 
    
    newCol.DataBodyRange.Formula2 = _
         "=VLOOKUP(TRIM(" & c.Address(False, False) & "),TRIM('MyDataSheet'!$A$1:$E$500),4,FALSE)"
    
End Sub
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading