vba - 数据透视表位于同一工作表上

标签 vba excel pivot-table

我已经根据数据创建了各种数据透视表,但仅在其他工作表(插入新工作表)中。现在,我在同一个 Excel 工作表中拥有数据,我想创建数据透视表。它一直说我设置 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

最佳答案

请替换这些行:

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

关于vba - 数据透视表位于同一工作表上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46486994/

相关文章:

VBA:在单元格中拆分文本,为单元格中的每个元素创建重复行

excel - TEXT 公式中的日期格式与 Excel 中使用的语言无关

java - 使用 Apache POI 刷新数据透视表

MySQL如何透视数据以显示数据库中属于多个组的用户

VBA - 使用宏操作特定工作表数据 - 不是 Activesheet

vba - 标记字符串

excel - VBA 03 - 应用程序路径 - 到达父文件夹

vba - 在 Excel VBA 中,根据列数据创建新行

excel - VBA excel(宏)

mysql - 如何在mysql中透视一个有n行的表?