2017-02-17 58 views
3

我有一个数据透视表,用于在"part"上汇总"coverage"仅适用于接受的零件。从数据透视表提取数据vba

enter image description here

我想然后提取"sum of coverage"到另一片材。 我写了下面的宏:

Sub Pull_data() 
'Update the pivot table 
Sheets("Pivot").PivotTables("PivotTable2").PivotCache.Refresh 
'clear all filters 
Sheets("Pivot").PivotTables("PivotTable2").PivotFields("Accepted").ClearAllFilters 
'filters only accepted items 
Sheets("Pivot").PivotTables("PivotTable2").PivotFields("Accepted").CurrentPage = "YES" 
'get the last row of the pivot table 
Set PT = Sheets("Pivot").PivotTables("PivotTable2") 
With PT.TableRange1 
    lngLastRow = .rows(.rows.Count).Row 
End With 
For i = 4 To lngLastRow 
    'copy the coverage to destination sheet 
    NEWi = i + 10 
    Sheets("Destination").Range("G" & NEWi) = PivotTable.GetPivotData(data_field, Range("I" & i), “Coverage”) 
Next i 
End Sub 

我得到一个运行时错误“424”,对象上

Sheets("Destination").Range("G" & NEWi) = PivotTable.GetPivotData(data_field, Range("I" & i), “Coverage”) 

需要这将是写这条线的正确方法?

+0

您的数据透视表对象是'PT'而不是'PivotTable' – Rory

+0

替换“数据透视表'与'PT'仍然给出错误'运行时错误1004应用程序定义或对象定义的错误' –

+0

@ L.Dutch而不是'循环'尝试'TableRange2'(参见我的代码) –

回答

2

这应该是:

Sheets("Destination").Range("G" & i + 10).Value = _ 
    pT.GetPivotData("Sum of coverage", "Part", Range("I" & i).Value).Value 

因为pT.GetPivotData返回Range!

清理代码:

Sub Pull_data() 
    Dim pT As PivotTable 
    Set pT = Sheets("Pivot").PivotTables("PivotTable2") 

    With pT 
     '''Update the pivot table 
     .PivotCache.Refresh 
     '''clear all filters 
     .PivotFields("Accepted").ClearAllFilters 
     '''filters only accepted items 
     .PivotFields("Accepted").CurrentPage = "YES" 
     '''get the last row of the pivot table 
     With .TableRange1 
      lngLastRow = .Rows(.Rows.Count).Row 
      For i = .Cells(2, 1).Row To lngLastRow 
       Debug.Print "i=" & i & "|" & Sheets("Pivot").Range("I" & i).Value 
       '''copy the coverage to destination sheet 
       Sheets("Destination").Range("G" & i + 10).Value = _ 
        pT.GetPivotData("Sum of coverage", "Part", Sheets("Pivot").Range("I" & i).Value).Value 
      Next i 
     End With '.TableRange1 
    End With 'pT 
End Sub 
+0

这给出了“运行时错误438.对象不支持这个属性或方法 –

+0

@ L.Dutch:我的坏在那里有一个错字! ;) – R3uK

+0

再次出现错误438,也使用清理后的代码 –

2

你可以尝试从您的PivotTable它的过滤,以您的需求后,复制整列,与TableRange2,使用Resize到一列,然后CopyPasteSpecial xlValues目的地工作表。

如果下面的代码采用了错误的列,您还可以使用Offset(0,1)来获得正确的一个。

With PT 
    .TableRange2.Resize(.TableRange2.Rows.Count, 1).Copy 
    Worksheets("Destination").Range("G14").PasteSpecial xlValues '<-- start Pasting from Row 14 
End With 

注意:如果上面的代码将列在左边,试试下面的代码行:

.TableRange2.Resize(.TableRange2.Rows.Count, 1).Offset(, 1).Copy