Search code examples
vbaexcelexcel-2007pivot-table

Changing a PivotTable filter by entering a value into a cell


I have looked around for an answer and in fact the code that I am using is from this site. I have the VBA for changing PivotTable filters by inputing a value into a seperate cell like so:

Sub Worksheet_Change(ByVal Target As Range)

If Not Application.Intersect(Target, Sheets("Dashboard").Range("Lane1")) Is Nothing Then
Sheets("Dashboard").PivotTables("PivotTable1").PivotFields("TLEG"). _
    ClearAllFilters
Sheets("Dashboard").PivotTables("PivotTable1").PivotFields("TLEG").CurrentPage _
    = Sheets("Dashboard").Range("Lane1").Value
End If

End SUb

The code works fine. It lets me enter the value and filters accordingly, but when I delete the value in the cell it does not filter "all". Instead, the problem I run into is that a runtime error '1004' is thrown when I delete the value in the cell. I hit end and it gives me the answer. However the error keeps popping up.

I am pretty much a newborn when it comes VBA, so it might be so that I have missed something glaringly obvious.


Solution

  • Sub Worksheet_Change(ByVal Target As Range)
    
        Dim rng As Range
    
        Set rng=Me.Range("Lane1")
        If Not Application.Intersect(Target, rng) Is Nothing Then
            With Sheets("Dashboard").PivotTables("PivotTable1").PivotFields("TLEG")
                .ClearAllFilters
                If Len(rng.Value)>0 Then  .CurrentPage = rng.Value
            End With 
        End If
    
    End SUb