I am using an VBA code to generate a Pivot table, my code works well with other sheet, but in this sheet it is always creating an error. I checked the column Name, sheet Name everyting, still I could not figure out where I am making mistake. I even recorded macro to crosscheck, still i am clueless.
Sub AutoPivot7()
Dim ws7 As Worksheet
Dim pc7 As PivotCache
Dim pt7 As PivotTable
Dim ct7 As Integer
Set ws7 = Sheets("Pivot_Reasons")
Set pc7 = ActiveWorkbook.PivotCaches.Create(xlDatabase, "'Reasons for Delay'!R1C1:R1048576C2")
Set pt7 = pc7.CreatePivotTable(ws7.Range("B3"))
pt7.AddDataField pt7.PivotFields("Sum of Reasons for Delay"), "Sum of Reasons for Delay", xlSum
With pt7
With .PivotFields("Reasons for Delay")
.Orientation = xlRowField
.Position = 1
.AutoSort xlDescending, "Sum of Reasons for Delay"
End With
With .PivotFields("Sum of Reasons for Delay")
.Calculation = xlPercentOfTotal
End With
End With
End Sub
The error occurs in the line
pt7.AddDataField pt7.PivotFields("Sum of Reasons for Delay"), "Sum of Reasons for Delay", xlSum
if i remove this and run my code, i am not getting the error. I also have attached the record macro which i reffered
Sub Macro7()
'
' Macro7 Macro
'
'
ActiveCell.Offset(-21, -1).Range("Table3[#All]").Select
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Table3", Version:=xlPivotTableVersion15).CreatePivotTable TableDestination _
:="Sheet1!R3C1", TableName:="PivotTable44", DefaultVersion:= _
xlPivotTableVersion15
Sheets("Sheet1").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable44").PivotFields("Reasons for Delay")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable44").AddDataField ActiveSheet.PivotTables( _
"PivotTable44").PivotFields("Sum of Reasons for Delay"), _
"Sum of Sum of Reasons for Delay", xlSum
ActiveSheet.PivotTables("PivotTable44").PivotFields("Reasons for Delay"). _
AutoSort xlDescending, "Sum of Sum of Reasons for Delay"
ActiveCell.Offset(0, 1).Range("A1").Select
With ActiveSheet.PivotTables("PivotTable44").PivotFields( _
"Sum of Sum of Reasons for Delay")
.Calculation = xlPercentOfTotal
.NumberFormat = "0,00%"
End With
End Sub
pt7.AddDataField pt7.PivotFields("Reasons for Delay"), "Sum of Reasons for Delay", xlSum
– Rory