How to Filter Based on Cell Value Using Excel VBA (4 Methods)

Let’s introduce today’s dataset (B4:E15 cell range) as shown in the following screenshot. Here, the Number of Visits for each website is provided along with the Name and Category of the Sites. The dates and mode of Platforms are also given. Let’s filter the table based on a specific cell value.

Dataset


Method 1 – Filter Based on a Certain Cell Value

Let’s put “Education”, one of options for the Category of the Sites, in the G5 cell. We’ll use it to filter the table. That means the row number and column number of the location of the cell are 5 and 7, respectively.

Using the Simple Method

Steps:

  • Open a module by clicking on the Developer tab and selecting Visual Basic.

How to Insert VBA Code

  • Go to Insert and select Module.

How to Insert VBA Code

  • Inside the empty module, copy the following code:
Sub Filter_CellValue1()
ActiveSheet.Range("B4:E15").AutoFilter field:=2, Criteria1:=Cells(5, 7).Value
End Sub

Excel VBA Filter Based on Cell Value

⧭ In the above code, we used the ActiveSheet property and the Range object to assign the entire dataset. Then, we used the AutoFilter method along with the field as 2 and Criteria1 as the value of the G5 cell. The value of the field is 2 since the Category of the Sites is located at the second position from the left of the dataset. We specified the value of the cell using the Cells property.

  • Run the code (the keyboard shortcut is F5 or Fn + F5), and you’ll get the following filtered dataset.

Excel VBA Filter Based on Cell ValueRead More: Filter Multiple Criteria in Excel with VBA (Both AND and OR Types)


Method 2 – Filter Based on Cell Value Using a Drop-down List 

Steps

  • Select the filter cell, in this case G5.
  • Choose the Data Validation tool from the Data Tools ribbon in the Data tab.

Using a Drop-down List

  • You’ll see the following dialog box where you need to choose the List under the Allow criteria.
  • Insert All Platforms, Web, Mobile in the box for Source. Alternatively, you can create a drop-down list with unique values.

Using a Drop-down List

  • Press OK, and you’ll see the following drop-down list.

Using a Drop-down List

  • Go to the Sheet tab of the active sheet (at the bottom) and right-click on the current sheet’s name.
  • Choose the View Code option.

Using a Drop-down List

  • Copy-paste the following code inside the module that opens:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$G$5" Then
 If Range("G5").Value = "All Platforms" Then
  Range("B5").AutoFilter
 Else
  Range("B5").AutoFilter field:=3, Criteria1:=Range("G5").Value
 End If
End If
End Sub

Excel VBA Filter Based on Cell Value Using a Drop-down List

⧭ In the above code, we used the Worksheet.Change event which processes continuous changes in cell values within the worksheet. Then, we utilized the If…Then…Else statement along with the AutoFilter method to filter the dataset based on either “All Platforms” (with no criteria) or other values of the G5 cell (with criteria).

  • Close the VBA Editor.
  • Go to the main worksheet and choose any platform from the drop-down list.
  • We chose the Web platform to filter the dataset.

Excel VBA Filter Based on Cell Value Using a Drop-down List

  • We got the following filtered data based on the Web platform.

Excel VBA Filter Based on Cell Value Using a Drop-down List

Read More: Excel VBA: How to Filter with Multiple Criteria in Array


Method 3 – Filter with Multiple Criteria Using the OR Operator

Suppose that you have two categories of the sites in the G5:H5 cell. Category1 is Entertainment which is not available along with the whole dataset and Category2 is about Sport. We’ll return results that satisfy either one of the criteria.

Multiple Criteria Using Or Operator

  • Open the VBA editor (right-click on the sheet name and select View Code).
  • Copy the following code:
Sub Using_OR_Logic()
Dim range_to_filter As Range

Set range_to_filter = Range("B4:E15")

range_to_filter.AutoFilter field:=2, Criteria1:=Cells(5, 7).Value, Operator:=xlOr, Criteria2:=Cells(5, 8).Value

End Sub

Excel VBA Filter Based on Cell Value Multiple Criteria Using Or Operator

  • Run the code by saving and closing the tab.

Things to Keep in Mind While Using the Above Code:

  • Range: It refers to the cell range to filter e.g. B4:E15.
  • Field: It is the index of the column number from the leftmost part of your dataset. The value of the second field will be 2.
  • Criteria 1: The first criteria for a field e.g. Criteria1=Cells(5, 7).Value
  • Criteria 2: The second criterion for a field e.g. Criteria2=Cells(5, 8).Value
  • Operator: An Excel operator that specifies certain filtering requirements. Here, the Or operator is used which returns TRUE if any input is TRUE.

