Formula to reference an entire pivot table? - excel

I have a bunch of sheets with detailed data sets and pivot tables. On a summary sheet, I want to display just the pivot tables. (Of course, I'd rather stay DRY and not create a whole new set.) How can I reference the old pivot tables?
I can use VBA to do this if necessary.

This sub will keep the pivot tables 'live.' You could PasteValues over them if you don't want that.
Sub SummarizePivotTables()
Dim wb As Workbook, ws As Worksheet, ss As Worksheet, pt As PivotTable
Dim pasteRow As Long
Const rowsBetween As Long = 1
Set wb = ThisWorkbook
Set ss = wb.Worksheets("Summary")
pasteRow = 1 'first table row'
For Each ws In wb.Worksheets
For Each pt In ws.PivotTables
'change this to TableRange1 if you do not want the page field included'
With pt.TableRange2
.Copy ss.Range("A" & pasteRow)
pasteRow = pasteRow + .Rows.Count + rowsBetween
End With
Next pt
Next ws
End Sub

Pivot tables are named "Excel tables" in your workbook. So you should be able to do this without VB as I described in this answer.
tl;dr;
Data -> Get External Data -> Existing Connections
Goto "Tables" tab, select your table
Insert as "Table"

Related

Change automatically the range of the datasource of a pivot table of each worksheet

I want to change automatically the range of the sourcedata of each pivot table of each worksheet. I have the sheet 'DATA' which feeds every pivot table of the workbook. The point is that the range of the DATA sheet is variable. So when I change the DATA sheet I want to refresh all the pivot table adjusting also the rnew range of data.
I wrote the following script, but it is not working. I don't know why:
Sub Prueba_Rango_TD()
Dim ws As Worksheet
Dim LastRow As Integer
LastRow = Cells(Rows.Count, 3).End(xlUp).Row
For Each ws In ThisWorkbook.Worksheets
For Each tbl In ws.ListObjects
tbl.Resize tbl.Range.Resize("DATA!B8:O" & Ultima_fila)
Next tbl
Next ws
End Sub
Can you help me please?
Thank you!
The easy way you do this is by recording a Macro.
Then you will se what type of Objects being used and where the pointer of your first Pivot, something like this:
ActiveSheet.PivotTables("PivotTable1").ChangePivotCache
ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:=ThisWorkbook.Worksheets("DATA").UsedRange.Address,
Version:=xlPivotTableVersion12)
If all the other sheets points towards the same data Cashe you do it with the loop.
.PivotTables("PivotTable1").ChangePivotCache ("DATA!PivotTable1")
.PivotTables("PivotTable1").RefreshTable

Loop to filter Pivot Table based on values in another Sheet

