How to link cell value as a filter in PowerPivot Pivot Table in Excel? - vba

I have two Pivot Table (PivotTable1 and PivotTable2) in Sheet PivotTables_Sheetand a cell that shows the year in Sheet YearInput. I tried to link the cell year (J4) in YearInput as a filter to all pivot tables in PivotTables Sheet.
But somehow my code doesn't work as expected. Anybody knows how to correct this code?
This is the code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Target.Address = Range("J4").Address Then Exit Sub
Dim pt As PivotTable
Dim ptItem As PivotItem
On Error Resume Next
For Each pt In Worksheets("PivotTables_Sheet").PivotTables
With pt.PivotFields("Year for Sales")
If .EnableMultiplePageItems = True Then
.ClearAllFilters
End If
Set ptItem = .PivotItems(Target.Value)
If Not ptItem Is Nothing Then
.CurrentPage = Target.Value
End If
End With
Next
End Sub
Note: I use Excel 2010 and built the pivot tables using PowerPivot.

One way to do this without VBA is to use a slicer which is common between all the pivots. Then one year is changed on one, it will also update the other pivot tables.
This is by first clicking on the pivot, which will then show on the ribbon an Analyze option. Under that there is an insert slicer, which you would do for year.
Afterwards you would go to your other pivots and instead do filter connection, and select your year slicer.
Note that the year slicer can then just be moved to a hidden sheet if you do not want the end user to see it, it will still do its job of propagating the year across all the pivots that are referencing it.

Related

Excel VBA Loop Through a PivotTable and perform calculation

I have a PivotTable that automatically refreshes every time I refresh a data set to our mySQL database in our office.
My Excel file launches a query against the mySQL database and returns a data table, and I have two PivotTables on separate sheets that will automatically update every time that is done. My code for that is below:
Sub UpdatePivots()
' This sub is intended to update all pivot charts in the by switching to the appropriate
' worksheet, locating the appropriate pivot table, and updating them.
Dim ws As Worksheet
Dim PT As PivotTable
For Each ws In ActiveWorkbook.Worksheets '<~~ Loop all worksheets in workbook
For Each PT In ws.PivotTables '<~~ Loop all pivot tables in worksheet
PT.PivotCache.Refresh
Next PT
Next ws
End Sub
What I am looking to do calculate a YIELD for some of the fields in the Pivot Table. The table currently looks like this below:
As you can see, I added in the "YIELD" column automatically and simply did an:
=GETPIVOTDATA("Pass / Fail",$B$5,"Job ID","Job 1","Pass / Fail","Pass")/GETPIVOTDATA("Pass / Fail",$B$5,"Job ID","Job 1")
Ideally, what I would like to do is add to my UpdatePivots() macro to automatically calculate the yield (Pass / Grand Total) for each of the rows listed.
This table is subject to change in size - sometimes I am looking at only 3 jobs in a given month (like September so far), other times my boss wants me to run this report for an entire year where I can have an upwards of 100 jobs. So I would like to use some pseudo code that might look like this:
Cell F6.Text = YIELD
<Apply Pivot Table Formatting to Cell F6>
for each row in pivottable {
Cell Fx.Value = Pass / Grand Total
}
Can anybody help me do that? I have tried brainstorming on paper, but don't even know where to start.
PS - How can I get the Pivot Table to stop that terrible formatting, and to keep my grayed cells? I want to eventually add in charts.
Thank you!!
The following code satisfies my need:
Sub CalculateYield()
k = Cells(Rows.Count, 2).End(xlUp).Row
For r = 9 To k
Cells(r, 6).Formula = "=" & Cells(r, 3).Address(False, False) & "/" & Cells(r, 5).Address(False, False)
Next
End Sub

How to adjust PivotTable Filters

