无法设置 PivotItem class 的可见 属性

Unable to set Visible property of the PivotItem class

我编写了一个 VBA 脚本来遍历多个数据透视表并根据用户输入更改月份。它在测试期间工作了几次,但现在它突然抛出了标题中的错误。我不明白为什么。

Sub change_pivot()
Dim Wb As Workbook
Dim Ws As Worksheet:
Dim p As PivotTable:
Dim f As PivotField:
Dim i As PivotItem, s$
Dim i2 As PivotItem
Dim Message, Title, Default, MyValue
Dim curr_year As Integer
Dim pvt_tables As Variant

Set Wb = ThisWorkbook
Set Ws = Wb.Worksheets("Sheet1")
Set p = Ws.PivotTables("PivotTable1")
Set f = p.PivotFields("Month")
Set g = p.PivotFields("Year")

curr_year = year(Date)

pvt_tables = Array("1", "10", "3", "12", "11", "4", "5")

Message = "Enter a month value in the folowing format: (01)"
Title = "Insert Month"    ' Set title.
Default = "01"    ' Set default.
' Display message, title, and default value.
s = InputBox(Message, Title, Default)



Message = "Is the year correct?"
Title = "check year"    ' Set title.
Default = curr_year   ' Set default.
' Display message, title, and default value.
y = InputBox(Message, Title, Default)

        
For Each x In pvt_tables
    Set p = Ws.PivotTables("PivotTable" & x)
    Set f = p.PivotFields("Month")


' change months
    With f
        For Each i In .PivotItems
            If i.Name <> s Then
                i.Visible = False
            Else:
                i.Visible = True
            End If
        Next
    End With
Next

它不适用于数组上的循环,没有它也是如此。知道我做错了什么吗?

您必须至少有一个 PivotItem 可见 - 当您尝试隐藏最后一个可见的时会出现该错误(因此它会失败,除非您显示的项目出现在 之前 你试图隐藏的最后一个)。

尝试这样的事情:

Sub change_pivot()
    Dim Wb As Workbook
    Dim Ws As Worksheet
    Dim p As PivotTable
    Dim f As PivotField
    Dim i As PivotItem, mnth As String, yr As String
    Dim i2 As PivotItem
    Dim pvt_tables As Variant, x, pi As PivotItem
    
    Set Wb = ThisWorkbook
    Set Ws = Wb.Worksheets("Sheet1")
    
    mnth = InputBox("Enter a month number", "Month", "01")
    If Len(mnth) = 1 Then mnth = "0" & mnth 'add leading zero if not entered
    
'    yr = InputBox("Is the year correct?", _
'                 "Insert Month", Year(Date))
    
    pvt_tables = Array("1", "10", "3", "12", "11", "4", "5")
    
    For Each x In pvt_tables
        Set p = Ws.PivotTables("PivotTable" & x)
        With p.PivotFields("Month")
            On Error Resume Next
            Set pi = .PivotItems(mnth) 'check the entered item exists
            On Error GoTo 0
            If Not pi Is Nothing Then
                pi.Visible = True         'first set desired item visible
                For Each i In .PivotItems 'then hide the others
                    If i.Name <> mnth Then i.Visible = False
                Next
            Else
                MsgBox "No item exists for '" & mnth & "'"
            End If
        End With
    Next

End Sub