Vba pivot tables in vba in Excel
In the previous chapter, the fundamentals of the pivot tables were discussed.
In this chapter, we will see, how to automate it using visual basic editor.
In VBA, the "PivotTable" object is used to work with pivot tables
The "PivotTable" object is a member of PivotTable Collections.
To access a pivot table in excel, the index number of the pivot table is used.
Let us consider the pivot table of previous chapter and explore some of the concepts of it in VBA.
1.AddDataField
This method adds a new data field to the pivot table report.
The data field added should be a member of the pivot table.
The following example illustrates this:
- Sub pivotaddfields()
- With Sheets("Q52").PivotTables(1)
- .AddDataField Sheets("Q52").PivotTables( _
- 1).PivotFields("Women"), "Women Population"
- End With
- End Sub
The above example adds "Women" column in the pivot table report.
2.ClearAllFilters
This method clears all filters currently applied to the pivot table.
This includes both PivotFilters collection and manual filtering applied to the pivot table.
The following code demonstrates this:
- Sub pivotclrfilter()
- With Sheets("Q53").PivotTables(1).ClearAllFilters
- End With
- End Sub
3.ClearTable
The�ClearTable�method is used for clearing a PivotTable. Clearing PivotTables includes removing all the fields and
deleting all filtering and sorting applied to the PivotTables. This method resets the PivotTable to the state it had right after it was created,
before any fields were added to it.
The following code demonstrates this
- Sub clrpivot()
- With Sheets("Q53").PivotTables(1).ClearTable
- End With
- End Sub
4.RefreshTable
This method refreshes a pivot table with the source data.
Refreshing means, updating the pivot table with latest data of the source range.
The following example shows this:
- Sub pivotrfrsh()
- Sheets("Q53").PivotTables(1).RefreshTable
- End Sub
Note that, the result of the above snippet will be visible only there is any change in the source range.
The screenshot of code and pivot table is shown below: