2017-02-17 59 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