Filtering values from OLAP Cube Pivot Table - vba

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)

Related

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.

VBA: Finding the row number by looking up a user defined value (date)

I am trying to use VBA to look up the row value that corresponds to a user defined date on one of my work sheets so that I am able to edit all data on that row.
As a bit of context:
I have several time series data sets that all have different start and end dates with a good portion of overlap in the middle. I want to chart these using user defined date parameters, however, because of non-uniform start dates, the chart is impossible to dynamically rebase.
I was hoping to use a macro to clone the data on one sheet, overwrite the line of values that corresponds to the user defined start date, and then calculate return values based on percentage change figures (I already have in a different sheet).
If I can dynamically o/w the row that corresponds to the UD start date of the date range, I can replace it with a one and all my calculations will effectively rebase.
Any and all feedback would be great!
EDIT
Lucas,
I am having two issues; firstly, what I have inexpertly cobbled together doesn't work when I protect the sheets (not insurmountable); secondly, it doesn't work :). Here is my work:
Sub Rebase()
Dim UDStartVal
Dim UDStartLoc As Range
Dim UDRow As Integer
'
' Rebase Macro
' A macro to rebase the chart to the user defined start date.
'
'
Sheets("Cumulative Monthly Returns").Select
Cells.Select
Selection.Copy
Sheets("Chart Numbers").Select
Range("A1").Select
ActiveSheet.Paste
' Lookup to change the value of the cells corresponding to the user defined start date to 0, effectivley rebasing the portfolo.
Worksheets("Cumulative Period Returns").Activate
UDStartVal = Cells(4, 2).Value
Set UDStartLoc = Range("A:A").SpecialCells(xlCellTypeVisible).Find(UDStartVal)
Set UDRow = UDStartLoc.Row
Stop
End Sub
Here's some code that I use to find the row of an entry based on quote numbers on a sheet that gets resorted and re-filtered constantly.
Private Sub FindQuote(partNum as String)
Dim quoteRow as Range
Set quoteRow = Range("A:A").SpecialCells(xlCellTypeVisible).Find(partNum)
then when I want to do something that uses the range of that row I use quoteRow.Row
If Not quoteRow Is Nothing Then
quoteNum = Cells(quoteRow.Row, "P").Value
Cells(quoteRow.Row, "Q").Value = "Found"
Else
MsgBox "No quote was found"
End If
End Sub
Did you need help with the part where you clone your sheet?

Excel VBA to filter Pivot Table and Pivot Chart for previous day - Pivot Filter Field

Here is my problem, every bit of code, every alteration, every type, doesn't work. I'm using Office 360 at my work site (up to date), so it's excel 2016 and VBA 7.1.
What I'm looking to do is automate our end of shift reports. Here's the process:
We enter data into an excel sheet (Log) every hour. At the end of the day, at 5:00 AM, we save and close that log, open another excel sheet that IMPORTS the data into power pivot, and displays it on a PivotTable (formatting for printing for our bosses), and we choose the filter for the previous date using the filter drop down, and print it. We do this with three (3) reports: 2 PivotTables, and 1 PivotChart. Power Pivot imports ALL of the data from the Log sheet to reformat it for printing.
I've successfully managed to get and rewrite the code (beginner at this) for the automation process of: auto saving the log, closing the log, opening the Report workbook, refreshing the data, and printing the data, then closing the report. The only part I'm now missing is the auto-filtering.
The code I've tried is vast, but here's an example of what I've tried recently (I've erased and re-copied so many codes...)
Sub Filter_PivotField()
'Description: Filter a pivot table or slicer for a specific date or period
'Source: excelcampus.com/vba/filter-pivot-table-slicer-recent-date-period
Dim sSheetName As String
Dim sPivotName As String
Dim sFieldName As String
Dim sFilterCrit As String
Dim pi As PivotFields
'Set the variables
sSheetName = "EOS Report"
sPivotName = "PivotTable1"
sFieldName = "Date"
sFilterCrit = "xlDateYesterday"
'sFilterCrit = ThisWorkbook.Worksheets("EOS Report").Range("O1").Value
With ThisWorkbook.Worksheets(sSheetName).PivotTables(sPivotName).PivotFields(sFieldName)
'Clear all filter of the pivotfield
.ClearAllFilters
'Loop through pivot items of the pivot field
'Hide or filter out items that do not match the criteria
For Each pi In .PivotFields
If pi.Name <> sFilterCrit Then
pi.Visible = False
End If
Next pi
End With
End Sub
To no avail....
When I record a macro doing the manual filter, I get this:
Sub manualfilter()
'
' manualfilter Macro
'
'
ActiveSheet.PivotTables("PivotTable1").PivotFields( _
"[Bi-Hourly Report].[Date].[Date]").VisibleItemsList = Array( _
"[Bi-Hourly Report].[Date].&[2016-09-28T00:00:00]")
End Sub
But it fails when I try to re-run the same macro that I just recorded (after changing the date back). I've enabled and disabled multiple selection option, etc.
Not to mention, trying to auto-filter a chart is a nightmare because tables, yea there's tons of articles on it, but charts? not much comes up on researching.
Here's images of the filter button, because almost everything I've researched is to sort the COLUMN of the Table, not the filter itself with a PivotTable.
Table Filter
Chart Filter
I cannot post the actual excel spreadsheets as they are proprietary property of the company, but I can replicate the format with false data if needed.
check this out.
Dim prev_date As String
prev_date = Month(Date - 1) & "/" & Day(Date - 1) & "/" & Year(Date - 1)
Thisworkbook.Sheets("Sheet1").Activate
'change this line with your sheet where pivot table is present. Change Sheet name.
ActiveSheet.PivotTables("PivotTable1").RefreshTable
ActiveSheet.PivotTables("PivotTable1").PivotFields("Date").CurrentPage = prev_date

excel real time refresh of filter

In my Pivot Table in excel, I have a field List about the due date of some reports.
For example, 10/5/2016
My problem is, every day I have to choose the date so that I can see the report code, I don't want it to be this. What I want is, everyday I open the excel, the filter will automatically change from 10/5/2016 to 11/5/2016.
What function / VBA should I use?
Helps
If you want a VBA solution, add the following to the ThisWorkbook code.
Private Sub Workbook_Open()
Dim tDay As Date, pf As PivotField
tDay = Date
Set pf = Sheets("name of worksheet").PivotTables("pivot table name").PivotFields("insert the name of your filter here")
pf.ClearAllFilters
pf.CurrentPage = tDay
End Sub
Change the sheet name, pivot table name and the name of the filter.
If you need to do more VBA manipulation of pivot tables I suggest reading the following http://www.thespreadsheetguru.com/blog/2014/9/27/vba-guide-excel-pivot-tables.

Excel - Using COUNTIFS to count dates within a certain range across multiple sheets

I am trying to "COUNT" the number of dates that fall between a certain date range over multiple sheets excluding the first 'Summary' sheet. Following other examples I have used:
=COUNTIFS('CWP-A1-Inst'!S7:S51,">=2015-09-13" _
,'CWP-A1-Inst'!S7:S51,"<=2015-09-19") _
+ COUNTIFS('CWP-A2-Inst'!V7:V51,">=2015-09-13" _
,'CWP-A2-Inst'!V7:V51,"<=2015-09-19") _
+ COUNTIFS('CWP-A3-Inst'!T7:T50,">=2015-09-13" _
,'CWP-A3-Inst'!T7:T50,"<=2015-09-19")
This method works but I have 28 sheets, 75 date ranges (each week starting with Sunday ending with Saturday for over a year) and 7 cost codes to fill this out for. It would take forever to change these all manually.
I have also tried the UDF suggested in another example - Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column - but I am unable to figure out how to add the second set of criteria in the example as I am by no means a VB expert.
Thanks in advance for any recommendations.
It is easier to get summary information about data when it is in a good structure.
If you had one big long list you would benefit from being able to use pivot tables For examples see here
If you were to take you data and put it in one long list this would be a good start (if the existing tables have the same structure).
Harvey
Try this mod to the posted UDF link.
Edit: code has been fixed so now it works. I also added the "<=" into the function, so all you need to provide is the input dates as they are and nothing else.
Function myCountIf(rng As Range, startDate as Variant, endDate as Variant) As Long
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
myCountIf = myCountIf + WorksheetFunction.CountIf(ws.Range(rng.Address), "<=" & endDate) - WorksheetFunction.CountIf(ws.Range(rng.Address), "<=" & startDate)
Next ws
End Function
And for startDate and endDate enter your criteria eg =myCountIf(A:A,">=2015-09-13","<=2015-09-19").