Excel VBA multiple criteria in Label Filter of Pivot Table

This Excel VBA tutorial explains how to apply multiple criteria in Label Filter of Pivot Table.

Problem with multiple criteria in Label Filter of Pivot Table

There are three kinds of Filters in Pivot Table for each Pivot Filters – Label Filter, Value Filter, Manual Filter. In this tutorial, I will focus on Label Filter, because I use “Department” as an example, which is non-numerical.

Suppose you have the below Pivot Table and you want to show Department Name contains “Fin” and “Aud”.

pivotFilters_01

Click on Department arrow and you can select criteria using Filters. You can see a list of options here for you to make criteria on Department. Now click “Contains…”

pivotFilters_02

You will immediately notice that you can only add one condition (so do other condition options), but we really need to use multiple conditions such as AND, OR

pivotFilters_03

Now go back to the previous option page, you can simply uncheck the HR and IT box. Although you can do the job reluctantly, the action is manual.

pivotFilters_04

Syntax of PivotFilters

Before continue reading, you should have knowledge in creating Pivot Table and change Pivot Table layout. If not, please read the below articles.

Create Pivot Table using Excel VBA

Change Pivot Table Layout using VBA

To add criteria in Pivot Table, we have to use Add Property of PivotFilters.

Below is the syntax of PivotFilters.Add Property

PivotFilters.Add(Type, DataField, value1, Value2, Order, Name, Description, IsMemberPropertyFilter, MemberPropertyField)
NameRequired/OptionalData TypeDescription
TypeRequiredXlPivotFilterTypeRequires an XlPivotFilterType type of filter.
DataFieldOptionalVariantThe field to which the filter is attached.
Value1OptionalVariantFilter value 1.
Value2OptionalVariantFilter value 2.
OrderOptionalVariantOrder in which the data should be filtered.
NameOptionalVariantName of the filter.
DescriptionOptionalVariantA brief description of the filter.
MemberPropertyFieldOptionalVariantSpecifies the member property field on which the label filter is based.

 

The first argument Type determines how you want to compare the data in the filter. Some “Type” such as xlValueIsBetween requires two value (Value1, Valu2), but “Value2” does not mean you can add two criteria using one Filter.

Below are the values of Type

NameValueDescription
xlBefore31Filters for all dates before a specified date
xlBeforeOrEqualTo32Filters for all dates on or before a specified date
xlAfter33Filters for all dates after a specified date
xlAfterOrEqualTo34Filters for all dates on or after a specified date
xlAllDatesInPeriodJanuary53Filters for all dates in January
xlAllDatesInPeriodFebruary54Filters for all dates in February
xlAllDatesInPeriodMarch55Filters for all dates in March
xlAllDatesInPeriodApril56Filters for all dates in April
xlAllDatesInPeriodMay57Filters for all dates in May
xlAllDatesInPeriodJune58Filters for all dates in June
xlAllDatesInPeriodJuly59Filters for all dates in July
xlAllDatesInPeriodAugust60Filters for all dates in August
xlAllDatesInPeriodSeptember61Filters for all dates in September
xlAllDatesInPeriodOctober62Filters for all dates in October
xlAllDatesInPeriodNovember63Filters for all dates in November
xlAllDatesInPeriodDecember64Filters for all dates in December
xlAllDatesInPeriodQuarter149Filters for all dates in Quarter1
xlAllDatesInPeriodQuarter250Filters for all dates in Quarter2
xlAllDatesInPeriodQuarter351Filters for all dates in Quarter3
xlAllDatesInPeriodQuarter452Filters for all dates in Quarter 4
xlBottomCount2Filters for the specified number of values from the bottom of a list
xlBottomPercent4Filters for the specified percentage of values from the bottom of a list
xlBottomSum6Sum of the values from the bottom of the list
xlCaptionBeginsWith17Filters for all captions beginning with the specified string
xlCaptionContains21Filters for all captions that contain the specified string
xlCaptionDoesNotBeginWith18Filters for all captions that do not begin with the specified string
xlCaptionDoesNotContain22Filters for all captions that do not contain the specified string
xlCaptionDoesNotEndWith20Filters for all captions that do not end with the specified string
xlCaptionDoesNotEqual16Filters for all captions that do not match the specified string
xlCaptionEndsWith19Filters for all captions that end with the specified string
xlCaptionEquals15Filters for all captions that match the specified string
xlCaptionIsBetween27Filters for all captions that are between a specified range of values
xlCaptionIsGreaterThan23Filters for all captions that are greater than the specified value
xlCaptionIsGreaterThanOrEqualTo24Filters for all captions that are greater than or match the specified value
xlCaptionIsLessThan25Filters for all captions that are less than the specified value
xlCaptionIsLessThanOrEqualTo26Filters for all captions that are less than or match the specified value
xlCaptionIsNotBetween28Filters for all captions that are not between a specified range of values
xlDateBetween32Filters for all dates that are between a specified range of dates
xlDateLastMonth41Filters for all dates that apply to the previous month
xlDateLastQuarter44Filters for all dates that apply to the previous quarter
xlDateLastWeek38Filters for all dates that apply to the previous week
xlDateLastYear47Filters for all dates that apply to the previous year
xlDateNextMonth39Filters for all dates that apply to the next month
xlDateNextQuarter42Filters for all dates that apply to the next quarter
xlDateNextWeek36Filters for all dates that apply to the next week
xlDateNextYear45Filters for all dates that apply to the next year
xlDateThisMonth40Filters for all dates that apply to the current month
xlDateThisQuarter43Filters for all dates that apply to the current quarter
xlDateThisWeek37Filters for all dates that apply to the current week
xlDateThisYear46Filters for all dates that apply to the current year
xlDateToday34Filters for all dates that apply to the current date
xlDateTomorrow33Filters for all dates that apply to the next day
xlDateYesterday35Filters for all dates that apply to the previous day
xlNotSpecificDate30Filters for all dates that do not match a specified date
xlSpecificDate29Filters for all dates that match a specified date
xlTopCount1Filters for the specified number of values from the top of a list
xlTopPercent3Filters for the specified percentage of values from a list
xlTopSum5Sum of the values from the top of the list
xlValueDoesNotEqual8Filters for all values that do not match the specified value
xlValueEquals7Filters for all values that match the specified value
xlValueIsBetween13Filters for all values that are between a specified range of values
xlValueIsGreaterThan9Filters for all values that are greater than the specified value
xlValueIsGreaterThanOrEqualTo10Filters for all values that are greater than or match the specified value
xlValueIsLessThan11Filters for all values that are less than the specified value
xlValueIsLessThanOrEqualTo12Filters for all values that are less than or match the specified value
xlValueIsNotBetween14Filters for all values that are not between a specified range of values
xlYearToDate48Filters for all values that are within one year of a specified date

 

