4

我正在尝试选择一个报告过滤器,在本例中为加拿大。这意味着必须使其余部分不可见。此代码可以正常工作:

Public Sub FilterPivotTable()

    With ActiveSheet.PivotTables("Epidemiology").PivotFields("COUNTRY")

        .PivotItems("Canada").Visible = True
        .PivotItems("USA").Visible = False
        .PivotItems("Germany").Visible = False
        .PivotItems("France").Visible = False

    End With

End Sub

但是,当我们将其他国家添加到我们的“流行病学”数据透视表中时,我正在尝试做准备,所以我尝试了一个 for 循环。此代码不起作用:

With ActiveSheet.PivotTables("Epidemiology").PivotFields("COUNTRY")

    .PivotItems("Canada").Visible = True

    For Each Pi In .PivotItems
        If Pi.Value = "CANADA" Then
            Pi.Visible = True
        Else
            Pi.Visible = False
        End If
    Next Pi

End With

它给了我一个Pi.Visible = False在线错误。我得到的错误是Run-time error '1004': Unable to set the Visible property of the PivotItem class

为什么它不能在 for 循环中工作?!

令人沮丧的是,我在网上找到的所有示例都使用类似的语法。(有些使用索引,但我尝试过并得到了同样的错误。)

4

2 回答 2

7

这是你正在尝试的吗?

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
于 2013-01-17T21:09:14.670 回答
0

在可透视过滤器中,您必须始终选择至少一项。即使您打算稍后在代码中选择一个。

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

请注意,如果您尝试不选择任何内容,例如 opt 1 = "" 和 opt2 = "" 和 opt3 = "",您将遇到同样的错误:您必须至少选择一个枢轴项目。

于 2013-01-30T17:01:59.600 回答