使用VBA从数据透视图字段中获取可见项列表

时间:2016-08-01 20:00:20

标签: vba excel-vba pivot-table pivotitem excel

我正在使用以下代码循环遍历枢轴字段以获取可见的透视项目。但是当枢轴字段位于行标签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

1 个答案:

答案 0 :(得分:1)

显式地迭代RowFields可以获得行字段中可见数据透视表项的句柄。 请看看这是否符合目的:

    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