Apply single criteria in PivotFilters

To filter department that contains string “Fin”

ActiveSheet.PivotTables("PivotTable3").PivotFields("Department").PivotFilters.Add Type:=xlCaptionContains, Value1:="Fin"

The above example has the same effect as typing “Fin” in Label Filter

pivotFilters_03

Cancel criteria in Label Filter

Method for PivotFieldsExplanation
ClearValueFiltersClear only Value Filter
ClearLabelFiltersClear only Label Filter
ClearManualFiltersClear only Manual Filter (items your manually select or uncheck)
ClearAllFiltersClear all Value, Label and Manual Filters

The below example cancels all Filters for pivot field “Department”.

ActiveSheet.PivotTables("PivotTable3").PivotFields("Department").ClearAllFilters

In order to cancel all Filters of all PivotFields, loop through all PivotFields in PivotTable

Public Sub cancelAll()
    For Each ptf In ActiveSheet.PivotTables("PivotTable1").PivotFields
        ptf.ClearAllFilters
    Next
End Sub

Apply multiple criteria in PivotFilters

Same old problem as in user interface of Label Filter, we cannot add multiple criteria under one Filter even in VBA.

To work around, we need to simulate the effect of “checking” and “unchecking” the box but also adding the function to do the “Contain” filter.

pivotFilters_04

The department name (Audit, Finance…) under a “Department” (a PivotFields) is referred to as “PivotItems”. Each PivotFields has its own array of PivotItems.

We can loop through each PivotItems (Audit, Finance…) in PivotFields “Department” to check the name of each department.

Sub Macro1()
    With ActiveSheet.PivotTables("PivotTable3").PivotFields("Department")
        For i = 1 To .PivotItems.Count
            If InStr(1, .PivotItems(i), "Fin")<>0 Or InStr(1, .PivotItems(i), "Aud")<>0 Then
                .PivotItems(i).Visible = True
            Else
                .PivotItems(i).Visible = False
            End If
        Next i
    End With
End Sub

What I did in the above code is to loop through each PivotItems (Audit, Finance…) under “Department”, and check the name to see if it contains “Fin” or “Aud” using INSTR function (return 0 if substring not found, return the position of first occurrence if found) . If found, show them, otherwise hide them.

Here is how you can simulate the rest of the criteria in Label Filter.

EqualPivotItems(i) = “xxx”
Does Not EqualPivotItems(i) <> “xxx”
Begins Withleft(PivotItems(i),len(“xxx”)) = “xxx”
Does Not Begin Withleft(PivotItems(i),len(“xxx”)) <> “xxx”
Ends Withright(PivotItems(i),len(“xxx”)) = “xxx”
Does Not End Withright(PivotItems(i),len(“xxx”)) <> “xxx”
ContainsInstr(1,PivotItems(i),”xxx”) <> 0
Does Not ContainInstr(1,PivotItems(i),”xxx”) = 0

Select specific number of PivotItems

Instead of using text to filter, we can specify the how many PivotItems we want to return. In the below example, I want to select only the 2nd to 5th PivotItems in alphabetic order.

Sub Macro1()
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Department")
        For i = 1 To .PivotItems.Count
            If i >= 2 And i <= 5 Then
                .PivotItems(i).Visible = True
            Else
                .PivotItems(i).Visible = False
            End If
        Next i
    End With
End Sub

In the below example, I want to exclude the 1st to 5th department.

Sub Macro1()
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Department")
        For i = 1 To .PivotItems.Count
            If i >5 Then
                .PivotItems(i).Visible = True
            Else
                .PivotItems(i).Visible = False
            End If
        Next i
    End With
End Sub

In the below example, I want to exclude the 1st to 5th department.

Sub Macro1()
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Department")
        For i = 1 To .PivotItems.Count
            If i >5 Then
                .PivotItems(i).Visible = True
            Else
                .PivotItems(i).Visible = False
            End If
        Next i
    End With
End Sub

In the below example, I want to include the 1st to 5th department plus Finance department

Sub Macro1()
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Department")
        For i = 1 To .PivotItems.Count
            If i <=5 OR InStr(1, .PivotItems(i), "Fin")>0 Then
                .PivotItems(i).Visible = True
            Else
                .PivotItems(i).Visible = False
            End If
        Next i
    End With
End Sub

Outbound References

https://msdn.microsoft.com/zh-tw/library/office/ff193582%28v=office.14%29.aspx

 

Comments are closed.