我有以下代码来更改数据透视表过滤器,并且我想从当前值中选择上一个月份,但是该代码没有执行任何操作,例如过滤器为“ Sep”,而我想转到“ Oct” 11月,我需要运行宏并将过滤器更改为“ Oct”
Sub PivotChange()
Application.ScreenUpdating = False
Dim WBM As Workbook
Set WBM = Workbooks("MASTER SellOut.xlsx")
Dim SellOut As Worksheet
Set SellOut = WBM.Worksheets("SellOut")
Dim pf As PivotField
Set pf = SellOut.PivotTables("PivotTable2").PivotFields("Date")
Dim pi As PivotField
Dim strMonth As String
' current month as string
strMonth = Format(Date, "mmm")
' refresh pivottable
SellOut.PivotTables("PivotTable2").PivotCache.Refresh
With SellOut.PivotTables("PivotTable2").PivotFields("Date")
On Error Resume Next
' check, if pivotfield exists
Set pi = .PivotField(strMonth)
On Error GoTo 0
If Not pi Is Nothing Then
pi.Visible = True
For Each pi In .PivotField
If pi.Name <> strMonth Then pi.Visible = False
Next pi
End If
End With
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:0)
您的pi
应该是PivotItem
而不是PivotField
:
Dim pi As PivotItem
...
With pf
On Error Resume Next
' check, if pivotfield exists
Set pi = .PivotItems(strMonth)
On Error GoTo 0
If Not pi Is Nothing Then
pi.Visible = True
For Each pi In .PivotItems
If pi.Name <> strMonth Then pi.Visible = False
Next pi
End If
End With