![]()
Excel -- Filters -- AutoFilter Programming
A few examples of controlling AutoFilters through VBA programming.
Show All Records
Turn On AutoFilter
Turn Off AutoFilter
Hide Filter Arrows
Copy Filtered Rows
AutoFilter on a Protected Worksheet
Count Visible Rows
The following code shows all records, if a filter has been applied.
Sub ShowAllRecords() If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData End If End Sub
Use the following code to turn on an AutoFilter, if none exists
Sub TurnAutoFilterOn() 'check for filter, turn on if none exists If Not ActiveSheet.AutoFilterMode Then ActiveSheet.Range("A1").AutoFilter End If End Sub
Use the following code to turn off an AutoFilter, if one exists
Sub TurnFilterOff() 'removes AutoFilter if one exists Worksheets("Data").AutoFilterMode = False End Sub
Perhaps you want users to filter only one of the columns in a table. The following procedure hides the arrows for all columns except column 2.
Sub HideArrows() 'hides all arrows except column 2 Dim c As Range Dim i As Integer i = Cells(1, 1).End(xlToRight).Column Application.ScreenUpdating = False For Each c In Range(Cells(1, 1), Cells(1, i)) If c.Column <> 2 Then c.AutoFilter Field:=c.Column, _ Visibledropdown:=False End If Next Application.ScreenUpdating = True End SubTo show all the arrows, you can use the following code:
Sub ShowArrows() Dim c As Range Dim i As Integer i = Cells(1, 1).End(xlToRight).Column Application.ScreenUpdating = False For Each c In Range(Cells(1, 1), Cells(1, i)) c.AutoFilter Field:=c.Column, _ Visibledropdown:=True Next Application.ScreenUpdating = True End Sub
The following code copies the filtered rows from the active sheet to Sheet2.
Sub CopyFilter() 'by Tom Ogilvy Dim rng As Range Dim rng2 As Range With ActiveSheet.AutoFilter.Range On Error Resume Next Set rng2 = .Offset(1, 0).Resize(.Rows.Count - 1, 1) _ .SpecialCells(xlCellTypeVisible) On Error GoTo 0 End With If rng2 Is Nothing Then MsgBox "No data to copy" Else Worksheets("Sheet2").Cells.Clear Set rng = ActiveSheet.AutoFilter.Range rng.Offset(1, 0).Resize(rng.Rows.Count - 1).Copy _ Destination:=Worksheets("Sheet2").Range("A1") End If ActiveSheet.ShowAllData End Sub
You can display a message that shows a count of the rows that are visible after a filter has been applied:
Sub CountVisRows() 'by Tom Ogilvy Dim rng As Range Set rng = ActiveSheet.AutoFilter.Range MsgBox rng.Columns(1). _ SpecialCells(xlCellTypeVisible).Count - 1 _ & " of " & rng _ .Rows.Count - 1 & " Records" End Sub
- AutoFilter Basics
- AutoFilter Tips
- AutoFilter Programming