无法设置 pivotItem Class 的可见性 属性

Unable To set The Visibility property of the pivotItem Class

我有一个 Excel 文件,在按名称过滤时创建了数据透视表和两个过滤器(主要供应商名称和日期)

我想过滤每个主要供应商名称,一次只应选择过滤器中的一个值,其他应取消选择 我试过这个代码。

Dim ws As Worksheet
    Set ws = Worksheets("3rd Pivot")

    Dim pt As PivotTable
    Set pt = ws.PivotTables("secondpivot_table")
    
    Dim pF As PivotField

    Set pF = pt.PivotFields("Principal Vendor Name")

    pF.EnableMultiplePageItems = True
    pF.CurrentPage = "(All)"
    
    For i = 1 To pF.PivotItems.Count

    pt.PivotCache.MissingItemsLimit = xlMissingItemsNone
     
    pt.PivotCache.Refresh
    k = i
    For j = 1 To pF.PivotItems.Count
    pt.PivotCache.MissingItemsLimit = xlMissingItemsNone
    pt.PivotCache.Refresh
  
    If i = j Then
    pF.PivotItems(k).Visible = True
    Else
    pF.PivotItems(j).Visible = False
    End If
    Next j

但是这行显示错误 pF.PivotItems(j).可见=假 “无法设置 pivotItem Class 的可见性 属性”

像这样:

Sub Tester()

    Dim ws As Worksheet, pt As PivotTable, pF As PivotField
    Dim i As Long, n As Long
    
    Set ws = Worksheets("3rd Pivot")
    Set pt = ws.PivotTables("secondpivot_table")
    Set pF = pt.PivotFields("Principal Vendor Name")

    pF.EnableMultiplePageItems = True
    pF.CurrentPage = "(All)"
    
    For i = 1 To pF.PivotItems.Count
        
        pF.PivotItems(i).Visible = True 'set the visible one first
        'then hide the rest
        For n = 1 To pF.PivotItems.Count
            If n <> i Then pF.PivotItems(n).Visible = False
        Next n
    
    Next i

End Sub