Search code examples
excelvbarangevlookupnamed-ranges

vlookup in VBA using selection.currentregion in another sheet


i'm new to both macros and vba

I have a pivot table in sheet FR Pivot and a table in sheet Final. I want to pick up the pivot table data and use vlookup to fill in values in my table in the Final sheet. The issue is that the pivot table can be dynamic. So I'm trying the following:

Dim Range1 As Range
    
     With Sheets("FR Pivot")
            
        'Select cell - You can change as per your requirement
        .Range("E4").Select
        
        'Selects the current region
        Selection.CurrentRegion.Select
                
        
        Set Range1 = Selection
        
    End With
    Sheets("Final").Select
    Range("J7").Select
    ActiveCell.FormulaR1C1 = _
        "=IFNA(VLOOKUP([@[Row Labels]],Range1,2,0),""NA"")" 

I think I'm going wrong with the named range part but unable to figure out how to fix it. For the macro, I'm recording my actions and then modifying code to make it dynamic which is why there are so many selects.


Solution

  • Without any selections:

    Dim addr 
    
    addr = Sheets("FR Pivot").Range("E4").Currentregion.Address()
    
    Sheets("Final").Range("J7").Formula = _
            "=IFNA(VLOOKUP([@[Row Labels]], 'FR Pivot'!" & addr & ",2,0),""NA"")"