2011-02-28 122 views
2

我有一个Excel工作表,其中包含三个数据透视表名称为PivotTable1 ... PivotTable3和活动字段名称分别为国家,语言和打印机的三个数据透视表。我需要的是将每个数据透视表中的所有数据都存储到每个字符串或字符串数​​组中。任何帮助将非常感谢。从Vba中的数据透视表检索数据

+0

任何帮助,请?????? – 1355 2011-02-28 11:55:45

回答

2

快速&肮脏的一个让你走;一个线性字符串中的数据透视表的所有单元格,由“;”分隔。这应该给予使用哪些方法和属性足够的启发。注意:Tmp不能保留无限大的数据透视表,如果它们变得非常大,请考虑将Tmp写入文件。

Sub PTTest() 
Dim SH As Worksheet ' the current worksheet from the colection of workbooks 
Dim PT As PivotTable ' the current pivot table from the current worksheet 
Dim PTC As Range ' the cell range of the current pivot table 
Dim Tmp As String ' the buffer for concatenated cell values 

    Tmp = "" 
    ' process all sheets, as Pivot table objects are contained by sheets 
    For Each SH In ActiveWorkbook.Worksheets 

     For Each PT In SH.PivotTables 

      For Each PTC In PT.TableRange1.Cells 
       ' all cells in one buffer, seperated by ";" 
       ' if you want to include page header cells, use 
       ' "PT.TableRange2.Cells" instead 
       Tmp = Tmp & PTC & ";" 
      Next PTC 

      ' *** do something *** with the buffer 
      ' ok very simple we print it into the debugger's Immediate window 
      Debug.Print Tmp 

      ' empty buffer for next pivot table 
      Tmp = "" 

     Next PT 
    Next SH 
End Sub 

希望帮助....好运气拾音

+0

非常感谢您的帮助。它工作得很好。但我不需要浏览工作簿中的所有工作表。只有一个指定的。那么,必须做出什么改变? – 1355 2011-03-01 04:28:11

+1

现在我在内循环之后的外循环中使用'Exit For'命令。所以我只能通过第一张工作表。这是我的需要也.. – 1355 2011-03-01 04:52:41

+1

为一个特定工作表中的透视表,您可以删除外部For Each SH并重写内部循环为“For Each PT In Worksheets(”Sheet1“)。PivotTables” – MikeD 2011-03-01 16:24:55