Skip to content

Excel VBA – How to Create a PivotTable with Excel Macro

    To create a PivotTable, first define the PivotTable cache using PivotCaches.Create. Then create the PivotTable using PivotCaches.Add

    PivotCaches.Create has the following parameters:

    PivotCaches .Create(SourceType, SourceData, Version)

    SourceType can be xlConsolidation, xlDatabase, or xlExternal.

    Version can be…

    NameValueDescription
    xlPivotTableVersion20000Excel 2000
    xlPivotTableVersion101Excel 2002
    xlPivotTableVersion112Excel 2003
    xlPivotTableVersion123Excel 2007
    xlPivotTableVersion144Excel 2010
    xlPivotTableVersion155Excel 2013
    xlPivotTableVersionCurrent-1Provided only for backward compatibility
    PivotCaches.Add has the following parameters
    PivotCaches.Add(PivotCache, TableDestination, TableName,ReadData, DefaultVersion)

    The code below relates to the data shown above.

    Dim ws As Worksheet
    Set ws = ActiveSheet
    Dim wb As Workbook
    Set wb = ActiveWorkbook
    Dim PTcache As PivotCache
    Dim PT As PivotTable
    'Define the cache for the PivotTable
    Set PTcache =wb.PivotCaches.Create(SourceType:=xlDatabase, _
    SourceData:=Range("Sales_Data[#All]"),Version:=xlPivotTableVersion15)
    'Create the PivotTable
    Set PT =ws.PivotTables.Add(PivotCache:=PTcache, _
    TableDestination:=Range("J1"),TableName:="Sales Analysis")
    With PT
    .PivotFields("Branch").Orientation = xlRowField
    .PivotFields("ProductCategory").Orientation = xlColumnField
    .PivotFields("Region").Orientation= xlPageField
    .PivotFields("Revenue").Orientation = xlDataField
    .DataBodyRange.NumberFormat ="£#,##0;-£#,##0"
    End With

    The code above would create the PivotTable shown below

    Alternatively use the AddFields and AddDataFields of thePivotTable object, as shown below. Use array to specify more than one field.

    Dim ws As Worksheet
    Set ws = ActiveSheet
    Dim wb As Workbook
    Set wb = ActiveWorkbook
    Dim PTcache As PivotCache
    Dim PT As PivotTable
    'Define the cache for the PivotTable
    Set PTcache =wb.PivotCaches.Create(SourceType:=xlDatabase, _
    SourceData:=Range("Sales_Data[#All]"),Version:=xlPivotTableVersion15)
    'Create the PivotTable
    Set PT =ws.PivotTables.Add(PivotCache:=PTcache, _
    TableDestination:=Range("J1"),TableName:="Sales Analysis")
    PT.AddFieldsRowFields:=Array("Region", "Branch"), _
    ColumnFields:="Product",PageFields:="Product Category"
    PT.AddDataFieldField:=PT.PivotFields("Revenue"), _
    Caption:="No of Transactions", Function:=xlCount

    The code above would create the PivotTable shown below.