2017-07-17 86 views
0

我一直在廣泛研究通過vba創建數據透視表,並面臨一些複雜的問題,我無法找到解決方案。我正在試圖在「Pivot」表的第4列中創建一個數據透視表。當我嘗試運行我的代碼時,得到:Excel VBA:在特定目的地創建數據透視表,沒有錯誤?

「運行時錯誤1004:Worksheet類的PivotTableWizard方法失敗。」

任何人都可以幫忙嗎?我對vba仍然很陌生。 這裏是我的代碼,我一直在第二行收到錯誤:

Sub PivotTable() 
ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=Sheets("Information").UsedRange).CreatePivotTable TableDestination:="Pivot!R1C4", TableName:="PivotTable", DefaultVersion:=xlPivotTableVersion10 
ActiveSheet.PivotTableWizard TableDestination:=ActiveSheet.Cells(1, 1) 
With ActiveSheet.PivotTables("PivotTable").PivotFields("PN") 
    .Orientation = xlRowField 
.Position = 1 
End With 
With ActiveSheet.PivotTables("PivotTable").PivotFields("Commit") 
.Orientation = xlColumnField 
.Position = 1 
End With 
ActiveSheet.PivotTables("PivotTable").AddDataField ActiveSheet.PivotTables("PivotTable").PivotFields("Qty"), "Sum", xlSum 
End Sub 
+1

什麼的那點當你已經在第一行中指定了在哪裏創建它時? – Rory

+1

正如@Rory提到的......看起來你已經創建了數據透視表,標題爲'PivotTable'。註釋掉第二行,然後逐步完成。看看你打到第三線時會發生什麼。只要你的第一行用你想要的數據創建PT,它應該繼續。我猜你是通過使用「Record Macro」獲得的,這是一個很好的開始。嘗試錄製宏而不使用嚮導。它可以幫助您瞭解如何嚴格使用VBA創建PT。 – Busse

回答

1

您正在尋找的東西像下面的代碼(代碼註釋中說明):

Option Explicit 

Sub AutoPivotTable() 

Dim Sht As Worksheet 
Dim PvtSht As Worksheet 
Dim SrcData As Range 
Dim PvtCache As PivotCache 
Dim PvtTbl As PivotTable 

'-- Determine the data range you want to pivot -- 
' Set the Worksheet object 
Set Sht = ThisWorkbook.Worksheets("Information") 
Set SrcData = Sht.UsedRange '1:Z10000").Address(False, False, xlR1C1, xlExternal) 

' Set the Pivot Cache from Source Data 
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData.Address(False, False, xlA1, xlExternal)) 

' Set the Worksheet object where the Pivot Table will be loated 
Set PvtSht = ThisWorkbook.Worksheets("Pivot") 

On Error Resume Next 
'Set the pivot table object 
Set PvtTbl = PvtSht.PivotTables("PivotTable") ' check if "PivotTable" Pivot Table already created (in past runs of this Macro) 
On Error GoTo 0 
If PvtTbl Is Nothing Then '<-- Pivot Table not created >> create it 
    ' create a new Pivot Table in "Pivot" sheet 
    Set PvtTbl = PvtSht.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=PvtSht.Range("D1"), TableName:="PivotTable") 
    With PvtTbl 
     With .PivotFields("PN") 
      .Orientation = xlRowField 
      .Position = 1 
     End With 
     With .PivotFields("Commit") 
      .Orientation = xlColumnField 
      .Position = 1 
     End With 
     .AddDataField .PivotFields("Qty"), "Sum of Qty", xlSum 
    End With 

Else ' just refresh the Pivot cache with the updated Range 
    PvtTbl.ChangePivotCache PvtCache 
    PvtTbl.RefreshTable 
End If 

End Sub