我试图将两个数据透视表放到同一张纸上,但是当我进入VBA时没有创建第二个数据透视表。该代码运行时没有任何错误,但从未创建第二个数据透视表。我希望最终将许多数据透视表添加到同一张纸上,以便对此提供任何帮助。
我尝试设置两个不同的缓存,但是我认为这不会帮助解决此特定问题。我也尝试过
Sub CreatePivottablewithVBA()
'Declare Variables
Dim Psheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim Ptable As PivotTable
Dim Ptable2 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
Worksheets("PivotTable").Delete
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
Set Psheet = Worksheets("PivotTable")
Set DSheet = Worksheets("Raw")
'Define Data Range
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)
'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=Psheet.Cells(2, 2), _
TableName:="SalesbyYearMonth")
'Insert Blank Pivot Table
Set Ptable = PCache.CreatePivotTable _
(TableDestination:=Psheet.Cells(1, 1), TableName:="SalesbyYearMonth")
'Insert Row Fields
With ActiveSheet.PivotTables("SalesbyYearMonth").PivotFields("ck_complete_dt")
.Orientation = xlRowField
.Position = 2
End With
'Insert Data Field
With ActiveSheet.PivotTables("SalesbyYearMonth").PivotFields("total_amount")
.Orientation = xlDataField
.Position = 1
.Function = xlCount
.Name = "# of Sales"
End With
With ActiveSheet.PivotTables("SalesbyYearMonth").PivotFields("total_amount")
.Orientation = xlDataField
.Position = 2
.NumberFormat = "$#,##0.00"
.Function = xlSum
.Name = "Total Amount"
End With
With ActiveSheet.PivotTables("SalesbyYearMonth").PivotFields("total_amount")
.Orientation = xlDataField
.Position = 3
.Calculation = xlPercentOfTotal
.NumberFormat = "0.00%"
.Name = "% of Total"
End With
'Format Pivot Table
ActiveSheet.PivotTables("SalesbyYearMonth").ShowTableStyleRowStripes = True
ActiveSheet.PivotTables("SalesbyYearMonth").TableStyle2 = "PivotStyleMedium9"
PivotTable.DataOnRows = False
'Create PivotTable2
Set Ptable2 = PCache.CreatePivotTable(TableDestination:=Psheet.Cells(22, 2), TableName:="SalesPerCategory")
With ActiveSheet.PivotTables("SalesPerCategory").PivotFields("highest_categ_level")
.Orientation = xlRowField
.Position = 1
.Name = "Category"
End With
With ActiveSheet.PivotTables("SalesPerCategory").PivotFields("highest_categ_level")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
.Name = "Count of Categories"
End With
End Sub
我没有收到任何错误消息,但是我希望看到在数据透视表中创建的两个数据透视表