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

我试图创build一个数据透视表,但我得到了我的最后一行代码错误。

Dim WSD As Worksheet Dim WSD2 As Worksheet Dim PTCache As PivotCache Dim PT As PivotTable Dim PRange As Range Dim FinalRow As Long Dim FinalCol As Long Set WSD = Worksheets("SKU Sum") Set WSD2 = Worksheets("Finelines") ' Select the data for pivot table FinalRow = WSD.Cells(Rows.Count, 1).End(xlUp).Row FinalCol = WSD.Cells(1, Columns.Count).End(xlToLeft).Column Set PRange = WSD.Cells(1, 1).Resize(FinalRow, FinalCol) Set PTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange) Set PT = WSD.PivotTables.Add(PivotCache:=PTCache, TableDestination:=WSD2.Range(A1), TableName:="Pivotab") 

任何帮助将不胜感激。

谢谢,

G

replace您当前的PivtoCache行:

 Set PTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange) 

附:

 Set PTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange.Address(False, False, xlA1, xlExternal)) 

另外 ,由于您正在设置数据透视表WSD2.Range(A1) ,括号内的string需要具有" 。”,所以还要将其修改为WSD2.Range("A1")

用最后一行replace

 Set PT = PTCache.CreatePivotTable(TableDestination:=WSD2.Range("A1"), TableName:="Pivotab")