Problems filtering a Pivot Table with VBA

Frank123

New Member
Joined
Mar 27, 2024
Messages
2
Office Version
  1. 365
Platform
  1. Windows
I have have a data table something like this in worksheet "Base Ventas Asistido".
Fecha DesdeSKUVentasDivision
29-01-2024mpm239583000Deporte
05-02-2024mpm387542000Regalos
19-02-2024mpm488324000Deporte
29-01-2024mpm38784300Deporte
19-02-2024mpm28494500Deporte

And in worksheet "Deporte" in cell C2 and C3 I have a START DATE and an END DATE.

1711560980066.png


With VBA I managed to creat this pivot table, that ended up somthing like this:
1711561061002.png



Now I want to filter between dates using this code:

VBA Code:
Dim startDate As Date
Dim endDate As Date

If IsDate(ws_Dest.Range("C2").Value) Then
    startDate = ws_Dest.Range("C2").Text

Else
    MsgBox "The start date is not a valid date."
    Exit Sub
End If

If IsDate(ws_Dest.Range("C3").Value) Then
    endDate = ws_Dest.Range("C3").Text
Else
    MsgBox "The end date is not a valid date."
    Exit Sub
End If

    If IsDate(startDate) And IsDate(endDate) Then
        ' Apply the date filter
       With ptTable.PivotFields("Fecha Desde")
             .ClearAllFilters ' Clear any existing filter
             .PivotFilters.Add2 Type:=xlDateBetween, Value1:=CLng(startDate), Value2:=CLng(endDate)
       End With
        
    Else
        MsgBox "The start date or end date is not a valid date."
    End If

But I keep getting this error Error 1004 Application-defined or object-defined in this line:

VBA Code:
.PivotFilters.Add2 Type:=xlDateBetween, Value1:=CLng(startDate), Value2:=CLng(endDate)


Here is the whole code:
VBA Code:
Sub CrearTablaDinamicaaaa()
    Dim ws_Source As Worksheet
    Dim ws_Dest As Worksheet
    Dim ptCache As PivotCache
    Dim ptTable As PivotTable
    Dim rangoDatos As Range
    Dim lastRow As Long
    Dim ptTableName As String
    
    
    
    Set ws_Source = ThisWorkbook.Sheets("Base Ventas Asistidos")
    Set ws_Dest = ThisWorkbook.Sheets("Deporte")
    ptTableName = "TablaDinamicaVentas"

    ' Define range where to place the Pivot Table
    lastRow = ws_Source.Cells(ws_Source.Rows.Count, "A").End(xlUp).Row
    Set rangoDatos = ws_Source.Range("A1:L" & lastRow)

    ' Crear un Pivot Cache
    Set ptCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rangoDatos)
    
    
    ' Crete Pivot Table
    Set ptTable = ptCache.CreatePivotTable(TableDestination:=ws_Dest.Range("H40"), TableName:=ptTableName)
    

    ' Configure Pivot Table
    With ptTable
        'Filter
        .PivotFields("División").Orientation = xlPageField
        .PivotFields("División").Position = 1

        'Filter
        .PivotFields("Fecha Desde").Orientation = xlPageField
        .PivotFields("Fecha Desde").Position = 2

        'Rows
        .PivotFields("SKU").Orientation = xlRowField
        .PivotFields("SKU").Position = 1

        'Create Values of "Ventas" (Sales)
        With .PivotFields("Ventas")
            .Orientation = xlDataField
            .Position = 1
            .Function = xlSum
            .NumberFormat = "#,##0"
            .Name = "Total Ventas"
        End With
    End With
    
    ' Refresh
ptTable.RefreshTable

'sort
With ptTable
    .PivotFields("SKU").AutoSort xlDescending, "Total Ventas"
End With

' Refresh
ptTable.RefreshTable

Dim startDate As Date
Dim endDate As Date

If IsDate(ws_Dest.Range("C2").Value) Then
    startDate = ws_Dest.Range("C2").Text
Else
    MsgBox "The start date is not a valid date."
    Exit Sub
End If


If IsDate(ws_Dest.Range("C3").Value) Then
    endDate = ws_Dest.Range("C3").Text
Else
    MsgBox "The end date is not a valid date."
    Exit Sub
End If

    If IsDate(startDate) And IsDate(endDate) Then
        ' Apply the date filter
       With ptTable.PivotFields("Fecha Desde") ' Ensure this is the correct field name
             .ClearAllFilters ' Clear any existing filters
             '.PivotFilters.Add Type:=xlDateBetween, Value1:=startDate, Value2:=endDate
             .PivotFilters.Add2 Type:=xlDateBetween, Value1:=CLng(startDate), Value2:=CLng(endDate)
       End With
        
    Else
        MsgBox "The start date or end date is not a valid date."
    End If
    ' Refresh the PivotTable to apply the date filter
    ptTable.RefreshTable
End Sub


I allready saw this solution at DateBetween, change from a date to a value from a cell
But for some reason its not working for me.
¿Can any body help me please?
 

