VBA Filter error

后端 未结 1 1687
闹比i
闹比i 2021-01-16 21:31

I have a filter field called week_of_year (1,2,3,4,5,6,7,8....), another pivot field year(2012,2013,2014), the vba code belows filter on the current week and year of 2014/20

相关标签:
1条回答
  • 2021-01-16 22:12

    If you only want to filter on one value, drag the field of interest to the Report Filter pane, then you can do this very quickly without looping using the following code:

    Sub FilterOnWeek()
    Dim pt As PivotTable
    Dim pf As PivotField
    
    
    Set pt = Worksheets("LO").PivotTables("PivotTable3")
    Set pf = pt.PivotFields("week_of_year")
    
    pf.CurrentPage = Format(Date, "ww")
    End Sub
    

    If for some reason this field absolutely must stay in the PivotTable as a row field, you can still filter without looping by the following method if you have Excel 2010 or later

    1. Make a copy of the PivotTable, and drag the 'week_of_year' field in the copy to the Report Filter area
    2. Set up a slicer on the week_of_year field on one PivotTable, and connect it to the other PivotTable via the Report Connections dialog. (Right click on the Slicer, select 'Report Connections')
    3. Amend the above code so it runs on the 2nd PivotTable.

    The Slicer will then sync the two PivotTables.

    If you want to filter on more than one value, drag the field to the ROWS area, and use this:

    Sub FilterOnWeek2()
    Dim pt As PivotTable
    Dim pf As PivotField
    Dim pi As PivotItem
    Dim lStart As Long
    Dim lEnd As Long
    
    
    lEnd = Format(Date, "ww")
    lStart = Val(Format(Date, "ww")) - 1
    
    Set pt = Worksheets("LO").PivotTables("PivotTable3")
    Set pf = pt.PivotFields("week_of_year")
    
    With pf
        .ClearAllFilters
        .PivotFilters.Add Type:=xlCaptionIsBetween, Value1:=lStart, Value2:=lEnd
    End With
    
    End Sub
    

    If for some reason you don't want this field in the PivotTable as a row field, follow the same general approach as above: make a copy of the PivotTable, put the field that you want to filter on in the copy as a ROWS field, connect the fields of interest together as a slicer, hide the slicer somewhere, and amend the code so it runs on the copy of the PivotTable with the rowfield in it.

    I recommend you read my article at http://dailydoseofexcel.com/archives/2013/11/14/filtering-pivots-based-on-external-ranges/ if you want to learn more about efficiently filtering PivotTables.

    0 讨论(0)
提交回复
热议问题