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

时间:2017-09-29 10:34:05

标签: excel vba excel-vba 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

2 个答案:

答案 0 :(得分:2)

请替换这些行:

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

答案 1 :(得分:0)

阅读以下代码并在代码注释中解释:

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