Looping VBA code for dynamic pivot table update - excel

I have found a solution to dynamically adjust pivot table filters from an excel cell which is working great; See here:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As
Range)
'This line stops the worksheet updating on every change, it only
updates when cell
'D1 or D2 is touched
If Intersect(Target, Worksheets("test").Range("D1:D2")) 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("test").PivotTables("PivotTable2")
Set Field = pt.PivotFields("Name")
NewCat = Worksheets("test").Range("D1").Value
'This updates and refreshes the PIVOT table
With pt
Field.ClearAllFilters
Field.CurrentPage = NewCat
pt.RefreshTable
End With
End Sub
I am trying to figure out how to loop this for example a defined number of times (ie 60) to control a large number of pivot tables all referring to different cells.
the plan is to have a list of employees and each pivot table will show data relevant to that employee, but the employee list will be dynamic.
EDIT:
Please see image of what i am trying to achieve;
The end goal is to set up page breaks and quickly refresh and print off individual skill levels for staff appraisals.

Looking at your image, this seems to be an XY Problem
You want a list of Users and their Skills. You have decided that this requires Multiple PivotTables. I propose instead a multi-column PivotTable, with a Blank Line between Users:
In addition to turning off Subtotals for "Name", you also need to "Insert blank line after each item label" and not "Display subtotals at the top of the group":
(Incidentally - when working from Multiple PivotTables, especially ones that use the same PivotCache, the PivotTable.ManualUpdate property is very useful to reduce redundant recalculation!)

Related

Can I get the name of a single Field in the "Values" quadrant of PivotTable?

Preface:
I am trying to build a macro that relies on no absolute references.
Problem:
Part of my macro needs the name of the field in the "Values" quadrant of the active PivotTable.
The field name will change so I cannot hard code it into my macro. (it is "AMT" in the image above, but it might be "Amount" in another PivotTable, which is why I need it to be dynamic.)
If I have a single Field in the value quadrant, how can I get it's name as a string? If I can just get it's name as a string, I can feed that into the macro that I have.
Speaking of which, here is my code just for reference:
Sub PivotNumberFormat()
'PivotNumberFormat Macro
'Formats the "Values" data field in the currently active pivot to: number format, 2 decimals, and commas
'=============================================
'Define variables
Dim PT As PivotTable
'=============================================
'Continue if pivot table not selected
On Error GoTo EndSub
'=============================================
'Set pivot table as variable "PT"
Set PT = ActiveCell.PivotTable
'=============================================
'If pivot table selected, change number format
If Not PT Is Nothing Then
'Change the format of the pivot table amt field
With PT.PivotFields("Sum of AMT") '<-------------This is the line where I need a dynamic reference.
.NumberFormat = "#,##0.00_);(#,##0.00)"
End With
'Notify user that format was changed
MsgBox "Format Changed"
'Stop macro
Exit Sub
End If
'=============================================
'If error, notify user and stop macro
EndSub:
MsgBox "Format NOT Changed"
End Sub
You can see about halfway down I put a note showing the PivotFields object that needs a dynamically-referenced name. Instead of the code reading "(Sum of AMT)", I want it to read "(Sum of [FieldName])" with [FieldName] being the dynamic field name string that changes with the PivotTable.
The vast majority of the time that I will use this macro, there will only be one field in the Values quadrant. If it is easy to make the macro scalable to multiple fields in the Values quadrant, that is a bonus, but definitely not required or needed.
I know that PivotTable vba is complex so I appreciate any of your valuable insight you bring to the table!
Thanks,
Logan
This might get you started:
Dim f As PivotField
For Each f In ActiveSheet.PivotTables(1).DataFields
Debug.Print f.SourceName, f.Name
Next f
See also: https://www.contextures.com/excel-vba-pivot-table-field-list.html

selecting a field from pivot table using vba macro

I have created a pivot table using vba. I need help with the understanding of below-mentioned points.
1: I want to select(copy) values with certain filters (eg: Underlying price
for Instrument Type = OPTCUR, Symbol = GBPUSD). Basically a VBA alternative for formula
GETPIVOTDATA("Underlying_price",$C$4,"Instrument Type","OPTCUR","Symbol","GBPUSD")
2: I want to set "show detail=True" without knowing cell details but the criteria as mentioned above.
3: when we set "show detail=True" a new sheet opens. i want to asign this sheet to a variable of type worksheet.
below is the SS of my pivot table. and TableName:="My_Pivot"
You get the relevant cell with PivotTable.GetPivotData
The new worksheet with details of this cell is shown by Range.ShowDetail = True.
Directly after that, the new ActiveSheet is the wanted one.
Here is a function to get the wanted worksheet with the details for a specified data field:
Private Function GetDetailSheet(pt As PivotTable, Val1 As String, Val2 As String) As Worksheet
Dim myCell As Range
With pt
Set myCell = .GetPivotData(.DataFields(1).Name, _
.RowFields(1).Name, Val1, _
.RowFields(2).Name, Val2)
End With
myCell.ShowDetail = True
Set GetDetailSheet = ActiveSheet
End Function
It can be used like this:
Private Sub Test()
Dim ws as Worksheet
Set ws = GetDetailSheet(ActiveSheet.PivotTables("My_Pivot"), "OPTCUR", "GBPUSD")
ws.Name = "Details OPTCUR GBPUSD"
End Sub
If you don't want to use the (hideos) GETPIVOTDATA there's a solution for you!
It's called CUBEVALUE. It's a bit difficult to master but once it's done you reports & Pivot Table get to a whole new level.
See here: https://www.excelcampus.com/cubevalue-formulas/
Yes, it's a long article, but it's definitely worth the effort, as it would enable you to point to a specific data point, not to a specific cell.
Once mastered, adding a VBA code to a "changed" cell event and changing the visibility status of a certain sheet is just a matter of minutes.

