REAL-TIME

VBA Projects

Full Access with Source Code
  • Designed and Developed by PNRao

  • Full Access with VBA Source Code

  • Well Commented Codes Lines

  • Creative and Professional Design

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:
  • 50+ Excel Templates

  • 50+ PowerPoint Templates

  • 25+ Word Templates

Share Post

Pivot tables in Excel VBA helps us to create summary tables for analyzing our data. We can create different aggregates, change the formats and create the calculated fields. We will see Pivot Table operation using Excel VBA.

Creating Pivot Tables in Excel VBA

This example code will show you how to create Pivot tables using Excel VBA. Instructions are commented in the code to understand the use of each statement.

'Example Data in Sheet1
'Department  Region     Profit
'109            5         119000
'107            3         64000
'109            2         12000


Sub sbCreatePivot()

'Declaration
Dim ws As Worksheet
Dim pc As PivotCache
Dim pt As PivotTable

'Adding new worksheet
Set ws = Worksheets.Add

'Creating Pivot cache
Set pc = ActiveWorkbook.PivotCaches.Create(xlDatabase, "Sheet1!R1C1:R10C3")

'Creating Pivot table
Set pt = pc.CreatePivotTable(ws.Range("B3"))

'Setting Fields
With pt
    'set row field
    With .PivotFields("Department")
    .Orientation = xlRowField
    .Position = 1
    End With
    
    'set column field
    With .PivotFields("Region")
    .Orientation = xlColumnField
    .Position = 1
    End With
    
    'set data field
    .AddDataField .PivotFields("Profit"), "Sum of Profit", xlSum
End With

End Sub

Create Pivot Chart using Excel VBA

This example will show you how to create Pivot chart using Pivot table. Instructions are commented in the code.

Sub sbPivotChartInNewSheet()

'declaration
Dim pt As PivotTable, ptr As Range, cht As Chart
    
'If no pivots exit procedure
    If ActiveSheet.PivotTables.Count = 0 Then Exit Sub
    
'setting piovot table
 Set pt = ActiveSheet.PivotTables(1)
 Set ptr = pt.TableRange1
 
' Add a new chart sheet.
Set cht = Charts.Add
    With cht
        .SetSourceData ptr
        .ChartType = xlLine
    End With

End Sub

Create Pivot Column Chart using Excel VBA

This is same as the above, the only change is Chart type. So we can use all chart options to Pivot charts.

Sub sbPivotChart()

Dim sh As Shape

'If no pivots exit procedure
If ActiveSheet.PivotTables.Count = 0 Then Exit Sub

'setting piovot table
 Set pt = ActiveSheet.PivotTables(1)
 Set ptr = pt.TableRange1

'Add chart
Set sh = ActiveSheet.Shapes.AddChart
sh.Select
 With ActiveChart
        .SetSourceData ptr
        .ChartType = xl3DColumn
End With

End Sub

Create Calculated Pivot Field in Excel VBA

We may not to store the calculated fields in the table or Excel worksheet. We can create the calculated field in the Pivot tables as shown below. So that we can save the space and easity manage the and analyse the data.

Sub sbCreateCalculatedField()

'Example Data in Sheet1
'Department  Region     Profit
'109            5         119000
'107            3         64000
'109            2         12000

'Declaration
Dim ws As Worksheet
Dim pc As PivotCache
Dim pt As PivotTable
'Adding new worksheet
Set ws = Worksheets.Add

'Creating Pivot cache
Set pc = ActiveWorkbook.PivotCaches.Create(xlDatabase, "Sheet1!R1C1:R10C3")

'Creating Pivot table
Set pt = pc.CreatePivotTable(ws.Range("B3"))

'Setting Fields
With pt
    'set row field
    With .PivotFields("Department")
    .Orientation = xlRowField
    .Position = 1
    End With
    
    'set column field
    With .PivotFields("Region")
    .Orientation = xlColumnField
    .Position = 1
    End With
    
    '***Create Calculated Field
    .CalculatedFields.Add "Savings", "=Profit*.1"
    
    'set data field
    .AddDataField .PivotFields("Savings"), "Sum of Savings", xlSum
End With

End Sub
Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Project Management Templates

All-in-One Pack
120+ Project Management Templates

Essential Pack
50+ PM Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project
Management Template
Ultimate Resource
Management Template
Project Portfolio
Management Templates
Categories: Excel VBATags: Last Updated: March 1, 2013

