简体   繁体   中英

Autofilter based on a cell values in another workbook

I am trying to filter a table that is located on a different workbook.

Scenario: I have 2 workbooks. WB1 has several drop down menus to filter the data that is on WB2.

I want to filter and copy the data from WB2 based on the multiple criterions on WB1 and paste it on an existing tab on WB1 as well

I have been working on this for about 8 or 9 hours now with no success.

So far this is what I have:

Sub filter_by_cell_value()

    Dim WB1 As Workbook
    Dim WB2 As Workbook
    
    Set WB1 = ActiveWorkbook
    
    Workboooks.Open Filename = "C:\Users\name\Documents\jbl\Extract.xlsb"
    'Capture new workbook
    Set WB2 = ActiveWorkbook
    
    With ActiveWorkbook.Sheets("AU06").AutoFilterMode = False
        'Workbook("Extract.xlsb").Sheets ("AU06")
    .AutoFilter Field = 2, Criteria1:="=" & ThisWorkbook.Sheets("Appendix 2").Cells(2, 9).Value
    .SpecialCells(xlCellTypeVisible).Copy
    End With
    
    WB1.Activate
    
    ThisWorkbook.Sheets("AU06").Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
    Range("A1").CurrentRegion.Columns.AutoFit

End Sub

Any help at this point will be greatly appreciated.

I can guess, not having seen your workbooks, that the code might look something like this:

Sub filter_by_cell_value()
    Dim WS1 As Worksheet, WS2 As Worksheet
    
    Set WS1 = ThisWorkbook.Sheets("AU06")
    Set WS2 = Workbooks.Open("C:\Users\name\Documents\jbl\Extract.xlsb").Sheets("AU06")
    
    With WS2
        .AutoFilterMode = False
        With .Range("A1").CurrentRegion ' your own range
            .AutoFilter Field:=2, Criteria1:=WS1.Parent.Sheets("Appendix 2").Cells(2, 9).Text
            .SpecialCells(xlCellTypeVisible).Copy
        End With
    End With
    
    With WS1.Range("A1")
        .PasteSpecial Paste:=xlPasteValuesAndNumberFormats
        .CurrentRegion.Columns.AutoFit
    End With
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM