2016-08-01 23 views
1

我正在使用以下代码来循环显示透视项目的透视图字段。但pivotitem.count给出一个0时,枢轴字段在行标签当我将此透视字段移动到列标签,代码工作正常。但我需要这个字段留在行标签上。使用VBA从枢轴字段获取可见项列表

有没有解决我的问题?

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

迭代上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 
+0

都能跟得上。这不起作用。 For循环正在跳过。所以我认为它无法获取数据透视字段 – Pramod

+0

它的工作原理是这样的:For Each pi In pt.RowFields(1).PivotItems – Pramod

+0

我也试图使用“pt.Filter (1).PivotItems“,但这不起作用。你有什么想法如何在报表过滤器中使用Pivot字段? – Pramod