使用VBA错误创建数据透视表

时间:2017-04-12 18:27:16

标签: excel vba

我在下面有此代码,但Set PT_Cache行引发类型不匹配错误。

任何人都知道为什么?

Sub Create_Pivot_Table()
Dim wsData As Worksheet, wsPT As Worksheet
Dim PT_Cache As PivotCache
Dim PT As PivotTable
Dim LastRow As Long

With ThisWorkbook
Set wsData = .Worksheets("Data")
Set wsPT = .Worksheets("Pivot Table")
End With

LastRow = wsData.Cells(Rows.Count, 1).End(xlUp).Row

Set PT_Cache = ThisWorkbook.PivotCaches.Create(xlDatabase, wsData.Range("A1:O" & LastRow))

Set PT = PT_Cache.CreatePivotTable(wsPT.Range("D5"), "Pivot_Table_Test")

Set PT = Nothing
Set PT_Cache = Nothing
Set wsData = Nothing
Set wsPT = Nothing
Exit Sub

End Sub

1 个答案:

答案 0 :(得分:1)

尝试以下代码,我添加了2个选项来设置PivotCache,尝试一个并评论另一个(或反之亦然),看看哪个适合你(两个都在我测试时起作用)用我的虚拟数据)

<强>代码

Option Explicit

Sub Create_Pivot_Table()

Dim wsData As Worksheet, wsPT As Worksheet
Dim PT_Cache    As PivotCache
Dim PT          As PivotTable
Dim PRng        As Range
Dim LastRow     As Long

With ThisWorkbook
    Set wsData = .Worksheets("Data")
    Set wsPT = .Worksheets("Pivot Table")
End With

LastRow = wsData.Cells(wsData.Rows.Count, 1).End(xlUp).Row
MsgBox LastRow ' <-- confirm value

Set PRng = wsData.Range("A1:O" & LastRow)

' option 1: Set the Pivot Cache
Set PT_Cache = ThisWorkbook.PivotCaches.Create(xlDatabase, PRng)

' option 2: Set the Pivot Cache
Set PT_Cache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRng.Address(True, True, xlR1C1, True))

' set the Pivot Table
Set PT = wsPT.PivotTables.Add(PivotCache:=PT_Cache, TableDestination:=wsPT.Range("D5"), TableName:="Pivot_Table_Test")

Set PT = Nothing
Set PT_Cache = Nothing
Set wsData = Nothing
Set wsPT = Nothing
Exit Sub

End Sub