Мой код для создания сводной таблицы фактически ничего не делает. Он просто создает новый лист, но не сводную таблицу.
В моей рабочей тетради будет 2 листа: один с данными и один с сводной таблицей.
Это мой код:
Sub InsertPivotTable()
'Macro By ExcelChamps
'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
Worksheets("PivotTable").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("DATA")
'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:="Pivot_table")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="Pivot_table")
With ActiveSheet.PivotTables("Pivot_table").PivotFields("data1")
.Orientation = xlPageField
.Position = 1
End With
ActiveSheet.PivotTables("Pivot_table").AddDataField ActiveSheet.PivotTables( _
"Pivot_table").PivotFields("data2"), "Count of data2", xlCount
'Format Pivot Table
ActiveSheet.PivotTables("Pivot_table").ShowTableStyleRowStripes = True
ActiveSheet.PivotTables("Pivot_table").TableStyle2 = "PivotStyleMedium9"
End Sub