×

Excel VBA AutoFilter

One of the reasons for Excel VBA’s popularity is its capability to filter and analyze data from huge database with the help of a method known as AutoFilter. This method permits a user to filter the particular data according to a set criterion and aids its users to draw out precise reports and research work on data. AutoFilter method can filter data comprising values with text, numbers, Boolean, or date data types. Whenever the user applies the AutoFilters to its Excel sheet worksheet, black drop-down arrows (also called filter switches) pop up at the right of your column headings.

Although, we have a filter option available under the Data ribbon tab. But this option is only useful to deal with a minimal set of data. For bulk, it becomes complex to use this method. Hence, to resolve this problem, VBA AutoFilter was introduced. AutoFiltering technique is faster and more efficient. Before applying AutoFilter in VBA, the user should always keep in mind to turn off any current filters (if present) and remove them completely. The range object can also be used to declare AutoFilter in Excel VBA.

Syntax

AutoFilter (Field, Criteria1, Operator, Criteria2, SubField, VisibleDropDown)

Parameter

Field (optional) - This parameter represents an integer offset of the field on which bases you want to apply the filter. The leftmost field is considered as field one.

Criteria1 (optional) – It specifies the criteria. For e.g., to specify blank cells use “=”, for non-blank cells use “<>” and for no data “><” is used.

Operator (optional) – It Identifies the operator to use to associate two criteria applied by a filter. It can accept the following values:

  • xlAnd – Logical ‘AND’ will be applied criterion 1 and criteria 2.
  • xlBottom10Items- The lowest value displayed in Criteria1.
  • xlBottom10Percent- The lowest-valued percentage displayed in Criteria1.
  • xlFilterCellColor- The cell color
  • xlFilterDynamic – The dynamic filter
  • xlFilterFontColor – The font color
  • xlFilterIcon – filter icon
  • xlFilterValues – filter values
  • xlOr - Logical ‘OR’ will be applied criterion 1 and criteria 2.
  • xlTop10Items - The highest value displayed in Criteria1.
  • xlTop10Percent - The highest-values percentage displayed in Criteria1.

Criteria2 (optional) - It specifies the criteria. For e.g., to specify blank cells use “=”, for non-blank cells use “<>” and for no data “><” is used.

SubField (optional)- This parameter represents the field from a data type on which the user wishes to apply the criteria. If this parameter is not specified, by default, it targets the "Display Value".

VisibleDropDown (optional) – This parameter accepts a Boolean value. If it is set to Boolean True, it displays the drop-down window for filtering the field else for Boolean False it will hide the AutoFilter drop-down arrow. Bu default, it is set to Boolean True.

Example

We will use the use Excel Sheet data and with the help of AutoFilter method will put on a criterion to fetch only those rows where sales filed is greater than 35.

Excel VBA AutoFilter

Code:

Sub AutoFilter_Example()
 With ActiveSheet
     'FilterMode Property determines whether the AutoFilters are filtering data down
     'and FilterMode are in use
     .AutoFilterMode = False
     'specifying the AutoFilter range
     .Range("A2:I21").AutoFilter
     'setting the parameters and applying criteria
     'at filed 5, filtering sales data more than 35 
     .Range("A2:I21").AutoFilter Field:=5, Criteria1:=35
 End With
 End Sub 

Let’s work with the set-by-step code of lines:

Step 1: Open the VBA developer tab either by using the shortcut keywords Alt +F11 or click on developer window -> visual basic editor.

Step 2: Visual Basic Editor will open. Next step is to create a module. Right-clicking on the VBA Project-> Click on Insert-> Click on Module.

Excel VBA AutoFilter

Step 3: In the VBA Module window, within the sub-block, introduce your macro name.

Excel VBA AutoFilter

Step 4: Next, we will use the ‘With’ block we will define a series of ActiveSheet.

Excel VBA AutoFilter

Step 5: Firstly, we will disable the AutoFilterMode to turn off any current filters (if present) and remove them completely. This property determines whether the AutoFilters are filtering data, or the AutoFilter arrows are visible or not. Although this is an optional method. Nut its always advisable to make sure that the previous filters are put off.

Excel VBA AutoFilter

Step 6:  Now, with the help of Range object we will select the data from our Excel active sheet wherein we wish to apply the auto filter method.

Excel VBA AutoFilter

Step 7: We will us the parameters of the AutoFilter method and will define the filed number and criteria to put the filter. Unlike in the below example, we have put field=5 and the sales criteria should be greater than 35.

Excel VBA AutoFilter

Output

Step 8: Execute the above code either by pressing the F5 shortcut key or by clicking on the Run button.

Step 9: You will notice that your sheet has been filtered and only the row whole sales filed is greater than is displayed. Thus, hiding all the other values. You can copy these values and can paste it at another sheet for your future reference.

Excel VBA AutoFilter

Related Topics

Excel VBA: Select … Case Statement

