[英]How to update pivot data without clearing PivotTable Fields on Excel VBA?
My current code seems to be updating the source data range, but it is clearing the fields and filters.我当前的代码似乎正在更新源数据范围,但它正在清除字段和过滤器。 Is there any way to avoid that?
有什么办法可以避免吗?
sub update_pivot()
'change data range for pivot
Dim EndRow As Integer
Dim DataRange As Range
Dim NewRange As String
Dim Data_Sheet As Worksheet
Dim Pivot_Sheet As Worksheet
Set Data_Sheet = Workbooks(myfile).Worksheets("Consolidation")
Set Pivot_Sheet = Workbooks(myfile).Worksheets("Consolidation Pivot")
' find the last row in my data sheet
Data_Sheet.Select
EndRow = Cells(Rows.Count, "A").End(xlUp).Row
Set DataRange = Data_Sheet.Range("$A$1:$I" & EndRow)
NewRange = Data_Sheet.Name & "!" & DataRange.Address(ReferenceStyle:=xlR1C1)
Pivot_Sheet.Select
Pivot_Sheet.PivotTables("PivotTable6"). _
ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:=NewRange)
' Ensure Pivot Table is Refreshed
Pivot_Sheet.PivotTables("PivotTable6").RefreshTable
End Sub
From my experience, it's necessary to add the preferred fields and filters.根据我的经验,有必要添加首选字段和过滤器。 I believe the settings is stored within the .PivotCache, where changing cache will not have any fields or filters predetermined.
我相信设置存储在 .PivotCache 中,其中更改缓存不会预先确定任何字段或过滤器。
My solution would be to end the macro off with:我的解决方案是结束宏:
With Pivot_Sheet("PivotTable6")
.AddDataField .PivotFields("VariableName1")
.AddRowFields:=Array("VariableName2")
.RefreshTable
End with
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.