Excel Facts

Excel Can Read to You
Customize Quick Access Toolbar. From All Commands, add Speak Cells or Speak Cells on Enter to QAT. Select cells. Press Speak Cells.
Hello! Try this:
VBA Code:
Sub CrearTablaDinamicaaaa()
Dim ws_Source As Worksheet
Dim ws_Dest As Worksheet
Dim ptCache As PivotCache
Dim ptTable As PivotTable
Dim rangoDatos As Range
Dim lastRow As Long
Dim ptTableName As String
    
    Set ws_Source = ThisWorkbook.Sheets("Base Ventas Asistidos")
    Set ws_Dest = ThisWorkbook.Sheets("Deporte")
    ptTableName = "TablaDinamicaVentas"

    ' Define range where to place the Pivot Table
    lastRow = ws_Source.Cells(ws_Source.Rows.Count, "A").End(xlUp).Row
    Set rangoDatos = ws_Source.Range("A1:L" & lastRow)

    ' Crear un Pivot Cache
    Set ptCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rangoDatos)
    ' Crete Pivot Table
    Set ptTable = ptCache.CreatePivotTable(TableDestination:=ws_Dest.Range("H40"), TableName:=ptTableName)
    ' Configure Pivot Table
    With ptTable
        'Filter
        .PivotFields("División").Orientation = xlPageField
        .PivotFields("División").Position = 1

        'Filter
        .PivotFields("Fecha Desde").Orientation = xlPageField
        .PivotFields("Fecha Desde").Position = 2

        'Rows
        .PivotFields("SKU").Orientation = xlRowField
        .PivotFields("SKU").Position = 1

        'Create Values of "Ventas" (Sales)
        With .PivotFields("Ventas")
            .Orientation = xlDataField
            .Position = 1
            .Function = xlSum
            .NumberFormat = "#,##0"
            .Name = "Total Ventas"
        End With
    End With
    
    ' Refresh
    ptTable.RefreshTable
    
    'sort
    With ptTable
        .PivotFields("SKU").AutoSort xlDescending, "Total Ventas"
    End With
    
    ' Refresh
    ptTable.RefreshTable
    
    Dim startDate As Long, endDate As Long
    
    If IsDate(ws_Dest.Range("C2").Value) Then
        startDate = CLng(ws_Dest.Range("C2").Value)
        If IsDate(ws_Dest.Range("C3").Value) Then
            endDate = CLng(ws_Dest.Range("C3").Value)
            
            ' Apply the date filter
            With ptTable.PivotFields("Fecha Desde") ' Ensure this is the correct field name
                .ClearAllFilters ' Clear any existing filters
                '.PivotFilters.Add Type:=xlDateBetween, Value1:=startDate, Value2:=endDate
                .PivotFilters.Add2 Type:=xlDateBetween, Value1:=startDate, Value2:=endDate
            End With
            
        Else
            MsgBox "not valid date"
            Exit Sub
    Else
        MsgBox "not valid date"
        Exit Sub
    End If
    
    ptTable.RefreshTable
        
End Sub
 
Upvote 0
To filter a PageField between two dates, I think you'll need to loop through each PivotField. Maybe something like this...

VBA Code:
    If Not IsDate(ws_Dest.Range("C2").Value) Then
        MsgBox "The start date is not a valid date.", vbExclamation
        Exit Sub
    End If
   
    If Not IsDate(ws_Dest.Range("C3").Value) Then
        MsgBox "The end date is not a valid date.", vbExclamation
        Exit Sub
    End If
   
    Dim startDate As Date
    startDate = ws_Dest.Range("C2").Value
   
    Dim endDate As Date
    endDate = ws_Dest.Range("C3").Value
   
    Dim pvtItem As PivotItem
    Dim visibleItemsCount As Long
   
    With ptTable
        .ManualUpdate = True
        With .PivotCache
            .MissingItemsLimit = xlMissingItemsNone
            .Refresh
        End With
        With .PivotFields("Fecha Desde")
            .ClearAllFilters
            If .Orientation = xlPageField Then
                visibleItemsCount = .PivotItems.Count
                For Each pvtItem In .PivotItems
                    If CDate(pvtItem.Name) < startDate Or CDate(pvtItem.Name) > endDate Then
                        If visibleItemsCount > 1 Then
                            pvtItem.Visible = False
                            visibleItemsCount = visibleItemsCount - 1
                        Else
                            MsgBox "No items found.", vbExclamation '(optional)
                            .ClearAllFilters
                            Exit For
                        End If
                    End If
                Next pvtItem
            Else
                .PivotFilters.Add2 Type:=xlDateBetween, Value1:=startDate, Value2:=endDate
            End If
        End With
        .ManualUpdate = False
    End With

Hope this helps!
 
Last edited:
Upvote 0
Solution

Forum statistics

Threads
1,224,814
Messages
6,181,128
Members
453,021
Latest member
Justyna P

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top