Select … Case Statement When a group of statements is executed, depending upon the value of an Expression, then Switch Case is used.  If you have several conditions to check, then the If condition...

4 minutes read.

Debugging in Excel VBA

Debugging in VBA: Debugging is a technique used to fix errors in programming languages. In Excel VBA, we have different ways by which you can identify the error in the...

2 minutes read.

Excel VBA MonthName Function

Excel VBA MonthName Function: The MonthName function in VBA returns a string with the month name for the specified month number. Syntax MonthName (Month, [Abbreviate]) Parameter Month (required) – This parameter represents an integer between...

1 minute read.

Excel VBA FormatNumber Function

VBA FormatNumber Function: The FormatNumber function in VBA is used to apply a number format to a numeric expression, and it returns the result as a string. Syntax FormatNumber (Expression, [NumDigitsAfterDecimal], [IncludeLeadingDigit], [UseParensForNegativeNumbers], [GroupDigits]) Parameter Expression (required)...

2 minutes read.

Excel VBA Date Function

VBA Date Function The Date function in VBA returns the current date. Syntax Date( ) Parameter NA Return This function returns the current date. Example 1 Sub DateFunction_Example1() ' retuning the current date in the variable currentDate Dim currentDate As...

1 minute read.

Excel VBA Now Function

Excel VBA Now Function: The Now function in VBA returns the current date and time.  Syntax Now () Parameter NA Return This function returns the current date and time.  Example 1 Sub NowFunction_Example1() 'It will return...

1 minute read.

Excel VBA Split Function

Excel VBA Split Function: The Split function in VBA is used to split a string into several substrings and return a one-dimensional array of substrings. Syntax Split (Expression, [Delimiter], [Limit], [Compare]) Parameter Expression (required) – This parameter...

2 minutes read.

Excel VBA FormatPercent Function

VBA FormatPercent Function: The FormatPercent function in VBA is used to apply a percent format to a numeric expression, and it returns the result as a string. Syntax FormatPercent (Expression, [NumDigitsAfterDecimal], [IncludeLeadingDigit], [UseParensForNegativeNumbers], [GroupDigits]) Parameter Expression (required)...

2 minutes read.

Looping in VBA

Looping in VBA There are many situations where a programmer needs to execute a block of the repetitive code number of times. Writing the same statement will make the program tedious and monotonous....

3 minutes read.

Excel VBA Array

Introduction to VBA Array An array is a type of variable that holds more than one piece of data. In VBA, you can refer to a specific variable (element) of an array by using...

5 minutes read.

Excel VBA Hour Function

The hour function in VBA returns the hour element for the specified time. Syntax Hour (Time) Parameter Time (required) – This parameter represents the time. Return This function returns the hour element for the specified time. Example 1 Sub HourFunction_Example1() ...

1 minute read.

Excel VBA: IF…..THEN …ELSE Statement

VBA : IF…..THEN …ELSE Statement: This function enables you to check one condition and, based on that, then run one of the two statement blocks present. If the ‘IF’ condition...

2 minutes read.

Excel VBA Chr Function

VBA Chr Function: The Chr function in VBA returns the character equivalent to a supplied character code between 0 and 255. Syntax Chr (CharCode) Parameter CharCode (required) – This parameter represents the character code for...

1 minute read.

Excel VBA DateSerial Function

The DateSerial function in VBA returns a Date from a supplied year, month, and day number. Syntax DateSerial (Year, Month, Day) Parameter Year (required) – This parameter represents an integer signifying the year. Month (required) – This parameter...

2 minutes read.

Excel VBA CDec Function

VBA CDec Function: The CDec function in VBA converts an expression into a Decimal data type. Syntax CDec (Expression) Parameter Expression (required) – This parameter represents the expression that you want to convert to a...

1 minute read.

VBA UBound

VBA UBound  The UBound or Upper Bound function in VBA is used to specify the length of an array and returns the highest subscript for a dimension for the specified array. It is...

3 minutes read.

VBA Creating, Displaying, Uploading UserForms

UserForm is a customized interface and acts as a VBA container and can add various controls as per the required functionality, each of which has certain usage and related properties. You can...

4 minutes read.

VBA Cell

What is VBA cell? Cells is one of the elements (workbook, worksheet, range) in Excel VBA, which refers to cells of the Excel worksheet.  In VBA, the cell is also a property...

5 minutes read.

Excel VBA CDbl Function

VBA CDbl Function: The CDbl function in VBA converts an expression into a Double data type. Syntax CDbl (Expression) Parameter Expression (required) - This parameter represents the expression that that you want to convert to...

1 minute read.

Excel VBA WeekdayName Function

Excel VBA WeekdayName Function: The WeekdayName function in VBA returns a string containing the weekday name, for the specified integer representation of a weekday. Syntax WeekdayName (Weekday, [Abbreviate], [FirstDayOfWeek]) Parameter Weekday (required) – This parameter represents...

2 minutes read.