views:

1353

answers:

2

Here is some sample VBA code:

Sub Macro1()
    Dim pt As PivotTable
    Set pt = ActiveSheet.PivotTables("SomePivotTable")
    'Set colOfFields = pt.PivotFields  
End Sub

The third line is incomplete/broken. What is the correct way to get access to collection of all the fields in a PivotTable? I need to be able to loop over them. Actual coding is being done in C# VSTO Project.

+2  A: 

This works for me (Excel 2003 [11.8146.8202] SP2):

Sub Macro1()
    Dim pt As PivotTable
    Dim col As PivotFields
    Dim c As PivotField

    ' Name of the pivot table comes from right clicking on the pivot table,
    ' Table Options..., Name field.
    Set pt = ActiveSheet.PivotTables("PivotTable1")
    Set col = pt.PivotFields
    For Each c In col
        Debug.Print c.Name
    Next
End Sub
Patrick Cuff
Hmmm. Let me go test this over in VSTO-land. What is datatype is col?
tyndall
Edited to explicitly declare vars with datatypes.
Patrick Cuff
A: 

Ok. Found some C#-flavored code ideas from:
http://blogs.msdn.com/andreww/archive/2008/07/25/creating-a-pivottable-programmatically.aspx

// pvtTable is an Excel.PivotTable set earlier in the code
Excel.PivotFields pflds =     
    (Excel.PivotFields)pvtTable.PivotFields(System.Type.Missing);
    foreach (Excel.PivotField pf in pflds)
    {
      //some code here
    }

The trick is passing in the System.Type.Missing to get the "collection" of fields back.

tyndall