I have a file that has several tabs that have pivot tables that are based on one data tab. I am able to write the data to the data tab without issue, but I can't figure out how to get all of the tabs with pivot tables to refresh.
If this can be accomplished with openpyxl that would be ideal.
Note: Once you copy and paste the code, you have to save the workbook as Macro-Enabled Workbook. We can refresh the pivot table while opening the workbook. Right-Click on any of the pivot table and select the Pivot Table in the Excel option. Click on this option. Go to Data and check Refresh Data when opening the file.
Pivot Tables ¶ openpyxl provides read-support for pivot tables so that they will be preserved in existing files. The specification for pivot tables, while extensive, is not very clear and it is not intended that client code should be able to create pivot tables.
Firts, mark the pivottables for that updating when open file excel, for example: right click on pivot table, then, "Options of Pivot table", then, section "Data", then, mark checkbox "Update when on open file" Second, create one macro for that update all sheets with pivot table, for example:
To make it more efficient and auto-refresh the Pivot Table whenever there is a change in the data source, you can use a simple one-line VBA macro code. Decoding the Code: This is a change event which gets triggered whenever there is a change in the sheet that contains the source data.
I have similar problem but i thinking that this is thing very particularity of Excel, then, i have two solutions:
Firts, mark the pivottables for that updating when open file excel, for example: right click on pivot table, then, "Options of Pivot table", then, section "Data", then, mark checkbox "Update when on open file"
Second, create one macro for that update all sheets with pivot table, for example:
Dim Hoja As Worksheet
Dim TD As PivotTable
'
'read each sheet of file
For Each Hoja In ActiveWorkbook.Sheets
'read each pivot table of each sheet
For Each TD In Hoja.PivotTables
'update pivot table
TD.RefreshTable
Next TD
Next Hoja
If the data source range is always the same, you can set each pivot table as "refresh when open". To do that, just go to the pivot table tab, click on the pivot table, under "Analyze" - > Options -> Options -> Data -> select "Refresh data when opening the file".
If the data source range is dynamic, you can set a named range, and in the pivot table tab, Change Data Source to the named range. And again set "refresh when open".
So the above is achieved without using any python package, alternatively you can use openpyxl to refresh. However make sure that you're using the 2.5 release or above, because otherwise the pivot table format will be lost.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With