By Ajeet Kumar
EXCEL VBA AN EXAMPLE TO CREATE A PIVOT TABLE
Dim ShtPT As Worksheet
Dim rngSrcData As Range
Dim rngDest As Range
Dim PTCache As PivotCache
Dim PT As PivotTable
For Each PT In Sheet3.PivotTables
PT.TableRange2.Clear
Next
Set rngSrcData = Sheet2.Range("A1").CurrentRegion
Set rngDest = Sheet3.Range("C3")
Set PTCache = ThisWorkbook.PivotCaches.Create(xlDatabase, rngSrcData)
Set PT = PTCache.CreatePivotTable(TableDestination:=rngDest)
With PT.PivotFields(1)
.Orientation = xlPageField
.Position = 1
End With
With PT.PivotFields(2)
.Orientation = xlRowField
.Position = 1
End With
With PT.PivotFields(3)
.Orientation = xlColumnField
.Position = 1
End With
With PT.PivotFields(4)
.Orientation = xlDataField
.Position = 1
.Function = xlSum
End With
With PT.PivotFields(4)
.Orientation = xlDataField
.Function = xlCount
End With
Set rngSrcData = Nothing
Set rngDest = Nothing
Set PTCache = Nothing
Set PT = Nothing
End Sub
The
following steps are required to create a pivot table using VBA.
- An instance of PivotCache is created by using Create Method of PivotCaches collection.
- The Create method is passed source data range in case excel sheet provides the data.
- An instance of PivotTable is created by using CreatePivotTable method of PivotTable object. The CreatePivotTable method is passed the Destination Cell where the pivot table will be generated.
- The PIvotFields collection is indexded to refer pivot fields.
- The properties are set for each field included in the pivot table.
Dim ShtPT As Worksheet
Dim rngSrcData As Range
Dim rngDest As Range
Dim PTCache As PivotCache
Dim PT As PivotTable
For Each PT In Sheet3.PivotTables
PT.TableRange2.Clear
Next
Set rngSrcData = Sheet2.Range("A1").CurrentRegion
Set rngDest = Sheet3.Range("C3")
Set PTCache = ThisWorkbook.PivotCaches.Create(xlDatabase, rngSrcData)
Set PT = PTCache.CreatePivotTable(TableDestination:=rngDest)
With PT.PivotFields(1)
.Orientation = xlPageField
.Position = 1
End With
With PT.PivotFields(2)
.Orientation = xlRowField
.Position = 1
End With
With PT.PivotFields(3)
.Orientation = xlColumnField
.Position = 1
End With
With PT.PivotFields(4)
.Orientation = xlDataField
.Position = 1
.Function = xlSum
End With
With PT.PivotFields(4)
.Orientation = xlDataField
.Function = xlCount
End With
Set rngSrcData = Nothing
Set rngDest = Nothing
Set PTCache = Nothing
Set PT = Nothing
End Sub
No comments:
Post a Comment