Can't refresh using VBA a pivot table attached to a table - vba

I converted a range of cells to a table, called Table1. Then I inserted a pivot table and then I inserted this:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim pt As PivotTable
Set pt = ActiveSheet.PivotTables("PivotTable1")
pt.PivotCache.Refresh
End Sub
I'm getting an error 1004. The DataSource is 'Table1'

I moved the code from Worksheet_Change event, to a Sub that you can call from a button, otherwise it will fire everytime someone modifies or touches anywhere in this Sheet.
I defined the "PivotSrc_Range" that is Set-up to "Table1", and is set-up to the PivotCache, this way, everytime someone modifies or adds a data to "Table1", the PivotCache changes, and the PivotTable will be modified once you call the Sub below:
Sub UpdatePivot()
Dim sht1 As Worksheet
Dim pt As PivotTable
Dim PvtCache As PivotCache
Dim PivotSrc_Range As Range
' modify to your sheet name (I prefer not to use ActiveSheet)
Set sht1 = ThisWorkbook.Sheets("Sheet1")
' modify to your Table's name
Set PivotSrc_Range = sht1.Range("Table1")
' set the Pivot Cache
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PivotSrc_Range, Version:=xlPivotTableVersion14)
' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set pt = sht1.PivotTables("PivotTable1")
On Error GoTo 0
If pt Is Nothing Then
' create a new Pivot Table in "Sheet1" sheet, start from Cell I1
Set pt = sht1.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=sht1.Range("I1"), TableName:="PivotTable1")
Else
' just refresh the Pivot cache with the updated Range (data in Table1)
pt.ChangePivotCache PvtCache
pt.RefreshTable
End If
End Sub

Related

Excel pivot table filter links to cells

I'm a novice VBA user and already posted on this issue, but had to re-do some tables in my workbook and the initial question ended up being inaccurate, hence trying again.
I have modified a code found online to work with my workbook which:
links a cell to a my pivot table filter;
updates the filter and refreshes pivot table once the cell has been updated or activated;
Works great. The challange is that there are 2 pivot tables on the same worksheet and I'd need to filter 2 tables at the same time. Also the filter data is different, so the filter should be linked to different cells, although they do change at the same time.
The code I was using is below. Now there is PivotTable1 and PivotTable2; entry to cell H6 is linked to the 1st table and H7 to the other table. Got a little overwhelmed at this point, but this should be possible within the same code, right?
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'This line stops the worksheet updating on every change, it only updates when cell
'H6 or H7 is touched
If Intersect(Target, Range("H6:H7")) Is Nothing Then Exit Sub
'Set the Variables to be used
Dim pt As PivotTable
Dim Field As PivotField
Dim NewCat As String
'Here you amend to suit your data
Set pt = Worksheets("Sheet1").PivotTables("PivotTable1")
Set Field = pt.PivotFields("Category")
NewCat = Worksheets("Sheet1").Range("H6").Value
'This updates and refreshes the PIVOT table
With pt
Field.ClearAllFilters
Field.CurrentPage = NewCat
pt.RefreshTable
End With
End Sub
Your code can be amended as follows...
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'This line stops the worksheet updating on every change, it only updates when cell
'H6 or H7 is touched
If Intersect(Target, Range("H6:H7")) Is Nothing Then Exit Sub
'Set the Variables to be used
Dim pt As PivotTable
Dim Field As PivotField
Dim vPivotTableNames As Variant
Dim vNewCats As Variant
Dim i As Long
'Assign the pivottable names to a variable
vPivotTableNames = Array("PivotTable1", "PivotTable2")
'Assign the new categories to a variable
vNewCats = Range("H6:H7").Value
'Update the pivotables
For i = LBound(vPivotTableNames) To UBound(vPivotTableNames)
Set pt = Worksheets("Sheet1").PivotTables(vPivotTableNames(i))
Set Field = pt.PivotFields("Category")
With Field
.ClearAllFilters
.CurrentPage = vNewCats(i + 1, 1)
End With
pt.RefreshTable
Next i
End Sub
Although, the For/Next loop can be re-written as follows...
'Update the pivotables
For i = LBound(vPivotTableNames) To UBound(vPivotTableNames)
With Worksheets("Sheet1").PivotTables(vPivotTableNames(i))
With .PivotFields("Category")
.ClearAllFilters
.CurrentPage = vNewCats(i + 1, 1)
End With
.RefreshTable
End With
Next i

VBA Auto Update Pivot Table

I have a pivot table in sheet 2. The pivot table filter will automatically change each time I change the value in sheet 1 cell D1. However, the table only refreshes when I go back to sheet 2 and click anywhere on screen. How can I get this to change automatically?
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Set the Variables to be used
Dim pt As PivotTable
Dim Field As PivotField
Dim NewCat As String
'Set worksheet and cell
Set pt = Worksheets("Sheet2").PivotTables("PivotTable1")
Set Field = pt.PivotFields("Sum1")
NewCat = Worksheets("Sheet1").Range("D1").Value
'Update and refresh
With pt
Field.ClearAllFilters
Field.CurrentPage = NewCat
pt.Update
End With
End Sub
Note: I have also tried pt.Refresh and pt.RefreshTable

Run-Time Error 1004 - Macro to update pivot table

I am trying to update a pivot table using a macro since data is added to the bottom of the table each month (Update to include data to last row).
Option Explicit
Sub Pivot()
Dim shConD As Worksheet
Dim shPvtTbl As Worksheet
Dim lr As Long
Dim rng As Range
Set shConD = ActiveWorkbook.Sheets("Consolidated_Data")
Set shPvtTbl = ActiveWorkbook.Sheets("PivotTables")
lr = shConD.Range("A" & Rows.Count).End(xlUp).Row
Set rng = shConD.Range("A1:F" & lr)
With shPvtTbl.PivotTables(3).PivotCache
.SourceData = rng.Address(True, True, xlR1C1, True) 'Error appears here
.Refresh
End With
End Sub
On the .SourceData line, I am getting run-time error 1004, Application-defined or object-defined error. Followed logic from this thread and the continued chat . Thanks in advance guys.
If you're using Excel 2007 or later, then the simplest way to accomplish this is to make sure your PivotTable source data is an Excel Table (aka ListObject), and use the Table name in the Change PivotTable Data Source as shown below.
Thanks to the magic of Tables, from that point on, whenever you add new data to your Table, it will expand automatically. And whenever you refresh the PivotTable it will always pick up that new data automatically. There will be no need to change the PivotTable data source ever again.
Try the code below (explanation inside the code's comments) :
Option Explicit
Sub Pivot()
Dim shConD As Worksheet
Dim shPvtTbl As Worksheet
Dim lr As Long
Dim rng As Range
' Added PivotTable variables
Dim PvtTbl As PivotTable
Dim PvtCache As PivotCache
Set shConD = ActiveWorkbook.Sheets("Consolidated_Data")
Set shPvtTbl = ActiveWorkbook.Sheets("PivotTables")
lr = shConD.Range("A" & shConD.Rows.Count).End(xlUp).Row
Set rng = shConD.Range("A1:F" & lr)
' set/update the PivotCache (with latest rng modifications
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rng.Address(False, False, xlA1, xlExternal))
' for DEBUG Only
Debug.Print PvtCache.SourceData
' set the PivotTable object
Set PvtTbl = shPvtTbl.PivotTables(3)
' for DEBUG Only
Debug.Print PvtTbl.Name
' refresh the PivotTable with the updated PivotCache
PvtTbl.ChangePivotCache PvtCache
PvtTbl.RefreshTable
End Sub

Refreshing a Pivot table with VBA

