简体   繁体   中英

Error Changing Pivot Table Data Source using VBA

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!"

Only these lines will successfully create and change the Pivot Cache....

Set pvtcache = ThisWorkbook.PivotCaches.Create(xlDatabase, Data_sht.Name & "!" & Data_sht.Range("A1").CurrentRegion.Address)
Pivot_sht.PivotTables(1).ChangePivotCache pvtcache

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM