VBA数据透视表,行数据字段不显示在同一列中

时间:2018-04-16 12:09:22

标签: excel vba excel-vba pivot-table

下午好,

我的VBA宏存在问题,创建了一个我希望有人可以协助的数据透视表,我已经搜索但无法找到任何内容。

我选择了3个数据行,但是当我运行宏时,它将它们全部放在不同的列中,而不是放在同一列中。

所以只是为了更好地解释它,所选择的3行标题是'产品条码'产品编号' '产品说明',而不是将它们全部放在A列下面,它将每个标题放在一个单独的列中,因此产品条形码'在A列中,'产品编号'在B栏中,'产品说明'在C栏中。

对此的任何帮助将不胜感激。

提前致谢。

Sub TestingCategoryPivot3()

'Declare Variables
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As range
Dim LastRow As Long
Dim LastCol As Long

'Insert a New Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Sheets.Add Before:=Worksheets("Data")
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
On Error GoTo 0
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("Data")

'Define Data Range - i don't use this as i get a type mismatch error when i do
'LastRow = DSheet.Cells(DSheet.Rows.Count, 1).End(xlUp).Row
'LastCol = DSheet.Cells(1, DSheet.Columns.Count).End(xlToLeft).Column

'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Add _
(SourceType:=xlDatabase, SourceData:="Data!R1C1:R20000C23")

'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(28, 1), TableName:="PivotTable7")

'Insert Row Fields
With PTable.PivotFields("Product Barcode")
.Orientation = xlRowField
.Position = 1
End With

With PTable.PivotFields("Product Number")
.Orientation = xlRowField
.Position = 2
End With

With PTable.PivotFields("Product Description")
.Orientation = xlRowField
.Position = 3
End With

'Insert Column Fields
With PTable.PivotFields("Category")
.Orientation = xlColumnField
.Position = 1
End With

'Insert Data Field
With PTable.PivotFields("Category")
.Orientation = xlDataField
.Position = 1
.Function = xlCount
.NumberFormat = "#,##0"
End With

With PTable.PivotFields("Category")
.PivotItems("#VALUE!").Visible = False
.PivotItems("(blank)").Visible = False
End With

'Insert Pivot Filter
With PTable.PivotFields("Zone")
    .Orientation = xlPageField
    .Position = 1
End With

With PTable.PivotFields("Product type")
    .Orientation = xlPageField
    .Position = 2
End With

With PTable.PivotFields("Period")
    .Orientation = xlPageField
    .Position = 3
End With

'Format Pivot Table
PTable.ShowTableStyleRowStripes = True
PTable.TableStyle2 = "PivotStyleMedium9"

End Sub

1 个答案:

答案 0 :(得分:0)

听起来您正在描述报告布局功能。如果您从数据透视表工具>设计选项卡中选择报表布局并选择以紧凑形式显示,您会得到您想要的内容吗?