Using Excel VBA to Change the Pivot Table Source – 2 Methods

 

What Is a Pivot Table in Excel?

A pivot table is a tool through which you can select the data from a dataset and calculate, analyze, summarize, and get data trends.


The dataset contains Product ID, Product, category, sales of the products, Date, and Outlets of a grocery shop.

 

Dataset to change pivot table data source with Excel vba


Method 1 – Using Excel VBA to Change Pivot Table Data in the Same Source Range

Steps:

  • Select C4:E12.
  • Select Insert >> Pivot Table in the Toolbar.

Selecting range to create pivot table

  • In the Pivot Table dialog box, select New Worksheet >> OK.

insert  table range to in pivot table dialog box

  • Select all the categories in the pivot table fields to get a pivot table.
  • Change the name of the sheet to Pivot Table.

showing pivot table with pivot table fields

Opening VBA module

  • Enter the code in the module.

Writing vba code to change the pivot table source

Code:

Sub ChangePivotTableDataSource()
Dim pivotTable As pivotTable
Dim newRange As Range
Set newRange = Sheets("Dataset").Range("B4:G12")
Set pivotTable = Sheets("Pivot Table").PivotTables("PivotTable1")
' Change the name of the sheets according to _
your sheet name for both newRange and pivot table
pivotTable.ChangePivotCache ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=newRange)
pivotTable.RefreshTable
End Sub

Code Breakdown:

Sub ChangePivotTableDataSource()
Dim pivotTable As pivotTable
Dim newRange As Range
Set newRange = Sheets("Dataset").Range("B4:G12")
  • In the subroutine ChangePivotTableDataSource, the pivot table is declared as pivotTable and the changed range B4:G12 is declared as Range.
Set pivotTable = Sheets("Pivot Table").PivotTables("PivotTable1")
' Change the name of the sheets according to _
your sheet name for both newRange and pivot table
  • Sheets(“Pivot Table”) refers to the sheet to execute the process and (PivotTable1) specifies the pivot table.
  pivotTable.ChangePivotCache ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=newRange)
pivotTable.RefreshTable
End Sub
  • Changes the data source of the dataset and creates new pivot caches. Sets source data range in a new range and ends this program.

  • Click Run.
  • Go back to the sheet and check if the program is correctly run. You can create a button:
  • Select Developer >> Insert >> Button (Icon) in the Toolbar.

adding command button

  • Place the button in the sheet.
  • In the Assign Macro dialog box, select the assigned macro and click OK.

assigning macro to the source data

  • Place the cursor on the button and right-click to see the options menu.
  • Select Edit Text to change the name of the button.

using Edit Text from the menu

Note:

You can change the format using Edit Text.

selecting Format Control option

  • Click the button to see the final output.

If you change data in B4:G12, you will get a new output.


Method 2 – Using Excel VBA to Change Pivot Table Data and the Source Range

A row and a column were added to the dataset.

dataset to change pivot table data for changing source range

Steps:

  • Follow the steps described in Method 1 to open a new Module.
  • Enter the code.

Writing vba code to change pivot table source

Code:

Sub ChangePivotTableDataSource2()
Dim pivotTable As pivotTable
Dim newRange As Range
Dim rangeAddress As String
On Error Resume Next
Set newRange = Application.InputBox("Selected Range:", Type:=8)
On Error GoTo 0
If newRange Is Nothing Then
MsgBox "Invalid range", vbExclamation
Exit Sub
End If
'Select sheet name according to your Excel sheet name and add pivot table number according to your Excel sheet as well
Set pivotTable = Sheets("Pivot Table 2").PivotTables("PivotTable2")
pivotTable.ChangePivotCache ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=newRange)
pivotTable.RefreshTable
End Sub

Code Breakdown:

Sub ChangePivotTableDataSource2()
    Dim pivotTable As pivotTable
    Dim newRange As Range
    Dim rangeAddress As String

Declares the subroutine ChangePivotTableDataSource2 in which the pivot table is declared as pivotTable, the new range is declared as Range, and the range address is declared as String.

   On Error Resume Next
    Set newRange = Application.InputBox("Selected Range:", Type:=8)
    On Error GoTo 0
    If newRange Is Nothing Then
        MsgBox "Invalid range", vbExclamation
        Exit Sub
    End If

Selects a new range using the Input Box so that the range will be dynamic. If you input the wrong range, VBA stops the procedure and terminates the program.  On Error Go To 0 is used to work with the error and show “Invalid range”.

  pivotTable.ChangePivotCache ActiveWorkbook.PivotCaches.Create( _
        SourceType:=xlDatabase, _
        SourceData:=newRange)
    pivotTable.RefreshTable
End Sub

Changes the data source of the dataset, creates new pivot caches and ends the program by Setting the source data range in a new range.

  • Add a button. Follow the steps described in Method 1.
  • Click the button to select the changed dataset and see the output.

Things to Remember

  •  If the VBA option is blocked, select File >> Option >> Trust Center >> Trust Center settings >> Macro settings >> Enable Macro >> OK.

 


Download Practice Workbook

Download the practice sheet here.


Related Articles


<< Go Back to Pivot Table Data Source | Pivot Table in Excel | Learn Excel

Get FREE Advanced Excel Exercises with Solutions!
Afrina Nafisa
Afrina Nafisa

Afrina Nafisa Alam, BSc, Industrial and Production Engineering from Ahsanullah University of Science and Technology. She has been working with the Exceldemy project for over 6 months and is currently a web content developer here. She has published over 18 articles and reviewed several during this period. She is keen to learn different features and deliver the knowledge in her current project. She is interested in learning different features of Microsoft Office, especially Excel, Power Query, Data Analysis,... Read Full Bio

We will be happy to hear your thoughts

Leave a reply

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo