我正在寻找一种在数据透视表的 值 bin中添加多个字段的方法( 列标签下面的那个> EM> )。以下代码将我的字段添加到 列标签 bin中。我已按照指定here尝试了RowFields
和AddToTable
。这是我的数据透视表应该是这样的(除了阵列PF中有更多字段):
但它看起来像这样:
Global PF() As String
Sub AddPF()
Dim LastCol As Integer: LastCol = ActiveSheet.UsedRange.Columns.Count
Dim rngData As Range
Dim rngDest As Range: Set rngDest = Sheets("PIVOT Lifestyles Rollup").Range("A1")
Erase PF
For i = 2 To LastCol
ReDim Preserve PF(0 To i - 2)
PF(i - 2) = Cells(2, i).Value
Next
ActiveSheet.Range("B2").Select
Range(Selection, Selection.End(xlDown)).Select
Set rngData = Range(Selection, Selection.End(xlToRight))
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
rngData, Version:=xlPivotTableVersion14 _
).CreatePivotTable TableDestination:=rngDest, _
TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion14
rngDest.Parent.Activate
ActiveSheet.PivotTables(1).AddFields ColumnFields:=PF
End Sub
答案 0 :(得分:0)
删除代码的最后一行,然后单击“记录宏”并手动添加字段。您应该能够轻松清理录制的代码,然后将其添加到您已有的代码中。希望有所帮助
答案 1 :(得分:0)
添加数据字段的示例
With ActiveSheet.PivotTables(1)
With .PivotFields("Name of Pivot Field")
.Orientation = xlDataField
.Position = 1
.Caption = "Pivot Table Column Header"
.Function = xlSum
.NumberFormat = "Your desired number format"
End With
End With
如果要添加更多值字段,只需添加xlDataField并调整位置
即可