【发布时间】:2021-03-24 17:55:35
【问题描述】:
我编写了一个 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
它不适用于数组上的循环,没有它也一样。任何想法我做错了什么?
【问题讨论】:
-
您在循环中执行此操作
Set p = Ws.PivotTables("PivotTable" & x)但随后您不使用p? -
p 在 f 中“包含”。我本可以在 ine 步骤中完成此操作,但出于某种原因我使用了 2
-
但是 f 只指向
PivotTables("PivotTable1").PivotFields("Month")稍后更改p不会自动更改f... -
好吧,我可能不明白。我编辑了上面的代码。出于某种原因,它曾经工作过一次,但是当我第二次尝试时,我又遇到了同样的错误......我必须在哪里再次使用 p?
标签: arrays excel vba date pivot