我正在尝试根据这些行的值的排序对数据透视表中的项目进行分组。我正在尝试根据这些数据设置一个帕累托图。我在SO和谷歌上看了很多问题,但是找不到多少帮助......不幸的是,看起来这不是一个普遍的问题。
示例:
Original Pivot
State | Count
AK | 14
AL | 76
AR | 40
AZ | 129
CA | 2666
CO | 244
CT | 61
Sorted Pivot
State | Count
CA | 2666
CO | 244
AZ | 129
AL | 76
CT | 61
AR | 40
AK | 14
Grouped / Final Pivot
State | Count
CA | 2666
CO | 244
AZ | 129
OTHER | 191
我以前从未在VBA中进行过数据排序/分组(但手动执行此操作相当简单),所以我开始录制宏。我想出了如何首先应用排序,但尝试分组给了我这样的东西:
ActiveSheet.PivotTables("PT7").PivotSelect _
"State[AL,CT,AR,AK] Original 'NON-AA'", _
xlDataAndLabel + xlFirstRow, True
问题在于状态是根据枢轴中的值进行硬编码的。如果我想在另一组数据上运行此分组,其中一个不同的状态低于阈值(前3行,而不是count
的实际值),那么将包含错误的状态。
有没有办法只读取顶部/底部的 x 行数,而无需知道哪些行标签对应?
我想要像这样工作(使用行号代替字幕/标签):
ActiveSheet.PivotTables("PT7").PivotSelect _
"State[4, 5, 6, 7] Original 'NON-AA'", _
xlDataAndLabel + xlFirstRow, True
答案 0 :(得分:1)
我相信这样做:
Sub GroupLowerPivotItems()
Dim pt As Excel.PivotTable
Dim ptField As Excel.PivotField
Dim ptItem As Excel.PivotItem
Dim GroupStart As Long
Dim FirstCell As Excel.Range
Dim LastCell As Excel.Range
GroupStart = 4
Set pt = ActiveSheet.PivotTables(1)
Set ptField = pt.PivotFields("State")
Set ptItem = ptField.PivotItems(GroupStart)
Set FirstCell = ptItem.LabelRange
Set ptItem = ptField.PivotItems(ptField.PivotItems.Count)
Set LastCell = ptItem.LabelRange
pt.Parent.Range(FirstCell, LastCell).Group
End Sub
答案 1 :(得分:0)
我相信我已经解决了这个问题 - 需要重构。
Dim iFilterLoop As Integer
Dim vValue2List As Variant
Dim sValue2List As String
vValue2List = ActiveSheet.PivotTables("PT7").RowRange.Value2
sValue2List = ""
'Here's the key step in reading the string values:
For iFilterLoop = 4 To ActiveSheet.PivotTables("PT7").RowRange.Count ' Get all but the top 3 -- skip the first (start at 4), since that's the title
sValue2List = sValue2List & vValue2List(iFilterLoop, 1) & ","
Next iFilterLoop
sValue2List = Left(sValue2List, Len(sValue2List) - 1)
ActiveSheet.PivotTables("PT7").PivotSelect( _
"State[" & sValue2List & "] Original 'NON-AA'", _
xlDataAndLabel + xlFirstRow, True).Group