Excel VBA 或 VSTO - 如何遍历数据透视表上的字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/341221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 10:05:23  来源:igfitidea点击:

Excel VBA or VSTO - How do you loop over Fields on a PivotTable?

excelvbaexcel-vbavstopivot-table

提问by BuddyJoe

Here is some sample VBA code:

这是一些示例 VBA 代码:

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.

第三行不完整/损坏。访问数据透视表中所有字段集合的正确方法是什么?我需要能够遍历它们。实际编码是在 C# VSTO 项目中完成的。

回答by Patrick Cuff

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

这对我有用(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

回答by BuddyJoe

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

好的。从以下位置找到了一些 C# 风格的代码想法: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.

诀窍是传入 System.Type.Missing 以获取字段的“集合”。