Search code examples
excelvbamultiple-columnsautofilter

Autofilter VBA Excel not working for multiple columns


I am currently using an autofilter in VBA and it is no longer working. I have tried a load of fixes and nothing seems to have worked. I am filtering on columns X & Z. This is my current code:

    NT.Activate
    AutoFilter = True
    LR = Range("A:A").SpecialCells(xlCellTypeLastCell).Row
    With NT.Range("A1:Z")
   .AutoFilter Field:=26, Criteria1:="Buffalo Bayou"
   .AutoFilter Field:=24, Criteria1:="#N/A"
    If NT.Range("J2:J" & LR).SpecialCells(xlCellTypeVisible).Cells.Count > 1 Then
    NT.Range("A2:W" & LR).SpecialCells(xlCellTypeVisible).Copy
    BB.Sheets("Worksheet").Activate
    LR1 = ActiveSheet.Cells(Rows.Count, "I").End(xlUp).Row
    Range("A" & LR1).Offset(1, 0).PasteSpecial xlPasteAll

Solution

  • This worked for me:

    Sub Macro1()
        Dim NT As Worksheet, wsPaste As Worksheet
        
        Set NT = ThisWorkbook.Worksheets("NT")
        Set wsPaste = BB.Sheets("Worksheet")
        
        With NT.Range("A1:Z" & NT.Cells(Rows.Count, "A").End(xlUp).Row)
            
            .AutoFilter
            .AutoFilter Field:=26, Criteria1:="Buffalo Bayou"
            .AutoFilter Field:=24, Criteria1:="#N/A"
            
            If .Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count > 1 Then
                
                .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Copy
                
                wsPaste.Range("A" & wsPaste.Cells(Rows.Count, "I"). _
                               End(xlUp).Row + 1).PasteSpecial xlPasteAll
                
            End If
        End With
    End Sub