AngelicaWan
New Member
- Joined
- Aug 20, 2015
- Messages
- 8
I just encounter this issue and want to find a solution to auto filter just the most recent date in Pivot Table via VBA.
Like I want to set "TIME" column as filter field in Pivot Table. I searched online and modified a little bit to see whether it could work. Here are the codes:
Module1:
Sub MaxDatePivot()
Dim pfiPivFldItem As PivotItem
Dim PvtTbl As PivotTable
Dim dtmDate As Date
With ThisWorkbook.Sheets("Sheet1").PivotTables(1)
.ClearAllFilters
With .RowRange
dtmDate = Evaluate("MAX(IF(ISNUMBER(" & .Address(0, 0) & ")," & .Address(0, 0) & ",))")
End With
For Each pfiPivFldItem In .PivotFields("TIME").PivotItems
If pfiPivFldItem.Value = "(blank)" Then
pfiPivFldItem.Visible = False
Else
pfiPivFldItem.Visible = CDate(pfiPivFldItem.Value) = CLng(dtmDate)
End If
Next pfiPivFldItem
PvtTbl.PivotFields("TIME").PivotFilters.Add Type:=xlAfterOrEqualTo, Value1:=pfiPivFldItem
End With
End Sub
ThisWorkbook:
Private Sub Workbook_Open()
MaxDatePivot
End Sub
However, it showed me the red part is "Type Mismatch".
Is it possible to make it happen? How to modify or write codes to realize it? Thanks!
Like I want to set "TIME" column as filter field in Pivot Table. I searched online and modified a little bit to see whether it could work. Here are the codes:
Module1:
Sub MaxDatePivot()
Dim pfiPivFldItem As PivotItem
Dim PvtTbl As PivotTable
Dim dtmDate As Date
With ThisWorkbook.Sheets("Sheet1").PivotTables(1)
.ClearAllFilters
With .RowRange
dtmDate = Evaluate("MAX(IF(ISNUMBER(" & .Address(0, 0) & ")," & .Address(0, 0) & ",))")
End With
For Each pfiPivFldItem In .PivotFields("TIME").PivotItems
If pfiPivFldItem.Value = "(blank)" Then
pfiPivFldItem.Visible = False
Else
pfiPivFldItem.Visible = CDate(pfiPivFldItem.Value) = CLng(dtmDate)
End If
Next pfiPivFldItem
PvtTbl.PivotFields("TIME").PivotFilters.Add Type:=xlAfterOrEqualTo, Value1:=pfiPivFldItem
End With
End Sub
ThisWorkbook:
Private Sub Workbook_Open()
MaxDatePivot
End Sub
However, it showed me the red part is "Type Mismatch".
Is it possible to make it happen? How to modify or write codes to realize it? Thanks!