2017-08-25 510 views
0

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

这里是我的剧本,我也得到了各在谷歌和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!" 
+0

看http://www.contextures.com/xlPivot11.html#newcache – teylyn

回答

0

只有这些线路将成功地创建和更改数据透视缓存....

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