20 Comments

  1. Lisa August 9, 2014 at 7:26 AM

    Hi Valli,
    you are so good..
    would you be able to demonstrate pivot tables with conditional formatting in vba .
    say I would like to format all values in . PivotFields(“Percent of “) for anything between 10 and 25 in red , 20 and 50 in blue and 50 to 75 in yellow.
    How would you do this?

  2. Valli August 17, 2014 at 11:29 AM

    Hi Lisa,
    Thanks for your comments. I will provide an example ASAP.

    Thanks-Valli!

  3. Durga February 5, 2015 at 7:35 PM

    Hi Lisa,

    I need a quick help. I have a complicated Pivot table, with main status showing on dates for 5 different columns. The date of each column had to be compared with todays date and status of the template say example 1, then as below

    as of today(02.05.15) if I look at the column 1 date(01.14.15) and status = 1, I have to mark the cell as RED color.

    Please help.

    Thanks
    Durga.

  4. PNRao February 5, 2015 at 8:44 PM

    Hi Durga,

    You can do this using Conditional formatting. You can also use the below VBA code to check the pivot row labels and highlignt in red if it matches the criteria:

    Sub HilightPivotCellsBasedOnCondition()
        For Each cell In ActiveSheet.PivotTables(1).RowRange ' this loop through the each cell in the pivot table row labels/ side labels
            If Format(cell.Value, "mm.dd.yy") = Format(Now(), "mm.dd.yy") Then cell.Interior.Color = RGB(225, 0, 0)
        Next
    End Sub
    

    Thanks-PNRao!

  5. Faheeem February 13, 2015 at 12:03 AM

    Hi,

    I wanted to creat pvot table, Based on pivot field creteria tab.

    for example.In sheet 2 i have pvot feild list Field1–Label1(Geography),Label2-(Industry),Label3-(Sector),Data ColumnsLabel1- (Cost),Label2(Value).In Sheet1 Data which is not constant.The size of the data keep on changing.

    How would you do this.

    Thanks
    Faheem

  6. Vishal May 12, 2015 at 6:18 PM

    Hi,

    I have a lot of pivots for which show the data for 5 weeks. Now every new week, I have to take the oldest week number out and select the new week in. Is there a VB script to do this?

  7. PNRao May 13, 2015 at 8:42 PM

    Hi Vishal,

    You can use the below code to loop through the pivot items and select the a Pivot Item:

    
    Sub LoopthorughThePivotTableAndSelectAnItem()
    
    Set pTable = ActiveSheet.PivotTables(1)
    Set pField = pTable.PivotFields("Cat")
    pvtValToSlect = 6 ' Week number to be selected
    
        'first: select the required item
        For Each PItem In pField.PivotItems
            If CStr(PItem.Caption) = CStr(pvtValToSlect) Then PItem.Visible = True
        Next
        
        'then: unselect the remaining items
        For Each PItem In pField.PivotItems
          If CStr(PItem.Caption) <> CStr(pvtValToSlect) Then PItem.Visible = False
        Next   
    
    End Sub
    

    Thanks-PNRao!

  8. Pradeep SB May 27, 2015 at 11:02 PM

    Please could i know how can i run this program

  9. Santosh Hanamgonda September 26, 2015 at 6:59 AM

    Hello

    I have coded to for pivot table I am getting correct table still I want some changes in that

    1. same macro using 2nd time than should delet last pivot table
    2. I want chnges in pivot table heading color and cell color
    3. I need border for pivot table.
    4. I want to change “grangd total” to “total work Completed”.
    5. I want add comment below pivote table as work completed before 5pm.

    Now coded like these

    Sub sbCreatePivot()
    ‘Declaration
    Dim ws As Worksheet
    Dim pc As PivotCache
    Dim pt As PivotTable

    ‘If “Pivot” worksheet already exists, delete it

    On Error Resume Next
    Application.DisplayAlerts = False
    Sheets(“Pivot”).Delete
    On Error GoTo 0
    Application.DisplayAlerts = True

    ‘Adding new worksheet
    Set ws = Worksheets.Add

    ‘Creating Pivot cache
    Set pc = ActiveWorkbook.PivotCaches.Create(xlDatabase, “Sheet1!R1C1:R13C8”)

    ‘Creating Pivot table
    Set pt = pc.CreatePivotTable(ws.Range(“B3”))

    ‘Setting Fields
    With pt
    ‘set row field
    With .PivotFields(“Type”)
    .Orientation = xlRowField
    .Position = 1

    End With

    ‘set data field
    .AddDataField .PivotFields(“work count”), ” work count”, xlSum
    End With
    End Sub

    Date from Type IteM# work App weight serial
    12/23/2015 x A 2312 1 A 233 31123
    12/23/2015 y B 3 2 b 213 123
    12/23/2015 z C 21 3 c 313 3123
    12/23/2015 n D 321 1 d 13 313
    12/23/2015 m E1 12 2 a 13 3
    12/23/2015 f B 1231 3 s 13 12
    12/23/2015 r C 213 4 s 13 31
    12/23/2015 n A 123 2 d 31 3
    12/23/2015 e D 13 4 s 2 12
    12/23/2015 s F 123 20 d 123 3
    12/23/2015 x G 31 2 a 3 12

    above table I need colums are Type and work.

    Now I am geeting below shown

    Row Labels Sum of Work
    A 3
    B 5
    C 7
    D 5
    E1 2
    F 20
    G 2
    (blank)
    Grand Total 44

    can you you help me out to make required changes

  10. Santosh Hanamgonda September 26, 2015 at 7:02 AM

    data heading are Date, from ,Type, IteM#, work ,App .weight, serial

    Pivot table headings are Row Labels, Sum of Work

  11. Rajeevan December 13, 2015 at 10:02 AM

    Hai sir,
    i need your help, can u help me i am explain here what i need, actually i am doing a business so i need monthly outstanding report with easily i am using excel for entering details of sales so how can i get each party report i need party name qty of sale totl amount of each date like pls help

  12. Laxman kumar January 31, 2016 at 6:11 PM

    Pivot table’s example that given here is so useful to learn. Thanx alot

  13. krishna February 11, 2016 at 6:27 PM

    Hi there,

    I am trying to use vba code to select a single field from my pivot then go back to the pivot to select multiple fields from the filter.

    Any ideas?

    Thanks
    Krishna

  14. dash March 3, 2016 at 2:24 AM

    how to select the filter

  15. Krishnan July 27, 2016 at 11:41 AM

    Hi guys. Need a quick help.

    For my monthly reporting , how can I make the pivot to add a new month by itself , as and when a new month raw data is added??

    Thanks
    Krishnan

  16. Jana September 22, 2016 at 6:42 AM

    Hi.
    This is very helpful.
    I have created a complex pivot table and it works perfectly when I use the code in Excel 2010.
    But when I tried the same code in Excel 97-2003, it errors on creating the pivot table.
    I wish to create it in Excel 97-2003 because pivot table is easier to format in this version. Please help out. Thank you very much

  17. Jana September 22, 2016 at 6:48 AM

    ….correction, I used the code in Excel 2013 (not 2010).

  18. ricky May 25, 2017 at 10:01 PM

    Hai
    i need some help

    we all know that in the user form, we can load or show image or picture, and load or show the data with list object.. etc..
    but how can i show a pivot table in the user form ? which object i have to use ? can i use list object (in toolbox)? and how can i use it ? give me an example code..
    and please tell me how to add a calendar object in the toolbox..
    thanks

  19. Bala June 9, 2017 at 6:09 PM

    Hai Valli,

    I am new to vba. I have some requirement based on manipulating data. I have spent time on googling to complete the things, but i can’t understand by their way of approach. I recently found your site, you are providing good things to learn. I need a sample excel macro file that satisfy the below listed operations,

    1) Copy multiple sheets entire data to one workbook
    2) Add some coulmns
    3) Make some multiple column filter with multiple criteria
    4) Fill cell based on filtered results to new column
    5) Make VLOOKUP with opened another sheet data
    5) Finally form some PIVOT TABLE .

    Please guide me how to do the above.

    Thanks in ADVANCE…..

  20. Midhun T M August 1, 2020 at 10:57 AM

    Hi I am working on a VB code to get the row grand total, I have applied the last coding as the below.But not getting value fields row total in to the Grand Total column.

    With ActiveSheet.PivotTables(“PivotTable”).PivotFields(“*Engagement name”)
    .Orientation = xlDataField
    .Position = 132
    .NumberFormat = “#,##0”
    .Name = “Grand Total”
    .PivotFields (“Grand Total”), “Grand Total”, xlSum

    *Engagement name *Resource name *Office location *Current grade 25-Jan-21 01-Feb-21 08-Feb-21 15-Feb-21 22-Feb-21 Grand Total

Leave A Comment