VBA: Filter multiple items of a Dynamic Table containing certain text

Asked

Viewed 4,697 times

0

I am trying to run a code that shows all the items of a Dynamic Table that contain a certain text. I imagined that only using asterisks (*) before and after my keyword I could get results, but the VBA reads the asterisks as literal characters. How do I filter ALL items that have the word written in Inputbox?

Sub FilterCustomers()

    Dim f As String: f = InputBox("Type the text you want to filter:")

    With Sheets("Customers").PivotTables("Customers_PivotTable")
        .ClearAllFilters
        .PivotFields("Concatenation for filtering").CurrentPage = "*f*"
        End With

End Sub

2 answers

0


To filter multiple items in a Dynamic Table, you must read them item by item and mark them as visible or not. And to compare texts contained in others, one should use the statement Like. Thus, the most appropriate way to write the code for the desired purpose is:

Sub FilterCstomers()

    Dim f As String: f = InputBox("Type the text you want to filter:")

    Dim PvtItm As PivotItem
    With Sheets("Customers Pivot").PivotTables("Customers_PivotTable")
        .ClearAllFilters
        For Each PvtItm In .PivotFields("Concatenation for filtering").PivotItems
            If PvtItm.Name Like "*" & f & "*" Then
                PvtItm.Visible = True
            Else
                PvtItm.Visible = False
                End If
            Next PvtItm
        End With

End Sub

-2

Thanks @Julio_l_muller, helped a lot!

I could even filter 2 different words simultaneously (examples 1 and 2), below:

Sub FilterCstomers()

    Dim f As String: f = InputBox("Type the text you want to filter:")

    Dim PvtItm As PivotItem
    With Sheets("Customers Pivot").PivotTables("Customers_PivotTable")
        .ClearAllFilters
        For Each PvtItm In .PivotFields("Concatenation for filtering").PivotItems
            If PvtItm.Name Like "exemplo1" Then
                PvtItm.Visible = True
            Else
                If PvtItm.Name Like "exemplo2" then
                else
                PvtItm.Visible = False
                End If
            End If
        Next PvtItm
    End With

End Sub

Browser other questions tagged

You are not signed in. Login or sign up in order to post.