如何在excel VBA中创建数据透视表?

时间:2017-08-02 19:16:28

标签: excel vba excel-vba

我正在尝试创建一个数据透视表,但我的最后一行代码出错了。

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")

非常感谢任何帮助。

谢谢,

2 个答案:

答案 0 :(得分:1)

替换最后一行
Set PT = PTCache.CreatePivotTable(TableDestination:=WSD2.Range("A1"), TableName:="Pivotab")

答案 1 :(得分:0)

替换当前的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)

,您在最后一行收到错误,因为您正在设置数据透视表"的位置,括号内的字符串需要{{1 }}。所以也要将其修改为WSD2.Range("A1")