VBA Pivot filter on multiple cell ranges applied to multiple tables

While this topic is widely discussed I've been unable to find a proper solution to this issue.
As a data analyst, I would like to apply filters across multiple pivot table based on values in multiple cell ranges.
I have looked for answers and tried to apply these solutions:
https://www.mrexcel.com/forum/excel-questions/950078-filtering-pivot-table-based-cell-value.html
and this:
https://www.youtube.com/watch?v=xCJgCRuVU6c&t=201s
Specifically this code:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
'This line stops the worksheet updating on every change, it only updates when cell
'A1 to A9 is touched
If Intersect(Target, Worksheets(1).Range("A1:A9")) 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(1).PivotTables("PivotTable1")
Set Field = pt.PivotFields("Sales Region")
NewCat = Worksheets(1).Range("A1:A9").Value
'This updates and refreshes the PIVOT table
With pt
Field.ClearAllFilters
Field.CurrentPage = NewCat
pt.RefreshTable
End With
End Sub
however, they do not apply 100% as firstly it doesn't update anything at all (no reponse) and secondly it only applies the filter to the first column even if it would work.
Please see attached photo of how I'd like the model to look.
Above is of course not entirely true as the filtering options would remove many of the values in the tables.
The pivot tables have the IDs "PivotTable1" & "PivotTable2".
Worksheet is called "Sheet1".
I would like to be able to change these values and also the filter options (e.g. to include a Date value filter.
Please let me know if anything is unclear.
Also, if there are any other options that doesn't include VBA, these will also be well received.

Pivot/Table filter activated through link from other table's cell value

I have a list of items to work through and some items require deeper analysis. Essentially I have two tables. The first shows production results and through filtering column U, I get a list of outliers as in the following image.
Table of outliers
The values displayed in column S then require further analysis for which a pivot chart has been set up. In this chart I filter the particular VRTY number to take a closer look.
Pivot Chart for analysis
Both sheets are contained in the same workbook and I essentially work with two windows open, but to go through the list I have to manually enter every single VRTY value in the pivot filter.
The table of the Pivot chart and the outlier table are not related and data sources are different.
In column S of the outlier table (VRTY) I would ideally turn the values into links that automatically set the pivot filter to this value when clicked.
I am a novice at VBA but from the research I've done this will be the only option - I just haven't come by an instructions how to achieve this particular function.
Instructions/ advice would be highly appreciated.
Sambo: Make sure the orientation of the 'Number' field in the PivotChart's underlying PivotTable is a PageField, and then put the below code in the Sheet code module that corresponds to the sheet where the Outliers PivotTable is:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim pf As PivotField
Dim pf_Slave As PivotField
Set pf = ActiveSheet.PivotTables("PivotTable1").PivotFields("VRTY")
Set pf_Slave = ActiveSheet.PivotTables("PivotTable2").PivotFields("number")
If Not Intersect(Target, pf.DataRange) Is Nothing Then
On Error Resume Next
pf_Slave.CurrentPage = CStr(Target)
On Error GoTo 0
End If
End Sub
Change "PivotTable1" and "PivotTable2" as appropriate.
By "Sheet code module" I mean this type of thing:

Create an Excel view table?

I have the following raw table structure - a list of credit card transactions:
Date | Description | Debits | Credits
Date will be converted using this approach:
Ensure a valid date inside the cell in Excel
Other columns will stay AS IS. I can create the first row of a target table, but I need to expand it downwards to match the number of rows in the source table.
Is there a way to automate the last part, i.e. row expansion?
I am expecting the raw data table to grow over time, so the target table needs to adjust its row count as well (either fully automated or via a single-click macro).
There is a similar question on StackOverflow, but I am using named tables and named columns:
Matching number of rows in one excel table with the number of rows in another
Table names:
Source : TableRawData
Target : ProcessedData
Date conversion formula I am using in the 1st column:
=MorphDate(TableRawData[#Date])
Paste this code into the worksheet with the source Table (ListObject). I used the Table names you specified. You'll need to adjust the worksheet names to the actual ones in your workbook:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim loSource As Excel.ListObject
Dim loTarget As Excel.ListObject
Dim wb As Excel.Workbook
Set wb = ThisWorkbook
With wb
Set loSource = .Worksheets("Source").ListObjects("TableRawData")
Set loTarget = .Worksheets("Target").ListObjects("ProcessedData")
'Only change Target if Source has more rows or columns, i.e,
'don't shrink, only grow.
If loTarget.Range.Rows.Count < loSource.Range.Rows.Count Or _
loTarget.Range.Columns.Count < loSource.Range.Columns.Count Then
With loTarget
'two kinds of 'Resize in one line!
.Resize (.Range.Cells(1).Resize(loSource.Range.Rows.Count, loSource.Range.Columns.Count))
End With
End If
End With
End Sub
As noted in the comments this triggers if either the number of rows or columns gets bigger. If you want it to change if Target grows or shrinks then change the <'s to <>'s.
If you are interested in the two different Resizes used in the code, and some information on copying Tables, see my this post of mine.

Resources