Excel VBA:在特定的目的地创build数据透视表没有错误?

我一直在广泛研究通过vba创build数据透视表,并面临一些复杂的,我无法find解决scheme。 我正在试图在工作表“Pivot”的第4列中创build一个数据透视表。 当我尝试运行我的代码时,我得到:

“运行时错误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 

您正在寻找类似下面的代码(代码注释中的解释):

 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