Forum Discussion

leisaellemor's avatar
leisaellemor
Copper Contributor
Dec 01, 2023

Custom Number Filtering

I am wanting to create a Custom Number Autofilter which draws the information from a cell. Basically from the image below, I want to filter the column by amounts "less than" the amount shown in the c...
  • djclements's avatar
    djclements
    Dec 01, 2023

    leisaellemor To automate this with VBA, open the Visual Basic editor (Alt+F11). In the left-hand pane under VBAProject > Microsoft Excel Objects, double-click the sheet name that contains your data to open the worksheet module. The code will vary slightly, depending on if your data has been formatted as an Excel Table, or if it's just a regular worksheet range.

     

    Version 1: With a Structured Excel Table

     

    Option Explicit
    
    Private Sub Worksheet_Change(ByVal Target As Range)
    
    'Stop macro if more than once cell was changed
        If Target.Cells.Count > 1 Then Exit Sub
    
    'Apply filter if the criteria cell was changed
        Dim rg As Range
        Set rg = Me.Range("C1")
        If Not Intersect(Target, rg) Is Nothing Then
            Me.ListObjects(1).Range.AutoFilter Field:=3, criteria1:="<=" & rg.Value
        End If
    
    End Sub

     

    Version 2: With a Worksheet Range

     

    Option Explicit
    
    Private Sub Worksheet_Change(ByVal Target As Range)
    
    'Stop macro if more than once cell was changed
        If Target.Cells.Count > 1 Then Exit Sub
    
    'Apply filter if the criteria cell was changed
        Dim rg As Range
        Set rg = Me.Range("C1")
        If Not Intersect(Target, rg) Is Nothing Then
            Dim rgData As Range
            Set rgData = Me.Range("A2").CurrentRegion
            Set rgData = rgData.Offset(1).Resize(rgData.Rows.Count - 1)
            rgData.AutoFilter Field:=3, Criteria1:="<=" & rg.Value
        End If
    
    End Sub

     

    Note: since the screenshot of your data does not reveal the worksheet column letters or rows numbers, I made the assumption that the table begins in cell A2, the column to filter is Field:=3 and the criteria to filter by is in cell C1. Please adjust the range references and field number, if necessary.

     

    Also, Range("A2").CurrentRegion was used here to identify the entire data range. This method will only work properly if your data range does not contain any completely blank rows or columns... the CurrentRegion method identifies all adjacent data in the same manner that pressing Ctrl+Shift+8 (*) will highlight all adjacent data to the active cell. If your data contains additional adjacent cells above the header row, you may need to adjust the Offset and Resize numbers accordingly.

     

    Then, just input a new value in the criteria cell to refresh the filter.

Resources