如何在VBA中创build数据透视表

我试图创build一个数据透视表,但得到Invalid Procedure Call or Argument

 ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="rng", Version:=xlPivotTableVersion14).CreatePivotTable TableDestination:="rngB", TableName:="pvtReportA_B", DefaultVersion:=xlPivotTableVersion14 
  • rng (来源)是由大约20列和几千行组成的范围。
  • rngB (目标)是不同工作表中的单个单元格

任何人都可以build议我去哪里错了?

编辑:

我的错,我应该使用rngData而不是rng作为Source。

  Set rng = wsA.Range("C14") Set rngData = Range(rng, rng.End(xlToRight)) Set rngData = Range(rng, rng.End(xlDown)) Set rngB = wsB.Range("C8") ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rngData, Version:=xlPivotTableVersion14).CreatePivotTable TableDestination:=rngB, TableName:="pvtReportA_B", DefaultVersion:=xlPivotTableVersion14 

这带来了数据透视表框架就好了。

在这个例子中,我使用了错误的范围对象,这导致了Excel的出现。

 Set rng = wsA.Range("C14") Set rngData = Range(rng, rng.End(xlToRight)) Set rngData = Range(rng, rng.End(xlDown)) Set rngB = wsB.Range("C8") ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rngData, Version:=xlPivotTableVersion14).CreatePivotTable TableDestination:=rngB, TableName:="pvtReportA_B", DefaultVersion:=xlPivotTableVersion14 

要使用VBA代码在Excel 2010中创build数据透视表,您可以使用和调整此模板:

 Sub newPVT() Dim PTCache As PivotCache Dim PT As PivotTable 'Create the Cache Set PTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _ SourceData:=Range("Dynamic_Field_Summary")) 'Select the destination sheet Sheets("Field Summary").Select 'Create the Pivot table Set PT = ActiveSheet.PivotTables.Add(PivotCache:=PTCache, _ TableDestination:=Range("P1"), TableName:="Pivot1") ActiveWorkbook.ShowPivotTableFieldList = True 'Adding fields With PT With .PivotFields("Enterprise") .Orientation = xlColumnField .Position = 1 End With With .PivotFields("Field") .Orientation = xlRowField .Position = 1 End With With .PivotFields("Planted Acres") .Orientation = xlDataField .Position = 1 .Caption = " Planted Acres" .Function = xlSum End With With .PivotFields("Harvested Acres") .Orientation = xlDataField .Position = 2 .Caption = " Harvested Acres" .Function = xlSum End With With .PivotFields("lbs") .Orientation = xlDataField .Position = 3 .Caption = " lbs" .Function = xlSum End With 'Adjusting some settings .RowGrand = False .DisplayFieldCaptions = False .HasAutoFormat = False 'Improving the layout .TableStyle2 = "PivotStyleMedium9" .ShowTableStyleRowStripes = True .ShowTableStyleColumnStripes = True End With With ActiveSheet 'Adjusting columns width .Columns("P:V").ColumnWidth = 16 .Range("Q2:V2").HorizontalAlignment = xlCenter End With ActiveWorkbook.ShowPivotTableFieldList = False End Sub 

我在这里find了

在这个页面中,您还可以细化代码的每个部分的含义,例如在这里解释。 我认为这也是一个很好的代码,可以开始为Excel 2007或其他版本创buildvbamacros。