I am trying to refresh automatically a pivot table with Powershell script that calls a vba code in an excel.
my powershell code is th following.
$excel = new-object -comobject excel.application
$workbook = $excel.workbooks.open("$para_temp\RapportPalettes.xlsm")
$worksheet = $workbook.worksheets.item("source")
$excel.Run('Import')
$worksheet = $workbook.worksheets.item("TCD")
$excel.Run('MAJ')
the first macro "Import" works just fine. But the second "MAJ" that refreshes the Pivot table with the new data in source doesn't
I tried first this macro in maj :
Sub maj()
Dim pt As PivotTable
Set pt = ActiveSheet.PivotTables("TCD")
pt.RefreshTable
End Sub
I don't get any error but my pivote table isn't refreshed and i have to do it manually.
Then I tried this one to change the pivot table's source of data :
Sub MAJ()
Dim sht As Worksheet
Dim SrcData As String
Dim pvtCache As PivotCache
'Determine the data range you want to pivot
Set sht = ThisWorkbook.Worksheets("Source")
SrcData = sht.Name & "!" & Range("A1:Z10000").Address(ReferenceStyle:=xlR1C1)
'Create New Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
'Change which Pivot Cache the Pivot Table is referring to
Worksheets("TCD").Activate
ActiveSheet.PivotTables("TCD").ChangePivotCach (pvtCache)
End Sub
but i have an 438 error in the VBA : object doesn't support this property or method for this line
ActiveSheet.PivotTables("TCD").ChangePivotCach (pvtCache)
could you please Help ?
EDIT :
as you can see, I do have a worksheet and a pivot table named TCD.
EDIT :
In fact the macro is working, i tested it by creating a button that calls it.
It doesn't work when i call it with powershell
Try the code below to refresh the PivotTable named "TCD" in worksheet "TCD" with the updated PivotCache.
Code
Option Explicit
Sub MAJ()
Dim sht As Worksheet
Dim SrcData As String
Dim pvtCache As PivotCache
Dim pvtTbl As PivotTable
'Determine the data range you want to pivot
Set sht = ThisWorkbook.Worksheets("Source")
SrcData = sht.Range("A1:Z10000").Address(False, False, xlA1, xlExternal)
'Create New Pivot Cache from Source Data
Set pvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData)
'Set the pivot table object
Set pvtTbl = ThisWorkbook.Worksheets("TCD").PivotTables("TCD")
With pvtTbl
.ChangePivotCache pvtCache 'Change which Pivot Cache the Pivot Table is referring to
.RefreshTable ' refresh the Pivot Table
End With
End Sub
I finally found the problem which was a bit stupid. In fact I was refreshing the Pivot Table but I wasn't saving the changes.
This is the macro I finally used and I used the same powershell script:
Sub Test()
Application.DisplayAlerts = False
Dim TCD As PivotTable
For Each TCD In Worksheets("TCD").PivotTables
TCD.RefreshTable
Next
ThisWorkbook.Save
Application.DisplayAlerts = False
End Sub
Thanks for all

Excel VBA/button to refresh two or more pivots simultaneously

In another post I was provided with the following VBA code to attach to a "Refresh" button to refresh Pivot data:
Option Explicit
Sub Button5_Click()
Dim PvtTbl As PivotTable
Dim PvtCache As PivotCache
Dim PvtDataRng As Range
' Set/Update Pivot Data Range
Set PvtDataRng = Worksheets("PivotDataSheet").Range("A1:E100") ' <-- just an example
' Create/Update Pivot Cache
Set PvtCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, PvtDataRng)
' Set the Pivot Table (already created, otherwise need to create it)
Set PvtTbl = Worksheets("DD").PivotTables("test")
' refresh the Pivot Table with the latest Pivot Cache
With PvtTbl
.ChangePivotCache PvtCache
.RefreshTable
End With
End Sub
How can this code be modified to simultaneously refresh a 2nd pivot in the same worksheet? Lets call this 2nd pivot "test2" and it is also in the DD worksheet.
Thanks,
Kevbo
In case you have only these 2 PivotTable in "DD" worksheet, and you want to update these 2 based on the same PivotCache, then replace the following For loop :
With PvtTbl
.ChangePivotCache PvtCache
.RefreshTable
End With
With the following For loop:
' refresh all Pivot Tables in "DD" worksheet
For Each PvtTbl In Worksheets("DD").PivotTables
With PvtTbl
.ChangePivotCache PvtCache
.RefreshTable
End With
Next PvtTbl
Edit 1: Set the PivotCache inside the For loop, and clear it at the end. use the loop below, and remove the Set PvtCache line from it's previous place.
' refresh all Pivot Tables in "DD" worksheet
For Each PvtTbl In Worksheets("DD").PivotTables
' Create/Update Pivot Cache
Set PvtCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, PvtDataRng)
With PvtTbl
.ChangePivotCache PvtCache
.RefreshTable
End With
Set PvtCache = Nothing ' <-- clear the Pivot Cache
Next PvtTbl
I haven't tested this myself but you could try and tell me if it works. It seems like it may work for you
Function refreshPTcontent()
Dim ws As Worksheet
Dim pt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem
On Error Resume Next
For Each ws In ActiveWorkbook.Worksheets
For Each pt In ws.PivotTables
pt.RefreshTable
Next pt
Next ws
End Function