Hi All,
I'm new to macros and I am completely stuck. I am trying to filter a pivot table based on a date range using a macro. I have two cells where the start date and the end date will be inputted (using data validation) which will make up the date range. I've scoured through the forums and found a code that works, but it is written for several PTs which all have the same filter name. My problem is that I have several PTs but with different filter names (e.g. some are called "Date" others "PeriodDate"). Can anyone help me adapt this code (or any other which would do the trick) so it will run on only a single PT?
Public Sub Filter2()
Application.ScreenUpdating = True
Dim StartDate As Date, EndDate As Date
StartDate = ActiveSheet.Range("B1").Value
EndDate = ActiveSheet.Range("C1").Value
'takes the Date values from the sheet
'If there are no values then Gives them default values
If StartDate = 0 Then
MsgBox "Date Missing"
Exit Sub
End If
If EndDate = 0 Then
MsgBox "Date Missing"
Exit Sub
End If
Dim PT As PivotTable
Dim pf As PivotField
Dim pi As PivotItem
For Each PT In ActiveSheet.PivotTables
'Filters The dates between StartDate and EndDate in all pivot tables
'in the active sheet
PT.PivotFields("Date").ClearAllFilters
'goes through each pivot table on the sheet
Set pf = PT.PivotFields("Date")
For Each pi In pf.PivotItems
'goes through every item in the field "Date"
If Not pi.Name = "(blank)" Then
'ignores blanks and then checks if date is in range
If pi.Value < StartDate Or pi.Value > EndDate Then
pi.Visible = False
Else
pi.Visible = True
End If
End If
Next pi
Next PT
Application.ScreenUpdating = True
End Sub
Thanks in advance,
Darrel
Bookmarks