使用数组过滤数据透视表字段

时间:2018-02-27 15:51:43

标签: vba excel-2010

我正在尝试使用针对每个循环的嵌套来将数据透视字段过滤为数组中保存的值。我正在尝试过滤的枢轴字段包含会计期间 - 我想要保持可见的部分保存在单独的工作表上的一系列单元格中 - 日期控制表。我的代码如下:

Sub updateMSFPivotCharts()
Dim PivotYear As String, PvtTable As PivotTable, PivotPeriodsRange As Range, DateLastRow As String, PivotPeriods As Variant, ReportPeriodPF As PivotField, YearPF As PivotField, Pi As PivotItem
Dim LboundReportPeriodPF As String, PivotPeriodItem As Variant

PivotYear = Worksheets("Date Control Sheet").Range("A2").Value
DateLastRow = Worksheets("Date Control Sheet").Range("B2").End(xlDown).Row
Set PivotPeriodsRange = Worksheets("Date Control Sheet").Range("B2:B" & DateLastRow)
PivotPeriods = PivotPeriodsRange.Value


'Update Topline Performance Pivot
Call AdjustPivotDataRange("MSF Topline Performance", "1", "A9", "BI", strLastRow)
Set PvtTable = Worksheets("MSF Topline Performance").PivotTables("PivotTable1")
Set YearPF = Worksheets("MSF Topline Performance").PivotTables("PivotTable1").PivotFields("Year")
Set ReportPeriodPF = Worksheets("MSF Topline Performance").PivotTables("PivotTable1").PivotFields("Report Period")

'Filter Pivot to Date Ranges expressed on Date Control Sheet
With PvtTable
    'Update Pivot Table Field Filtering
    YearPF.ClearAllFilters
    ReportPeriodPF.ClearAllFilters
    YearPF.CurrentPage = PivotYear
End With

With ReportPeriodPF
    For Each PivotPeriodItem In PivotPeriods
        For Each Pi In ReportPeriodPF.PivotItems
            If Pi = PivotPeriodItem Then GoTo Skipstep Else Pi.Visible = False
        Next Pi
Skipstep:
    Pi.Visible = True
    Next PivotPeriodItem
End With

我遇到的问题是,当我将Pi与PivotPeriodItem匹配并退出循环时,Pi会在PivotPeriodItem开始时返回到下一个Item,因此当Pi等于前一个PivotPeriodItem时,它会隐藏它再次,当我希望它显示。

有没有人对如何重写代码以解决这个问题有任何建议?非常感谢提前提供的任何帮助。

安德鲁

1 个答案:

答案 0 :(得分:0)

而不是

With ReportPeriodPF
    For Each PivotPeriodItem In PivotPeriods
        For Each Pi In ReportPeriodPF.PivotItems
            If Pi = PivotPeriodItem Then GoTo Skipstep Else Pi.Visible = False
        Next Pi
Skipstep:
    Pi.Visible = True
    Next PivotPeriodItem
End With

将其替换为

With ReportPeriodPF
    For Each Pi In ReportPeriodPF.PivotItems
        If WorksheetFunction.CountIf(PivotPeriodsRange, Pi) > 0 Then
            Pi.Visible = True
        Else
            Pi.Visible = False
        End If
    Next Pi
End With

一个循环,只需使用CountIf来测试范围,而不是范围内的单个项目。