2017-04-12 150 views
1

我在下面有此代碼,但Set PT_Cache行正在引發類型不匹配錯誤。使用VBA錯誤創建數據透視表

任何人都知道爲什麼?

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 
+0

是什麼'LastRow'的價值? 'LastRow'也應該是'LastRow = wsData.Cells(wsData.Rows.Count,1).End(xlUp).Row' –

+0

我修正了這部分,這不是問題,「set PT_Cache」仍然出錯... –

+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