After running the code, you’ll get the filtered output based on Sport only as Category1 is not available in the dataset.

Excel VBA Filter Based on Cell Value Multiple Criteria Using Or Operator

Read More: How to Remove Filter in Excel VBA


Method 4 – Multiple Criteria Using the AND Operator

If you want to filter the dataset based on specific Platforms as well as a range of the Number of Visits (let’s between 5,000 and 15,000), we need to apply the AND to make sure the cells satisfy both criteria.

Using And Operator

  • Open the VBA module and copy the following code:
Dim range_to_filter As Range

Set range_to_filter = Range("B4:E15")

range_to_filter.AutoFilter field:=3, Criteria1:=Cells(5, 7).Value, Operator:=xlAnd
range_to_filter.AutoFilter field:=4, Criteria1:=">=5000", Criteria2:="<=15000"

End Sub

Excel VBA Filter Based on Cell Value Multiple Criteria Using And Operator

Things to Keep in Mind While Using the Above Code:

  • Field: the value of the field for the Platforms is 3 and the Number of Visits is 5.
  • Criteria 1 of Platforms: The first criteria for a field e.g. Criteria1=Cells(5, 7).Value
  • Criteria1 and 2 of the Number of Visits: The first criteria for the field e.g. Criteria1=”>=5000”  and the second criteria is Criteria2=“<=15000” 
  • Operator: here, I used the And operator which returns TRUE if all statements are TRUE. Otherwise, it will return FALSE.

If you run the code, you’ll get the following output.

Excel VBA Filter Based on Cell Value Multiple Criteria Using And Operator

Read More: Excel VBA to Filter in Same Column by Multiple Criteria


Related Articles

Get FREE Advanced Excel Exercises with Solutions!
Md. Abdul Kader
Md. Abdul Kader

MD. ABDUL KADER is an engineer with a talent for Excel and a passion for VBA programming. To him, programming is like a time-saving wizard, making data manipulation, file handling, and internet interactions a breeze. His skill set extends to SWM, GIS, RS, and SPSS. He holds a B.Sc in Urban & Regional Planning from Chittagong University of Engineering and Technology and has shifted to become a content developer. In this role, he crafts technical content centred around... Read Full Bio

4 Comments
  1. I would like to be able to run VBA code with a keyboard shortcut that mimics right click filter on selected cells value.

  2. Hello, I have multiple pivot tables in a single sheet.
    So, I’d like the user to be able to select which pivot table will apply the filter, from a dropdown menu in a cell.

    Is that possible? thanks
    regards
    Mark

    • Reply Mahfuza Anika Era
      Mahfuza Anika Era Aug 21, 2023 at 2:03 PM

      Dear MARK,
      Thank you for your query.
      Here is the dataset I will use to show the solution to your problem.

      dataset

      After creating a PivotTable, I have copied the PivotTable 5 times. So, there are 5 PivotTables in my worksheet now.

      PivotTable

      Now, we have to create a drop-down menu from the list of PivotTables.

      data validation

      Next, copy this VBA code into your VBA code editor. You have to change three things in this code. These are: the cell address of where you placed the drop-down menu, the filter values, and the field name that you want to filter.

      Sub Apply_Filter_PivotTable()
          Dim pivotTableName As String
          Dim pivotTable As pivotTable
          Dim field As PivotField
          Dim filterValue As String
          
          ' Change the cell address to where you placed the dropdown menu
          pivotTableName = Range("A2").Value
          filterValue = "Cash" ' Change this to the desired filter value
          
          On Error Resume Next
          Set pivotTable = ActiveSheet.PivotTables(pivotTableName)
          On Error GoTo 0
          
          If Not pivotTable Is Nothing Then
              ' Change "Field Name" to the name of the field you want to filter
              Set field = pivotTable.PivotFields("Payment Method")
              
              field.ClearAllFilters
              field.CurrentPage = filterValue
          Else
              MsgBox "Pivot table not found."
          End If
      End Sub
      
      Private Sub Worksheet_Change(ByVal Target As Range)
          If Target.Address = "$A$2" Then ' Change to the address of your dropdown cell
              ApplyPivotTableFilter
          End If

      VBA code

      To get the output, select the PivotTable from the drop-down which you want to filter, and then Run the code by pressing the F5 key.
      For your convenience, I have given the Excel file: Filtering PivotTable with drop-down menu.xlsm

      Regards
      Mahfuza Anika Era
      ExcelDemy

Leave a reply

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo