1

I have this code below, but the Set PT_Cache line is raising a Type mismatch error.

Anyone knows why?

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
6
  • what is the value of LastRow ? LastRow should also be LastRow = wsData.Cells(wsData.Rows.Count, 1).End(xlUp).Row Commented Apr 12, 2017 at 18:35
  • I fixed this part and this was not the problem, the "set PT_Cache" still got the error.... Commented Apr 12, 2017 at 18:37
  • have you read my answer and tested the code below ? Commented Apr 13, 2017 at 3:12
  • @ShaiRado Yes! I just tried! It works! But I'm keep running into problems as I adding more code, I'm able to create a empty pivot table with your code, after I added some values field, it tells me that I have error with the previous code.... Commented Apr 13, 2017 at 17:10
  • Then you should open a new post, with your modified code, and describe what you are trying to achieve. Commented Apr 13, 2017 at 17:12

1 Answer 1

1

Try the code below, I've added 2 options to set the PivotCache, try one and comment the other (or vise versa), see which one works for you (both worked when I tested it with my dummy data)

Code

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.