Looping through report filters to change visibility doesn't work

后端 未结 2 1239
死守一世寂寞
死守一世寂寞 2020-12-21 02:42

I\'m trying to select one report filter, in this case Canada. That means the rest must be made invisible. This code works without issue:

Public Sub FilterPiv         


        
相关标签:
2条回答
  • 2020-12-21 03:07

    In a pivottable filter, you must have at least one item selected at all times. Even if you intend to select one later in the code.

    With Pt.PivotFields("COUNTRYSCENARIO")
    
     ' Sets all filters to true, resetting it.
     .ClearAllFilters
    
     ' This is necessary if you want to select any options
     ' other than "All Pivot Items = Visible" and 
     ' "OnlyOneSpecificPivotItem = Visible"
     .EnableMultiplePageItems = True
    
     If .PivotItems.Count > 0 Then
    
         ' goofy but necessary
         Set firstPi = .PivotItems(1)
    
             For Each Pi In .PivotItems                                
    
                 ' Make sure that that first pivot item is visible.
                 ' It gets mad if it's already visible and you
                 ' set it to visible with firstPi.Visible = True
                 ' ...pretty silly
    
                 If firstPi.Visible = False Then firstPi.Visible = True
    
                 ' Don't loop through firstPi
                 If Pi.Value <> firstPi.Value Then
    
                     If Pi.Value = opt1 Or Pi.Value = opt2 Or Pi.Value = opt3 Then
                         Pi.Visible = True
    
                     ElseIf Pi.Visible = True Then
    
                         Pi.Visible = False
    
                     End If
    
                 End If
    
              Next Pi
    
              ' Finally perform the check on the first pivot item   
              If firstPi = opt1 Or firstPi = opt2 Or firstPi = opt3 Then
                  firstPi.Visible = True
              Else
                  firstPi.Visible = False
              End If
           End If
    End With
    

    Notice that if you try to select nothing, e.g. opt 1 = "" and opt2 = "" and opt3 = "", you will have that same error: you must have at least one pivot item selected.

    0 讨论(0)
  • 2020-12-21 03:16

    Is this what you are trying?

    Sub Sample()
        Dim Pi As PivotItem
    
        With ActiveSheet.PivotTables("Epidemiology").PivotFields("COUNTRY")
    
            .PivotItems("Canada").Visible = True
    
            For Each Pi In .PivotItems
                If UCase(Pi.Value) = "CANADA" Then
                    Pi.Visible = True
                Else
                    Pi.Visible = False
                End If
            Next Pi
        End With
    End Sub
    
    0 讨论(0)
提交回复
热议问题