Search code examples
excelvbaeventscriteriaautofilter

How to auto filter many columns together?


I am working on Excel sheet in which I want to filter many columns together. For example, I have columns from B to G and there are data validations lists on the first cell of each columns to select. I made the code when we select the data the column changes. When I apply the same on the next column, I get the data on the second column, but it removes the filter on the first column. What I want is to process filters on all columns together,

Here is my code:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim lastrow As Long
lastrow = Cells(Rows.Count, "C").End(xlUp).Row
With Me
If Not Intersect(Target, .Range("B1")) Is Nothing Then
If Target.Value <> "" Then
.AutoFilterMode = False
.Range("B2:B" & lastrow).AutoFilter Field:=1, Criteria1:=Target.Value
End If
End If
If Not Intersect(Target, .Range("C1")) Is Nothing Then
If Target.Value <> "" Then
.AutoFilterMode = False
.Range("C2:C" & lastrow).AutoFilter Field:=1, Criteria1:=Target.Value
End If
End If
End With
End Sub

What I need to do to make the two filters work together.


Solution

  • I think you want this:

    Private Sub Worksheet_Change(ByVal Target As Range)
    Dim lastrow As Long
    Dim rCriteria As Range
    Dim i As Long
    lastrow = Cells(Rows.Count, "C").End(xlUp).Row
    With Me
      Set rCriteria = .Range("B1:C1")
      If Not Intersect(Target, rCriteria) Is Nothing Then
        .AutoFilterMode = False
        For i = 1 To rCriteria.Count
          If rCriteria(i) <> "" Then
            .Range("B2:C" & lastrow).AutoFilter Field:=i, Criteria1:=rCriteria(i)
          End If
        Next
      End If
    End With
    End Sub