I'm trying to create a macro that will pull some data from a pivot table into a collection variable. What I'm wanting to do is to collect each Article's Sales Forecast and Insight each month for a single year (image below). The issue I have is that I don't know how to collect the information without it being shown in the pivot table, and I don't know how to have the macro adjust the column filters to meet my requirements.
I don't have access to the source of this pivot table and I'm reluctant to have the user manually adjust the table's column filters.
For clarification, the column filter goes by Year -> Quarter -> Month -> Week.
Edit:
What I'm trying to accomplish starts with a schedule workbook where the relevant article numbers are kept. The Master Scheduler has a different workbook with the input values (pivot table above) to base the calculations. This input workbook only has pivot tables and I don't know where it pulls the data; just this is where the Master Scheduler manually finds the relevant data.
My thought process is to pull the relevant articles from the scheduling workbook, pull all of the articles for one full year, sort out only the relevant articles, and place the sorted information into a new location in the Schedule workbook.
The issue I'm coming across is that the column filters may not be showing all of the relevant data and I don't know how to make VBA set the pivot table's filter to prevent this. The solutions that I have found changes the F9 cell, "Year," to an actual year value, which is not what I want to do.
In addition, when you manually open the column filter to select which year, there are four quarters (or seasons) where all four must have a check mark in the box for all twelve of the months to be available.
Hopefully this clarifies my question.
After some more research, I found this website that answers my question: Expand and Collapse Entire Pivot Table Fields – VBA Macro. I've also learned about the pt.ClearAllFilters command.
If the website becomes unavailable in the future, the code is also listed below.
Expand:
Sub Expand_Entire_RowField()
'Expand the lowest position field in the Rows area
'that is currently expanded (showing details)
Dim pt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem
Dim iFieldCount As Long
Dim iPosition As Long
'Create reference to 1st pivot table on sheet
'Can be changed to reference a specific sheet or pivot table.
Set pt = ActiveSheet.PivotTables(1)
'Count fields in Rows area minus 1 (last field can't be expanded)
iFieldCount = pt.RowFields.Count - 1
'Loop by position of field
For iPosition = 1 To iFieldCount
'Loop fields in Rows area
For Each pf In pt.RowFields
'If position matches first loop variable then
If pf.Position = iPosition Then
'Loop each pivot item
For Each pi In pf.PivotItems
'If pivot item is collapsed then
If pi.ShowDetail = False Then
'Expand entire field
pf.ShowDetail = True
'Exit the macro
Exit Sub
End If
Next pi
End If
Next pf
'If the Exit Sub line is not hit then the
'loop will continue to the next field position
Next iPosition
End Sub
Collapse:
Sub Collapse_Entire_RowField()
'Collapse the lowest position field in the Rows area
'that is currently expanded (showing details)
Dim pt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem
Dim iFieldCount As Long
Dim iPosition As Long
'Create reference to 1st pivot table on sheet
'Can be changed to reference a specific sheet or pivot table.
Set pt = ActiveSheet.PivotTables(1)
'Count fields in Rows area minus 1 (last field can't be expanded)
iFieldCount = pt.RowFields.Count - 1
'Loop backwards by position of field (step -1)
For iPosition = iFieldCount To 1 Step -1
'Loop fields in Rows area
For Each pf In pt.RowFields
'If position matches first loop variable then
If pf.Position = iPosition Then
'Loop each pivot item
For Each pi In pf.PivotItems
'If pivot item is expanded then
If pi.ShowDetail = True Then
'Collapse entire field
pf.ShowDetail = False
'Exit the macro
Exit Sub
End If
Next pi
End If
Next pf
'If the Exit Sub line is not hit then the
'loop will continue to the next field position
Next iPosition
End Sub
Edit: Solution Specific
Dim pt As PivotTable
Dim pf As PivotField
Set pt = ws.PivotTables(1)
'Setting all of the column filters to desired setup
For Each pf In pt.ColumnFields
pf.Hidden = False
pf.ClearAllFilters
'Drill Down until Months are opened, then exit the loop
If UBound(Split(pf.Name, "Month")) > 0 Then
pf.DrilledDown = False '<-- Ensuring nothing beneath "Months" is
Exit For
Else
pf.DrilledDown = True
End If
Next

Trying to use VBA to filter my Pivot Table based on Year and Period values in cells D2 and E2

I am trying to filter my Pivot Table using VBA so it will filter based on a Period and a Year in cells D2 and E2 respectively. I have the below code which is to filter by the year and works without having the Fiscal Period in the Columns but when I put the Fiscal Period in the columns it debugs at the Field.ClearAllFilters and Field.CurrentPage = Year lines. Can someone please help me find a fix for this?
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Intersect(Target, Worksheets("CY PT").Range("E2")) Is Nothing Then Exit Sub
Dim PT As PivotTable
Dim Field As PivotField
Dim Year As String
Set PT = Worksheets("CY PT").PivotTables("CY PT")
Set Field = PT.PivotFields("Fiscal Year")
Year = Worksheets("CY PT").Range("E2").Value
With PT
Field.ClearAllFilters
Field.CurrentPage = Year
PT.RefreshTable
End With
End Sub
The .CurrentPage method only applies to PageFields. Sounds like you are trying to filter RowFields. So your options are:
Change your fields to be PageFields; or
Use a Slicer; or
Use a PageField filter dropdown mascarading as a Data Validation
dropdown (like I outline at
http://dailydoseofexcel.com/archives/2014/08/16/sync-pivots-from-dropdown/
); or
Iterate through the PivotItems collection for each field, and set the
.Visible status of everything but the selected items to FALSE.
If you choose the last option, you need to be aware this can take a while. See the code I posted at Filtering a Pivot Table Based on Variable Range to get an understanding of how to do this efficiently. Also give my post at http://dailydoseofexcel.com/archives/2013/11/14/filtering-pivots-based-on-external-ranges/ a read.

