简体   繁体   English

如何在不清除 Excel VBA 上的数据透视表字段的情况下更新数据透视表?

[英]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.

相关问题 Excel VBA或VSTO-如何在数据透视表上的字段之间循环? - Excel VBA or VSTO - How do you loop over Fields on a PivotTable? 使用 VBA 更新 Excel 数据透视表数据源后,错误:数据透视表在没有基础数据的情况下保存 - After Updating Excel PivotTable DataSource w/ VBA, ERROR: The PivotTable report was saved without the underlying data Ghost数据透视字段保留在数据透视表中,但不在数据中 - Ghost pivot fields remain in PivotTable, but are not in data Excel 数据透视表更新 - 不创建数据透视缓存 (VBA) - Excel PivotTable Update - Not Creating PivotCache (VBA) 将数据从数据透视表中提取到VBA中的数组(Excel) - Fetching Data from PivotTable into Array in VBA (Excel) 如何使用 vba 从具有多个数据字段的 excel 数据透视表中删除小计 - How to remove subtotal from a excel pivot-table with mutiple data fields useing vba Excel VBA:更新数据透视源数据 - Excel VBA: Update Pivot Sourcedata 更新Excel数据透视表字段 - Update Excel Pivot Table Fields 如何在不使用VBA的情况下将矩阵转换为4列表(数据-数据透视表和数据透视图报表) - How to convert matrix to 4-column table without using VBA (Data - PivotTable and PivotChart Report) 用户窗体列表框中的数据透视表字段-Excel VBA - Pivot table fields in userform listbox - Excel vba
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM