How to use a VBA Code to Create a Pivot Table [Writing a Macro Step By Step]  

Before I hand over this guide to you to start using VBA to create a pivot table, let me confess something.

I have learned using VBA just four years back and the first time when I wrote a macro code to create a pivot table, it was a failure.

Since then I have learned more from my bad coding rather than from the codes which actually work.

And today, I will show you a simple way to automate your pivot tables using this macro code.

When normally when you insert a pivot table in a worksheet it happens through a simple process but that entire process is so quick that you never notice what happened.

In VBA, that entire process is same just executes using a code. In this guide, I’ll show that each step and how to write a code for it.

Just look at the 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

Eight Simple Steps to Write a Macro Code for Pivot Table

For your convenience, I have split the entire process into 8 simple steps. And, 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, 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.

'Insert a New Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("Data")

If you want to change the name of the worksheet, you can replace it from the code.

#3. Define Data Range

Now, next thing 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.

#4. Create Pivot Cache

In Excel 2000 and above, before creating a pivot table you need to create a pivot cache to define the data source.

Normally when you create a pivot table, Excel automatically creates a pivot cache without asking you, but when you need to use VBA, you need to write a code for this.

And  below code is for this:

'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="SalesPivotTable")

This code works in two way, first define a pivot cache by using data source and second define the cell address in the newly inserted worksheet to insert the pivot table.

You can change the position the pivot table by editing this code.

#5. Insert a Blank Pivot Table

After pivot cache, next step is to insert a blank pivot table.

Just remember when you create a pivot table what happens, you always get a blank pivot first and then you define all the values, columns, and row.

insert a blank pivot to use vba to create pivot table in excel

This code will do the same:

'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="SalesPivotTable")

This code creates a blank pivot table and names it "SalesPivotTable". You can change this name from the code itself.

#6. Insert Row and Column Fields

After creating a blank pivot table, next thing is to insert row and column fields, just like you do normally.

For each row and column field, you need to write a code. Here we want to add years and month in row field and zones in the column field.

insert row column fields to use vba to create pivot table in excel

Here is the code:

'Insert Row Fields
With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Year")
.Orientation = xlRowField
.Position = 1
End With

With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Month")
.Orientation = xlRowField
.Position = 2
End With

'Insert Column Fields
With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Zone")
.Orientation = xlColumnField
.Position = 1
End With

In this code, you have mentioned year and month as two fields. Now, if you look at the code you'll find that there is also a position number is there.

​This position number defines the sequence of fields.

​Whenever you need to add more than one fields (Row or Column) make sure to specify their position.

And, you can change fields by editing their name from code.

#7. Insert Data Field

Now, the main thing is to define value field in your pivot table.

The code for defining values is a bit different from defining row and columns because here we need to define the formatting of number, position, and function.

'Insert Data Field
With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Amount")
.Orientation = xlDataField
.Position = 1
.Function = xlSum
.NumberFormat = "#,##0"
.Name = "Revenue "
End With

With above code, you can add amount as the value field. And this code will format values as a number with (,) separator.

We are using xlsum to sum values but you can also use xlcount and other functions as well.

#8. Format Pivot Table

In the end, you need to use a code to format your pivot table.

Normally in a pivot table there is also a default formatting and then you change that formatting. But with VBA you can define formatting style withing the code.

use vba to create pivot table in excel formatting

Code is:

'Format Pivot
TableActiveSheet.PivotTables("SalesPivotTable").ShowTableStyleRowStripes = TrueActiveSheet.PivotTables("SalesPivotTable").TableStyle2 = "PivotStyleMedium9"

Above code will apply row strips and "Pivot Style Medium 9" style but you can also use another style.

Finally, you're code is ready to use.

Full Macro Code to Create a Pivot Table

Sub InsertPivotTable()
'Macro By ExcelChamps

'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

'Insert a New Blank Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("PivotTable").Delete
Sheets.Add Before:=ActiveSheet
ActiveSheet.Name = "PivotTable"
Application.DisplayAlerts = True
Set PSheet = Worksheets("PivotTable")
Set DSheet = Worksheets("Data")

'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)

'Define Pivot Cache
Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="SalesPivotTable")

'Insert Blank Pivot Table
Set PTable = PCache.CreatePivotTable _
(TableDestination:=PSheet.Cells(1, 1), TableName:="SalesPivotTable")

'Insert Row Fields
With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Year")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Month")
.Orientation = xlRowField
.Position = 2
End With

'Insert Column Fields
With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Zone")
.Orientation = xlColumnField
.Position = 1
End With

'Insert Data Field
With ActiveSheet.PivotTables("SalesPivotTable")
.PivotFields("Amount")
.Orientation = xlDataField​
.Function = xlSum
.NumberFormat = "#,##0"
.Name = "Revenue "
End With

'Format Pivot Table
ActiveSheet.PivotTables("SalesPivotTable").ShowTableStyleRowStripes = True
ActiveSheet.PivotTables("SalesPivotTable").TableStyle2 = "PivotStyleMedium9"

End Sub

Sample File

Enter your name and email below to get the sample file directly into your inbox.

Conclusion

By using this code we can automate your pivot tables.

Now tell me one thing.

Have you ever used VBA a code to create a pivot table?

Please share your views with me in the comment box, I'd love to share with you and make sure to share this tip with your friends.