I'm changing the data source of pivot table in excel using vba. I have this code below but it's returning a Type mismatch error at this line: Set pvtcache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=DataRange)
Here's my script which I also got from various solutions in google and stackoverflow.
Dim Data_sht As Worksheet
Dim Pivot_sht As Worksheet
Dim StartPoint As Range``
Dim DataRange As Range
Dim PivotName As String
Dim NewRange As String
Dim pvtcache As PivotCache
Set Data_sht = wb.Sheets("FINAL_DATA")
Set Pivot_sht = wb.Worksheets("Summary")
PivotName = "PivotTable1"
'Dynamically Retrieve Range Address of Data
Set StartPoint = Data_sht.Range("A1")
Set DataRange = Data_sht.Range(StartPoint,
StartPoint.SpecialCells(xlLastCell))
NewRange = Data_sht.Name & "!" & _
DataRange.Address(RowAbsolute:=True, ColumnAbsolute:=True,
ReferenceStyle:=xlR1C1, External:=True)
'Change Pivot Table Data Source Range Address
Set pvtcache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase,
SourceData:=DataRange)
With Pivot_sht
.PivotTables(PivotName).ChangePivotCache pvtcache
End With
'Refresh Pivot Table
Pivot_sht.PivotTables(PivotName).RefreshTable
'Message
MsgBox PivotName & "'s data source range has been successfully updated!"