How to create a pivot table in Excel using VBA MACRO CODE

Generic filters

Table of Contents

A Step By Step Process to Create a Pivot Table in Excel using VBA – MACRO CODE

Before you read this article and you start using VBA to create a pivot table let me tell you something. First time when I wrote a macro code to create a pivot table, it was a failure, thus by using our VBA code can be easy for you, however, in case you want o customize it as per your requirement you need to carefully look at code whether it actually correct. Else, you may also end up fail. But never the less, you need keep trying for result because its worth it!

Since then as individual, I have learned more from my bad coding rather than from the codes which actually work. From this article, you will gain understanding of a simple way to automate your pivot tables using a macro code. Normally, when you insert a pivot table in a excel worksheet it happens through a simple process, but that entire process is so quick that you never notice what just happened.

In VBA, that entire process is same, its just executes using a MACRO code. In this guide, we’ll show you each step and explain how to write a code for it. You can see below example, where you can run this macro code with a button and it returns a new pivot table in a new worksheet in a flash.

Macro Codes To Create A Pivot Table

Without any further ado, let’s get started to write our macro code to create a pivot table.

The Simple 8 Steps to Create a Pivot Table in Excel Using Macro Code in VBA 

For your convenience, I have split the entire process into 8 simple steps. After following these steps you will able to automate your all the pivot tables. 

1. Declare Variables

The first step is to declare the variables which we need to use in our code to define different things.

 ‘Declare Variables

Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long

In the above code, we have declared:

  1. PSheet: To create a sheet for a new pivot table.
  2. DSheet: To use as a data sheet.
  3. PChache: To use as a name for pivot table cache.
  4. PTable: To use as a name for our pivot table.
  5. PRange: to define source data range.
  6. LastRow and LastCol: To get the last row and column of our data range.

2. Insert a New Worksheet

Before creating a pivot table, In Excel inserts a blank sheet and then create a new pivot table there.

insert a new worksheet to use vba to create pivot table in excel

And, below code will do the same for you. It will insert a new worksheet with the name “Pivot Table” before the active worksheet and if there is worksheet with the same name already, it will delete it first. After inserting a new worksheet, this code will set the value of PSheet variable to pivot table worksheet and DSheet to source data worksheet.

Macro Code:

‘Declare Variables
On Error Resume Next
Application.DisplayAlerts = False
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = “PivotTable”
Application.DisplayAlerts = True
Set PSheet = Worksheets(
Set DSheet = Worksheets(

Customization Tip: If the name of the worksheets which you want to refer in the code is different then make sure to change it from the code where I have highlighted in red.

Define Data Range

Now, next step is to define data range from the source worksheet. Here you need to take care of one thing that you can’t specify a fixed source range. You need a code which can identify the entire data from source sheet. And, below is the code:


‘Define Data Range
LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)

This code will start from the first cell of the data table and select up to the last row and then up to the last column. And finally, define that selected range as a source. The best part is, you don’t need to change data source every time while creating the pivot table.

We Create Your Life Easy With Our Free Excel Templates & Spreadsheet Dashboards

Use free Excel Templates, Tools and Dashboards to create and draft a professional looking dashboards and computation sheet for your personal and business use. You can Explore Calendars, Activity Planners, Invoice Templates, Sales Forecast Sheets, Budget templates and various business information delivering Templates in Excel and Spreadsheet at XLSX Templates. 

These templates, dashboards and tools are useful in various occasions. You can also customize these templates as per your requirement. Modification of fields and data source helps in making the template more relevant.

Learn Microsoft Excel : Blogs and Articles

Learn about various tips and tricks in Microsoft Excel and Spreadsheet. Create best templates and dashboards using free tricks and tutorials in excel and spreadsheet. These tutorial posts are useful for everyone who wants to master the skills in excel and spreadsheet.

Deselect Cells in Excel

How To Deselect Cells in Excel

Table of Contents How to Deselect Cells in Excel After adding the deselecting cells feature in Excel, this  becomes so  …

Select Non-Contiguous Cells in Excel

Learn how to Select Non-Contiguous Cells in Excel

Table of Contents Select cell without using Ctrl Key By following these simple steps we can do it. At first, …

Format Painter in Excel

How to use Format Painter in Excel

Table of Contents Where’s the Format Painter Button? It’s there on your Home Tab. If you look at the clipboard …

Apply Strikethrough in Excel [Shortcut + Command]

How to apply Strikethrough in Excel [Shortcut + Command]

Table of Contents Shortcut Key to Apply Strikethrough to a Cell Let’s say you’re in hurry and don’t want to …

Formula Bar in Excel

Formula Bar in Excel

Table of Contents Key Points To Consider Using Formula Bar You can hide or unhide the formula bar. You can …

Convert Date into Day

Convert Date into Day Sub date2day() Dim tempCell As Range Selection.Value = Selection.Value For Each tempCell In Selection If IsDate(tempCell) …

Basic VBA Macro Codes in Excel

Custom Header & Footer

Sub CustomHeader() Dim myText As String myText = InputBox(“Enter your text here”, “Enter Text”) With ActiveSheet.PageSetup .LeftHeader = “” .CenterHeader …

Get Macro Code

Add Header and Footer Date

Sub DateInHeader() With ActiveSheet.PageSetup .LeftHeader = “” .CenterHeader = “&D” .RightHeader = “” .LeftFooter = “” .CenterFooter = “” .RightFooter …

Get Macro Code

Open Calculator

Sub OpenCalculator() Application.ActivateMicrosoftApp Index:=0 End Sub In Windows, there is a specific calculator and by using this macro code you …

Get Macro Code

Unmerge Cells

Sub UnmergeCells() Selection.UnMerge End Sub Unmerge Cells code simply uses the unmerge options which you have on the HOME‌ tab. …

Get Macro Code

Remove Text Wrap

Sub RemoveTextWrap() Range(“A1”).WrapText = False End Sub This code will help you to remove text wrap from the entire worksheet …

Get Macro Code

Auto Fit Rows

Sub AutoFitRows() Cells.Select Cells.EntireRow.AutoFit End Sub You can use this code to auto-fit all the rows in a worksheet. When …

Get Macro Code

Auto Fit Columns

Sub AutoFitColumns() Cells.Select Cells.EntireColumn.AutoFit End Sub Use above Excel macro code to auto fit rows in all your sheet at …

Get Macro Code

Insert Multiple Columns

Sub InsertMultipleColumns() Dim i As Integer Dim j As Integer ActiveCell.EntireColumn.Select On Error GoTo Last i = InputBox(“Enter number of …

Get Macro Code

Insert Multiple Rows

Sub InsertMultipleRows() Dim i As Integer Dim j As Integer ActiveCell.EntireRow.Select On Error GoTo Last i = InputBox(“Enter number of …

Get Macro Code