Table Filtering drop down list Excel VBA

I am currently doing my final year project and it make use of excel VBA whereby I am bad at it. I am really hope someone could guide me through the problem that I am facing.
As for now, I am hoping that I can use a drop down list to filter my table whereby it only shows the particular department and weeks I want to show.
From the image below,
From the range("C7:L26"), whenever I filter cell(F2) or cell(J2), it will leave the data that I want from the dropdown list.
For example, if cell(F2) = 2 and cell J2 = e,
From range("C7,L26"), it will only show department with value "e" and have week 2 in it. As for cells that does not have the department value or week value, it will be cleared or blank.
I also hope that if it is possible to press a button to return the table back to default.
Do guide me and I really need your help!! Thank You
[1]http://imgur.com/GNGyh91
[2]http://imgur.com/uuh2Y1u
As for now I have this as my codes that I've learnt from a user #PeterT
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A1:AW28")) Is Nothing Then
Dim legendWS As Worksheet
Dim legendcell As Range
Set legendWS = ThisWorkbook.Sheets("Legend")
Set legendcell = legendWS.Range("A2:A18").Find(Target.Value)
If Not legendcell Is Nothing Then
Target.Interior.Color = legendcell.Interior.Color
End If
End If
End Sub
End Sub

Excel VBA: Output Distinct Values and Subtotals

I have data of this form:
Category Source Amount
Dues FTW $100
Donations ODP $20
Donations IOI $33
Dues MMK $124
There is no sort order. The categories are unknown at compile time. I want a VBA macro to cycle through the range, output a list of distinct values, with the subtotals for each. For the above data, it would look like this:
Category Total Amount
Dues $224
Donations $55
How can I do this? Also, is there a way to make the macro run every time the table above is updated, or is it necessary for the user to click a button?
You may want to use a built in Excel feature to do this. Looping can take a long time and be problematic if you have a lot of values to loop through.
Something like the following might get you started on creating a pivot table (from http://www.ozgrid.com/News/pivot-tables.htm)
Sub MakeTable()
Dim Pt As PivotTable
Dim strField As String
'Pass heading to a String variable
strField = Selection.Cells(1, 1).Text
'Name the list range
Range(Selection, Selection.End(xlDown)).Name = "Items"
'Create the Pivot Table based off our named list range.
'TableDestination:="" will force it onto a new sheet
ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, _
SourceData:="=Items").CreatePivotTable TableDestination:="", _
TableName:="ItemList"
'Set a Pivot Table variable to our new Pivot Table
Set Pt = ActiveSheet.PivotTables("ItemList")
'Place the Pivot Table to Start from A3 on the new sheet
ActiveSheet.PivotTableWizard TableDestination:=Cells(3, 1)
'Move the list heading to the Row Field
Pt.AddFields RowFields:=strField
'Move the list heading to the Data Field
Pt.PivotFields(strField).Orientation = xlDataField
End Sub
This is for subtotals (though I much prefer pivot tables)
http://msdn.microsoft.com/en-us/library/aa213577(office.11).aspx
EDIT:
I reread and have the following thoughts. Set up the pivot table on a separate sheet (without using any code) then put the following code on the sheet that has the pivot table so that the table will update everytime the sheet is selected.
Private Sub Worksheet_Activate()
Dim pt As PivotTable
'change "MiPivot" to the name of your pivot table
Set pt = ActiveSheet.PivotTables("MyPivot")
pt.RefreshTable
End Sub
Edit #2
Refresh all pivot tables on sheet
http://www.ozgrid.com/VBA/pivot-table-refresh.htm
Private Sub Worksheet_Activate()
Dim pt As PivotTable
For Each pt In ActiveSheet.PivotTables
pt.RefreshTable
Next pt
End Sub
The link has multiple options on how to refresh pivot tables in the sheet/workbook.