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

我有下面的代码,但Set PT_Cache行引发types不匹配错误。

有人知道为什么

 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 

试试下面的代码,我已经添加了2个选项来设置PivotCache ,尝试一个并评论其他(或反之亦然),看看哪一个适合你(当我用我的虚拟数据testing它时,都工作)

 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