My objective is to filter a pivot table using a range in another sheet.
My pivot is in Worksheets("Aging Report").
My reference data using which I want to filter is in Columns A2 and onward in Worksheets("Instructions").
The below code worked on a table which did not have pivot table.
I need to take value from A2 then filter on ("Client ID") and export in Excel and save and so on with values in A3, A4, A5.
Sub Pivotfilter()
Dim varItemsToReplace As Variant
Dim varItem As Variant
Dim wksSource As Worksheet
Dim wksDest As Worksheet
Dim rngSource As Range
Dim rngSource2 As Range
Dim rngCell As Range
Set wksSource = Worksheets("Instructions")
Set wksDest = Worksheets("Aging Report")
With wksSource
Set rngSource = .Range("A2:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
End With
For Each rngCell In rngSource
With wksDest
ActiveSheet.PivotTables("PivotTable40").PivotFields ("Client ID")
.PivotFields(rngCell.Value).Visible = True
Dim wb As Workbook
Set wb = Workbooks.Add
Windows("XXXXXXX").Activate
Sheets("Aging Report").Select
Sheets("Aging Report").Copy Before:=wb.Sheets(1)
wb.SaveAs "C:\Users\XXX\Desktop\SOA\" & .Range("B3").Value & " - " & .Range("B4").Value & ".xlsx"
wb.Close
Windows("XXXXXXX.xlsm").Activate
End With
Next rngCell
End Sub
For filtering by value, my preferred method is to add more columns to the data itself, set the values by formulae, and add those columns to the pivot
Eg column Scope boolean added to pivot filter, filter on only true
Adding 30/60/90 aging column, add this to a pivot row to group by age
Etc
This lets you avoid needles complexity of combining two lesser known areas of expertise vba in general and vba specifically for pivots
Some Useful guidelines:
Raw Data:
Select the data and create a pivot table named "pvtTest" in Shhet 5
Try:
Option Explicit
Sub test()
Dim pvt As PivotTable
Dim Pf As PivotField
Dim strFilter As String
'Assign to variable "pvt" the pivot table to work with it
Set pvt = Worksheets("Sheet5").PivotTables("pvtTest")
'Assigh to "strFilter" the string to filter
strFilter = "A"
'Use column "Shop" as a filter of pivot table
pvt.PivotFields("Shop").Orientation = xlPageField
'Assign by which column the pivot table will be filtered
Set Pf = Worksheets("Sheet5").PivotTables("pvtTest").PivotFields("Shop")
'Clear filter previous choices
Pf.ClearAllFilters
'Select to filter the pivot table based on the value of "strFilter"
Pf.CurrentPage = strFilter
End Sub

VBA code to make a pivot table is not working

I am having an issue with my pivot tables. For some reason, this code was working this morning but now it is not. Here is my code up until the error.
Dim WSD2 As Worksheet
Set WSD2 = ActiveWorkbook.Sheets.Add(After:= _
Worksheets(Worksheets.Count))
WSD2.Name = "POS Info"
'--------------------------------------------------
' Step 2: Create the pivot table
'--------------------------------------------------
Dim WSD As Worksheet
Dim PTCache As PivotCache
Dim PT As PivotTable
Dim PRange As Range
Dim FinalRow As Long
Dim FinalCol As Long
Dim StartPT As String
Dim BottomRowStart As Range ' this is for pivot table
Dim BottomRowEnd As Range ' this is for pivot table
Set WSD = Worksheets("aggregateData")
' Select the data for pivot table
FinalRow = WSD.Cells(Rows.Count, 2).End(xlUp).Row
FinalCol = WSD.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = WSD.Cells(2, 1).Resize(FinalRow, FinalCol)
Set PTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange, Version:=xlPivotTableVersion14)
'Where do I want the pivot table to start
StartPT = WSD2.Range("A1").Address(ReferenceStyle:=xlR1C1)
Set WSD2 = Worksheets("POS Info")
'Begin to Create the Pivot Table
Set PT = PTCache.CreatePivotTable(TableDestination:=StartPT, TableName:="POS Data")
The last line is where I get the following error message:
"Application-defined or object-defined error".
Any help would be much appreciated.
Thanks,
G
Like #GSerg said in the comment, TableDestination needs to be a range instead of an address.
Right now you assign an address to the TableDestination, which really is just a string (text) saying "$A$3" or similar. You need to change this to TableDestination:=WSD2.range(StartPT) and then you code should work.
Note that it is possible that this worked previously but not any more because you may have added more worksheets to the document. Then when VBA tries to understand the address "$A$3" it cannot decide which worksheet to use and hence throws an error. It's therefore always smart to be quite clear when referring to ranges, and to do it via their workbook.worksheets path. See here for more.

Excel VBA - Hide range of rows after variable sized pivot table

I trying to write a macro to format a number of sheets containing pivot tables. I am stuck on this one problem.
My sheet contains a number of stacked pivot tables. I need the VBA code snippet to hide, say, 1000 rows after the first table (or all tables except the top one if possible). The top table will vary in size from one day to the next so it is not possible to just hide a set range.
Thanks
To hide all the pivot tables except one, you may try something like this...
In the below code, change the name of the pivot table you don't want to hide.
Sub HideAllPivotTablesButOne()
Dim ws As Worksheet
Dim pt As PivotTable
Application.ScreenUpdating = False
Set ws = ActiveSheet
lr = ws.UsedRange.Rows.Count
For Each pt In ws.PivotTables
If pt.Name <> "PivotTable1" Then 'Name of the Pivot Table which you don't want to hide
pt.TableRange2.EntireRow.Hidden = True
End If
Next pt
Application.ScreenUpdating = True
End Sub
If you want to show all the pivot tables again, you may try the below code...
Sub ShowAllPivotTables()
Dim ws As Worksheet
Dim pt As PivotTable
Application.ScreenUpdating = False
Set ws = ActiveSheet
lr = ws.UsedRange.Rows.Count
For Each pt In ws.PivotTables
pt.TableRange2.EntireRow.Hidden = False
Next pt
Application.ScreenUpdating = True
End Sub

Copy and paste data from columns A to AI up to the last row in pivot table

I'm trying to copy and paste data from columns A and AI up to the last populated row in a pivot table that is located in columns AO to AP.
I have tried this code but it keeps pasting beyond the last row of the pivot table.
Sub Test1()
Dim LastRow As Long
Set blah = Range("A2:AI2")
Sheets("FI").Activate
LastRow = Cells(Cells.Rows.Count, "AO").End(xlUp).Row
Range("A2:AI2" & LastRow).FillDown
End Sub
To select a field from a pivot table in VBA, you could use something like this.
Dim Wks as Worksheet, oPvt as PivotTable
Set Wks = ActiveWorksheet
Set oPvt = Wks.PivotTables([PivotTableName])
oPvt.PivotSelect Name:="[Field]", _
Mode:=xlDataAndLabel, _
UseStandardName:=True
Selection.Copy
More option of what you can select from a PivotTable is here and PivotTable.PivotSelect Method in this and show you how to select some specific data from a field.

Resources