The VBA code I have below is trying to create a Pivot Table based on data in "Sheet2", adding a new sheet "Pivot Table" and creating a Pivot Table on this sheet.
However the code is executing without error, just no table appears on the new sheet "Pivot Table" and I cannot see why.
Also the data on Sheet2 for the PT currently begins in column B, not sure if this is having an effect.
Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow1 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("Sheet2")
'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:="MilestonePivotTable")
'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="MilestonePivotTable")
'Insert Row Fields
With ActiveSheet.PivotTables("MilestonePivotTable").PivotFields("Resource Name")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("MilestonePivotTable").PivotFields("Deliverable")
.Orientation = xlRowField
.Position = 2
End With
'Insert Column Fields
With ActiveSheet.PivotTables("MilestonePivotTable").PivotFields("Milestone Date")
.Orientation = xlColumnField
.Position = 1
End With
PRange
be set asSet PRange = DSheet.Cells(1, "B").Resize(LastRow, LastCol - 1)
? – YowE3KDSheet.
It will be usingActiveSheet
by default, which can cause problems. – braXPSheet
,DSheet
andActiveSheet
are all in the same workbook, an unqualifiedRows.Count
andColumns.Count
won't cause an issue. (But it is definitely a good idea to qualify them anyway!) – YowE3KDSheet.Cells
? – SDROBOn Error GoTo 0
after yourApplication.DisplayAlerts = True
, so that errors aren't masked after that - it will then crash when the errors occur. – YowE3K