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

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.

Related

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

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.

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

Filtering values from OLAP Cube Pivot Table

I have a pivot table with a lots of date that I can choose in the filter (more than 1000 differents values).
What I need is to filter these values which are Dates from a user input.
example: Start date is 01-03-2018 to End date 20-03-2018
I need to do this through VBA code.
I'm not sure if actually the date values shown in the PT are really declared as date variable.
These values come from the Time dimension of the cube.
Here are some screenshots.
Image 1
Image 2
I made a try by using Wroksheet_Change but that works fine when I enter one date only (for example 2018-03-20) and the PT updates correctly, but i don´t know how to do it for a range of dates. Here is the code I used for one date only
Private Sub Worksheet_Change(ByVal Target As Range)
Dim newDate As String
newDate = Worksheets("KPICuboSIGP").Range("M4").Value
If Target.Address = "$M$4" Then
ActiveSheet.PivotTables("KPI-BPOP").PivotFields("[Time].[Date].[Date]"). _
VisibleItemsList = Array("[Time].[Date].&[" & newDate & "T00:00:00]")
End If
End Sub
I turned on the macro recorder too, and this is what it recorded.
ActiveSheet.PivotTables("KPI-BPOP").PivotFields("[Time].[Date].[Date]"). _
VisibleItemsList = Array("[Time].[Date].&[2018-01-21T00:00:00]", _
"[Time].[Date].&[2018-01-22T00:00:00]", "[Time].[Date].&[2018-01-23T00:00:00]", _
"[Time].[Date].&[2018-01-24T00:00:00]", "[Time].[Date].&[2018-01-25T00:00:00]", _
"[Time].[Date].&[2018-01-26T00:00:00]")
Those dates recorded should be selected automatically once I have the range from the user. Maybe I need to cycle through the options in the filter with For cycle, but I don´t know how to do it.
I'm pretty much a rookie in VBA
Can anyone help me with this.
Thanks for any advice
You can use the Labels filter to accomplish this. The problem is that the Labels filter isn't available to fields in the Filters part of a PivotTable. So you need to whip up a second PivotTable with nothing but the Dates field in it as a row field, then connect that PivotTable to the original PivotTable with a Slicer, and then programatically set a Label filter on the second PivotTable as I outline at Use VBA to select and deselect multiple slicer items (OLAP data)

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

Referencing Autofilter Results in VBA

I am currently experimenting using VBA and autofilter to query a dataset (as per Populate Excel Data Validation Drop-Down From Data Range Condition Using VBA )
However I am having trouble using VBA to refer to the auto filter results.
How can I collect results without needing to copy and paste? (for example to store a result as a variable)
How can I check how many results have been found, and trigger a msg box when the auto filter produces no results?
Thanks for your help
You may use the special parameters xlCellTypeVisible and SpecialCells.
Sub Test()
Dim SheetERP As Worksheet
Set SheetERP = Worksheets("MyDatas") 'Sheet with data
Dim myTabela As Excel.ListObject
Set myTabela = SheetERP.ListObjects("CodeData") 'Named Table range
Dim qtd As Integer 'To count filtered data rows (only visible)
qtd = SheetERP.ListObjects("CodeData").DataBodyRange.Columns(1).SpecialCells(xlCellTypeVisible).Count
'OR
qtd = myTabela.DataBodyRange.Columns(1).SpecialCells(xlCellTypeVisible).Count
MsgBox qtd
Dim TFiltro As Range
Set TFiltro = SheetERP.UsedRange.SpecialCells(xlCellTypeVisible)
'OR
Set TFiltro = myTabela.DataBodyRange.SpecialCells(xlCellTypeVisible)
'Do what you want with TFiltro
End Sub