【问题标题】:Get the List of Visible Items from a Pivot Field using VBA使用 VBA 从数据透视字段中获取可见项列表
【发布时间】:2016-12-07 00:34:12
【问题描述】:

我正在使用下面的代码循环遍历一个数据透视字段以获取可见的数据透视项目。但是pivotitem.count 在枢轴字段位于 行标签 时给出 0 当我将此枢轴字段移动到列标签时,代码工作正常。但我需要这个字段留在行标签上。

有什么办法可以解决我的问题吗?

Dim pt As PivotTable
Dim pf As PivotField
Dim pvtitem As PivotItem

Set nwSheet = Worksheets.Add
nwSheet.Activate
rw = 0

Set pt = Sheets("Reasons").PivotTables("PivotFields")
Set pf = pt.PivotFields("[Characteristics].[Reason].[Reason]")

With pf
    For i = 0 To .PivotItems.Count
        rw = rw + 1
        nwSheet.Cells(rw, 1).Value = .PivotItems.Count
    Next i
End With

【问题讨论】:

    标签: vba excel pivot-table pivotitem


    【解决方案1】:

    显式地对 RowFields 进行迭代可以获得对 Row Fields 中可见 Pivot Items 的句柄。 请看看这是否达到目的:

        Set pt = Sheets("Reasons").PivotTables("PivotFields")
        Dim pf As PivotField
        For Each pf In pt.RowFields
              MsgBox pf.Name & " : " & pf.VisibleItems.Count
        Next
    

    要迭代报告过滤器:

    Dim pt As PivotTable
    Dim pFilter As PivotFilter
    Dim pFilters As PivotFilters
    Dim pF As PivotField
    
    Set pt = Sheets("Reasons").PivotTables("PivotFields")
    'Set the first RowField as the PivotField
    Set pF = pt.RowFields(1)
    
    'Remove previous filters
    pF.ClearAllFilters
    
    'Assuming we have a RowField as 'Quarter' and DataField as 'Sum of Sale',
    'we can apply a new 'ValueIsLessThan' filter for a Sum of Sale value of 12000
    
    pt.PivotFields("Quarter").PivotFilters.Add Type:=xlValueIsLessThan, _
    DataField:=pt.PivotFields("Sum of Sale"), Value1:=12000
    
    Set pFilters = pt.PivotFields("Quarter").PivotFilters
    
    For Each pFilter In pFilters
      MsgBox "Filter Applied On: " & pFilter.PivotField.Name & " -- Filtered values for less than : " & pFilter.Value1
    Next
    

    【讨论】:

    • 不。那是行不通的。 For 循环只是被跳过。所以我认为它也无法获取数据透视字段
    • 它的工作原理如下: For Each pi In pt.RowFields(1).PivotItems
    • 我也在尝试使用“pt.Filter(1).PivotItems”获取报告过滤器中的字段,但这不起作用。您知道如何在报表过滤器中使用数据透视字段吗?
    • 我不明白您在报告过滤器中要做什么。我不想清除过滤器。我只想计算报告过滤器中每个数据透视字段中的项目数
    • 您是否尝试过类似的操作:将 pI 作为 PivotItem 对于 pFilter.PivotField.PivotItems 中的每个 pI msg = msg & vbCrLf & pI.Name Next MsgBox msg
    猜你喜欢
    • 2011-09-07
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多