简体   繁体   中英

Loop to filter Pivot Table based on values in another Sheet

My objective is to filter a pivot table using a range in another sheet.

My pivot is in Worksheets("Aging Report").

My reference data using which I want to filter is in Columns A2 and onward in Worksheets("Instructions").

The below code worked on a table which did not have pivot table.

I need to take value from A2 then filter on ("Client ID") and export in Excel and save and so on with values in A3, A4, A5.

Sub Pivotfilter()

Dim varItemsToReplace As Variant
Dim varItem As Variant
Dim wksSource As Worksheet
Dim wksDest As Worksheet
Dim rngSource As Range
Dim rngSource2 As Range
Dim rngCell As Range

Set wksSource = Worksheets("Instructions")
Set wksDest = Worksheets("Aging Report")

With wksSource
    Set rngSource = .Range("A2:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
End With

For Each rngCell In rngSource
    With wksDest
        ActiveSheet.PivotTables("PivotTable40").PivotFields ("Client ID")
        .PivotFields(rngCell.Value).Visible = True
        Dim wb As Workbook
        Set wb = Workbooks.Add
        Windows("XXXXXXX").Activate
        Sheets("Aging Report").Select
        Sheets("Aging Report").Copy Before:=wb.Sheets(1)
        wb.SaveAs "C:\Users\XXX\Desktop\SOA\" & .Range("B3").Value & " - " & .Range("B4").Value & ".xlsx"
        wb.Close
        Windows("XXXXXXX.xlsm").Activate
    End With
Next rngCell

End Sub

Some Useful guidelines:

Raw Data:

在此处输入图片说明

Select the data and create a pivot table named "pvtTest" in Shhet 5

Try:

Option Explicit

Sub test()

    Dim pvt As PivotTable
    Dim Pf As PivotField
    Dim strFilter As String

    'Assign to variable "pvt" the pivot table to work with it
    Set pvt = Worksheets("Sheet5").PivotTables("pvtTest")

    'Assigh to "strFilter" the string to filter
    strFilter = "A"

    'Use column "Shop" as a filter of pivot table
    pvt.PivotFields("Shop").Orientation = xlPageField

    'Assign by which column the pivot table will be filtered
    Set Pf = Worksheets("Sheet5").PivotTables("pvtTest").PivotFields("Shop")

    'Clear filter previous choices
    Pf.ClearAllFilters

    'Select to filter the pivot table based on the value of "strFilter"
    Pf.CurrentPage = strFilter

End Sub

For filtering by value, my preferred method is to add more columns to the data itself, set the values by formulae, and add those columns to the pivot

Eg column Scope boolean added to pivot filter, filter on only true

Adding 30/60/90 aging column, add this to a pivot row to group by age

Etc

This lets you avoid needles complexity of combining two lesser known areas of expertise vba in general and vba specifically for pivots

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM