Looking to filter a pivot table to be within a date range. The date filter is at the top of the pivot, with the main table having 3 columns. I have a picture with actual examples but can't upload here.
If I enter a date range of 1st Feb. 2018 - 1st March 2018 the filter works perfectly. If I enter a date range of 1st Feb. 2018 - 28th Feb 2018 the filter misses out the 3rd Feb - 9th Feb, picking back up again for the remainder of the data from the 10th Feb.
Different date ranges produce variants of this behavior.
From my research online this type of filtering in VBA has a bug of some sort where the code reads the data in US date format, regardless of Excel settings & the data itself (hence the formatting code, without it causes a mismatch error). I've seen a couple of workarounds online such as using CLng but the method below is the closest I've got.
- The pivot table itself is on a worksheet called "Pivots". Columns A-C, Date in cell B2, main table headers in row 4.
- The date range is on a worksheet called "Paretos", cell refs below.
- The table I'm working on here is PivotTable1
Sub FilterPivotDates()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.EnableEvents = False
Dim ws As Worksheet, ws2 As Worksheet, pt As PivotTable, pf As PivotField, PI As PivotItem
Dim FromDate As Date, ToDate As Date
Set ws = ThisWorkbook.Worksheets("Pivots")
Set ws2 = ThisWorkbook.Worksheets("Paretos")
FromDate = ws2.Range("B1").Value
ToDate = ws2.Range("E1").Value
pivno = 1
MCCol = 25
Set pt = ws.PivotTables("PivotTable" & pivno)
Set pf = pt.PivotFields("Date")
'On Error Resume Next
Do While pivno < 2 '25
Set pt = ws.PivotTables("PivotTable" & pivno)
Set pf = pt.PivotFields("Date")
pt.PivotFields("Date").ClearAllFilters
With pf
For Each PI In pf.PivotItems
If PI.Value >= Format(FromDate, "M/D/YYYY") And PI.Value <= Format(ToDate, "M/D/YYYY") Then PI.Visible = True Else PI.Visible = False
Next
End With
pivno = pivno + 1
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
Stepping through using msgbox commands it seems the missing dates are failing on one of the date checks, so the AND function removes the entry. I can't work out whats going on.
Using Excel 2016