与数据在同一工作表上的数据透视表

我已经创build了各种数据透视表,但只有在其他工作表(插入新的)从数据。 现在,我有相同的Excel表中的数据我想创build数据透视表。 它不断粉碎说,它在我设置PCache的行中有问题。 我正在提供下面的代码

Sub a() 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 Set PSheet = ActiveSheet LastRow = PSheet.Cells(Rows.Count, 1).End(xlUp).Row LastCol = PSheet.Cells(1, Columns.Count).End(xlToLeft).Column Set PRange = PSheet.Cells(1, 1).Resize(LastRow, LastCol) ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange).CreatePivotTable TableDestination:=PSheet.Cells(2, 13), TableName:="PivotTable1" With ActiveSheet.PivotTables("PivotTable1").PivotFields("Destination") .Orientation = xlRowField .Position = 1 .Subtotals(1) = True .Subtotals(1) = False End With With ActiveSheet.PivotTables("PivotTable1").PivotFields("Total trucks") .Orientation = xlDataField .Position = 1 .Function = xlSum .Name = "Sum of Quantity (cases/sw)" End With 'PTable.LayoutRowDefault = xlTabularRow 'Range("M2").Value = "Commodity Code" End Sub 

请replace这些行:

 Set PCache = ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=PRange).CreatePivotTable(TableDestination:=PSheet.Cells(2, 13), TableName:="PivotTable") Set PTable = PCache.CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), TableName:="PivotTable") 

附:

 ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange).CreatePivotTable TableDestination:= _ PSheet.Cells(2, 13), TableName:="PivotTable1" 

并将TableName重命名为PivotTable1

阅读下面的代码和代码的评论里面的解释:

 Option Explicit Sub a() 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 Set PSheet = ActiveSheet With PSheet LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column Set PRange = .Cells(1, 1).Resize(LastRow, LastCol) End With ' first: set the Pivot Cache object Set PCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange.Address(False, False, xlA1, xlExternal)) ' Second: set the Pivot Table object Set PTable = PSheet.PivotTables.Add(PivotCache:=PCache, TableDestination:=PSheet.Cells(2, 13), TableName:="PivotTable1") ' after we set the Pivot-Table object, use the object to modify it's properties With PTable With .PivotFields("Destination") .Orientation = xlRowField .Position = 1 .Subtotals(1) = True .Subtotals(1) = False End With With .PivotFields("Total trucks") .Orientation = xlDataField .Position = 1 .Function = xlSum .Name = "Sum of Quantity (cases/sw)" End With End With 'PTable.LayoutRowDefault = xlTabularRow 'Range("M2").Value = "Commodity Code" End Sub