使用VBA更改数据透视表数据源时出错

时间:2017-08-25 04:59:53

标签: excel vba excel-vba

我正在使用vba更改excel中数据透视表的数据源。我在下面有这个代码,但它在此行返回了类型不匹配错误:     设置pvtcache = ThisWorkbook.PivotCaches.Create(SourceType:= xlDatabase,     SourceData:= DataRange)

这是我在google和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!"

1 个答案:

答案 0 :(得分:0)

只有这些行才能成功创建和更改Pivot Cache ....

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