×

Steps to Create a Pivot Table

Steps to Create a Pivot Table: Pivot Tables can be easily automated through VBA coding. To create a Pivot Table in VBA, follow the below step by step procedure to create your own Pivot Table. Here we have used dummy data to generate the reports.

Steps to Create a Pivot Table

1. Declare Pivot Cache Object

The first step is to create a pivot cache object to define the data source. It is enabled to ensure the fast functioning of the program. It holds the duplicate data, and whenever we make changes in the Pivot table, it uses the pivot cache. Hence, the actual data does not get hampered.

Program:

Sub CreatePivotTable()
 Dim PTCache As PivotCache 
 End Sub 

2. Declare the Pivot Table Object

The Pivot Table object is used to declare the variable as PivotTables. It contains all the objects of the Pivot Table in a common worksheet.

Program:

Sub CreatePivotTable()
                 Dim PTCache As PivotCache
 Dim PT As PivotTable 
 End Sub 

3. Set the Pivot Cache

We need to set the pivot cache to optimize the pivot table functioning. The user needs to refresh the data to reflect any changes in the Pivot table.

Program:

Sub CreatePivotTable()
     Dim PTCache As PivotCache
     Dim PT As PivotTable
     'Set the Pivot Cache
     Set PTCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, Sheets("Pivot Table").Range("A1").CurrentRegion)
 End Sub 

4. Adding a new Worksheet

Adding a separate new worksheet to insert our Pivot Table as it would make it more readable and easier to relate with actual data.

Program:

Sub CreatePivotTable()
     Dim PTCache As PivotCache
     Dim PT As PivotTable
     'Set the Pivot Cache
     Set PTCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, Sheets("Pivot Table").Range("A1").CurrentRegion)
     ' Adding a new sheet for Pivot Table
     Worksheets.Add
 End Sub 

5. Creating the Pivot Table

In the above worksheet, we will be inserting a blank new Pivot table where we can later define our columns, rows, and values.

Program:

 'Create the Pivot Table
 Set PT = ActiveSheet.PivotTables.Add( _
  PivotCache:=PTCache, _
 TableDestination:=Range("A3")) 

6. Specifying the Fields

Once we have added the blank Pivot Table, the next step is to insert the rows and columns and apply the required filter and features. Unlike in the below code, we have inserted “Region”, “Rep”, “OrderDate” and “Total Billing” Fields to our Table. Next, we PT object to auto group the Dates and have applied a filter to fetch the data associated with the “Central” field.

Program:

    'Specifying the Pivot Fields
     With PT
         .PivotFields("Region").Orientation = xlPageField
         .PivotFields("Rep").Orientation = xlRowField
         .PivotFields("OrderDate").Orientation = xlColumnField
         .PivotFields("Total Billing").Orientation = xlDataField
     'To Group the dates 
         .PivotFields("OrderDate").AutoGroup
     ' NO Field Caption
         .DisplayFieldCaptions = False
     'Filter Data for Central Region Only
         .PivotFields("Region").CurrentPage = "Central"
     'To Change the caption 
         .PivotFields("Sum of Total Billing").Caption = "Total Billing: "
     End With 

The Complete code along with the required Output.

Sub CreatePivotTable()
     Dim PTCache As PivotCache
     Dim PT As PivotTable
     'Set the Pivot Cache
     Set PTCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, Sheets("Pivot Table").Range("A1").CurrentRegion)
     ' Adding a new sheet for Pivot Table 
     Worksheets.Add
     'Create the Pivot Table
     Set PT = ActiveSheet.PivotTables.Add( _
         PivotCache:=PTCache, _
         TableDestination:=Range("A3"))
     'Specifying the Pivot Fields
     With PT 
         .PivotFields("Region").Orientation = xlPageField
         .PivotFields("Rep").Orientation = xlRowField
         .PivotFields("OrderDate").Orientation = xlColumnField
         .PivotFields("Total Billing").Orientation = xlDataField
     'To Group the dates
         .PivotFields("OrderDate").AutoGroup
     ' NO Field Caption 
         .DisplayFieldCaptions = False
     'Filter Data for Central Region Only
         .PivotFields("Region").CurrentPage = "Central"
     'To Change the caption
         .PivotFields("Sum of Total Billing").Caption = "Total Billing: "
     End With
 End Sub 
Steps to Create a Pivot Table

Output

In the below Output, we have created a Pivot Table based on the data. At the top, we have applied a filter on the Region field and have chosen “Central”. We have grouped them by months and have calculated the total billing for different months for Central. Hence, at last, have returned the grand total for all.

Steps to Create a Pivot Table

Related Topics

CodeIgniter File Uploading Class

The Codeigniter provides a file Uploading library class which is used to upload any file such as images, pdf, mp3, etc. to the codeigniter’s application. It also allows to set various preferences such...

5 minutes read.

Excel VBA Day Function

The function Day in VBA returns the day number (from 1 to 31) for the given date value. Syntax Day (Date) Parameter Date (required) – This parameter represents the date. Return This function returns the day...

1 minute read.

VBA ListBox

What is a ListBox? ListBox refers to a permanently displayed control (usually box-shaped) which contains a list of objects (or attribute, or elements) from which the user can select single or multiple attributes....

8 minutes read.

Excel VBA InputBox

Input Box The InputBox function in VBA is used to prompt the users to enter values. The user can click either the OK button or can choose the CANCEL button. If the user clicks...

3 minutes read.

Excel VBA Timer Function

Excel VBA Timer Function: The Timer function in VBA returns a Single data type, evaluating the number of seconds that have elapsed since midnight of the current day. Syntax Timer () Parameter NA Return This...

1 minute read.

Excel VBA LBound Function

Excel VBA LBound Function: The LBound function in VBA returns the lowest subscript for the specified dimension in the given array. Syntax LBound (ArrayName, [Dimension]) Parameter ArrayName (required) – This parameter represents an array for which...

1 minute read.

Excel VBA StrConv Function

The StrConv function in VBA converts a string into a specified format. Syntax StrConv (String, Conversion, [LocaleID]) Parameter String (required) – This parameter represents the string to be converted. Conversion (required) – This parameter specifies the type of conversion. It can...

1 minute read.

Excel VBA: Select … Case Statement

Select … Case Statement When a group of statements is executed, depending upon the value of an Expression, then Switch Case is used.  If you have several conditions to check, then the If condition...

4 minutes read.

VBA runtime error 1004

What is 1004 error?  VBA 1004 Error, also known as object-defined or application-defined, is a runtime error in VBA, usually, if the specified range does not exist in the worksheet or if the Application...

6 minutes read.

Excel VBA Error Handling

What is Errors and Types of Error? Errors are conditions that resist the flow of the program or enables a problem while running any programming. There are three types of errors in VBA...

5 minutes read.

Excel VBA DateAdd Function

The DateAdd function in VBA adds a time interval to a supplied date and/or time and returns the resultant date/time. Syntax Dateadd (Interval, Number, Date) Parameter Interval (required) – This parameter a string specifying the interval to be...

1 minute read.

Excel VBA IsError Function

VBA IsError Function: The IsError function in VBA returns a Boolean value showing whether the specified Expression represents an error or not. Syntax IsError (Expression) Parameter Expression (required)- This parameter represents the variant that you...

1 minute read.

Looping in VBA

Looping in VBA There are many situations where a programmer needs to execute a block of the repetitive code number of times. Writing the same statement will make the program tedious and monotonous....

3 minutes read.

Steps to Create a Pivot Table

Steps to Create a Pivot Table: Pivot Tables can be easily automated through VBA coding. To create a Pivot Table in VBA, follow the below step by step procedure to...

4 minutes read.

Steps to Create a Chart in VBA

Steps to Create a Chart Charts are created either by directly working with the chart variable object that defines the chart data or by ChartObject method. In order to get to...

3 minutes read.

Excel VBA Rnd Function

VBA Rnd Function: The Rnd function in VBA returns a random number that is greater than or equal to (>=) 0 and is less than (<) 1. Syntax Rnd ([Number]) Parameter Number (optional) –This...

1 minute read.

Excel VBA InStr Function

VBA InStr Function The InStr function in VBA searches for a substring inside the given string. It returns the position of a substring within a string, as an integer if the substring is found...

1 minute read.

Excel VBA Month Function

The Mont function in VBA returns the month number for the specified date. Syntax Month (Date) Parameter Time (required) – This parameter represents the date. Return This function returns the month number for the specified date. Example 1 Sub MonthFunction_Example1() ...

1 minute read.

Excel VBA IsMissing Function

VBA IsMissing Function: The IsMissing function in VBA checks if any parameter to a procedure is missing or not. It returns a Boolean value True if the specified parameter has not been...

1 minute read.

VBA VBScript Regex Methods Regex

VBA VBScript Regex Methods Regex The VBA Regex supports 3 methods which are as follows: ExecuteReplaceText Execute The execute method is used to extract a match from the given based on the defined matching...

3 minutes read.