Dear All,
I am trying to create a Pivot using Excel VBA using CreatePivot vba.<?xml:namespace prefix = o ns = "urn:schemas-microsoft-comfficeffice" /><o></o>
<o> </o>
It is failing at adding Datafields.<o></o>
Your help would be appreciated.
Biz<o></o>
I am trying to create a Pivot using Excel VBA using CreatePivot vba.<?xml:namespace prefix = o ns = "urn:schemas-microsoft-comfficeffice" /><o></o>
<o> </o>
It is failing at adding Datafields.<o></o>
Code:
Sub CreatePivot()
Dim wsTarget As Worksheet
Dim wsDestination As Worksheet
Dim vrnPC As PivotCache
Dim vrnPT As PivotTable
Dim vrnWS As Worksheet
Set vrnWS = ActiveSheet
Dim vrnRng As Range
Dim finalRow As Long, finalCol As Long
Set wsTarget = Sheets("Adj")
Set wsDestination = Sheets("Pivot")
wsTarget.Activate
finalRow = Cells(Rows.Count, "A").End(xlUp).Row
finalCol = Cells(9, 256).End(xlToLeft).Column
Set vrnRng = wsTarget.Cells(1, 1).Resize(finalRow, finalCol).Offset(8, 0)
vrnRng.Select 'Test Range
wsDestination.Activate
Cells.Delete Shift:=xlUp ' Delete Previous Pivot table
'Create pivot table Cache from the table
Set vrnPC = ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, _
SourceData:=vrnRng)
'Create pivot table
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=vrnRng, _
Version:=xlPivotTableVersion10).CreatePivotTable _
TableDestination:=wsDestination.Range("A3"), TableName:="PivotTable1", DefaultVersion _
:=xlPivotTableVersion10
'Create Pivot Table filters xlPageField
With wsDestination.PivotTables("PivotTable1").PivotFields("List")
.Orientation = xlPageField
.Position = 1
.PivotItems("").Visible = False
End With
'Create Row Label
With wsDestination.PivotTables("PivotTable1").PivotFields("Class")
.Orientation = xlRowField
.Position = 1
.PivotItems("(blank)").Visible = False
End With
'Add Datafields
With wsDestination.PivotTables("PivotTable1")
.AddDataField.PivotFields ("Revenue"), "Sum of Revenue", .Function = xlSum
.AddDataField.PivotFields ("Repairs & Maintenance"), "Sum of Repairs & Maintenance", .Function = xlSum
.AddDataField.PivotFields ("Fuel"), "Sum of Fuel", .Function = xlSum
.AddDataField.PivotFields ("Other"), "Sum of Other", .Function = xlSum
.AddDataField.PivotFields ("Licence & Tax"), "Sum of Licence & Tax", .Function = xlSum
.AddDataField.PivotFields ("Leased Costs"), "Sum of Leased Costs", .Function = xlSum
.AddDataField.PivotFields ("Depreciation"), "Sum of Depreciation", .Function = xlSum
.AddDataField.PivotFields ("Total Expenses"), "Sum of Total Expenses", .Function = xlSum
.NumberFormat = "#,##0.00_);[Red](#,##0.00)"
End With
End Sub
Your help would be appreciated.
Biz<o></o>