Pivot Fields in Excel VBA (Visual Basic for Applications) code example

Pivot Fields in Excel VBA (Visual Basic for Applications) code example

PivotField

Is an object of PivotTable in a Excel sheet. In this article we will see how you can iterate all the pivot fields of a Pivot Table in Excel. Consider following PivotTable source where we make a selection and from selection we will build Pivot Table reference to iterate all Pivot Fields.

Source example

Code example

Public Sub PivotFielldExample()
    'Declare variable for pivot field
    Dim oPivotField As PivotField
    
    'Declare pivot table object
    Dim oPivotTable As PivotTable
    
    'Bind pivot reference
    Set oPivotTable = Selection.PivotCell.PivotTable
    
    'Print each pivot field name
    For Each oPivotField In oPivotTable.PivotFields
        'Print each fields' name
        Debug.Print oPivotField.Name
    Next oPivotField
    
    'Memory cleanup
    Set oPivotField = Nothing
    Set oPivotTable = Nothing
End Sub

Output

Products
Usage
Frequency

Next >> Understand Pivot Table in Excel

Leave a Reply

Your email address will not be published. Required fields are marked *