使用 VBA 从数据透视字段获取可见项列表
Get the List of Visible Items from a Pivot Field using VBA
我正在使用以下代码循环遍历数据透视表字段以获取可见的数据透视表项。但是,当数据透视字段位于 行标签 中时,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
明确地迭代 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
我正在使用以下代码循环遍历数据透视表字段以获取可见的数据透视表项。但是,当数据透视字段位于 行标签 中时,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
明确地迭代 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