使用2个单元格值过滤数据透视表

问题描述 投票:1回答:1

我正在尝试根据两个不同过滤器的两个单元格值过滤数据透视表。我找到了能够适应我所拥有的一个单元的代码,我不确定如何集成下面单元格中的第二个(参见我在下面修改的代码)

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

'This line stops the worksheet updating on every change, it only updates when cell
'H6 or H7 is touched
If Intersect(Target, Range("H6:H7")) Is Nothing Then Exit Sub

'Set the Variables to be used
Dim pt As PivotTable
Dim Field As PivotField
Dim NewCat As String

'Here you amend to suit your data
Set pt = Worksheets("Sheet1").PivotTables("PivotTable1")
Set Field = pt.PivotFields("Category")
NewCat = Worksheets("Sheet1").Range("H6").Value

'This updates and refreshes the PIVOT table
With pt
Field.ClearAllFilters
Field.CurrentPage = NewCat
pt.RefreshTable
End With

End Sub

谢谢您的帮助!

excel vba filtering pivot-table
1个回答
0
投票

经过深思熟虑后,我想出了我的问题。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

'This line stops the worksheet updating on every change, it only updates when cell
'H6 or H7 is touched
If Intersect(Target, Range("H6:H7")) Is Nothing Then Exit Sub

'Set the Variables to be used
Dim pt As PivotTable
Dim Field1 As PivotField
Dim Field2 As PivotField
Dim NewCat1 As String
Dim NewCat2 As String

'Here you amend to suit your data
Set pt = Worksheets("Sheet1").PivotTables("PivotTable1")
Set Field1 = pt.PivotFields("Category1")
Set Field1 = pt.PivotFields("Category2")
NewCat1 = Worksheets("Sheet1").Range("H6").Value
NewCat2 = Worksheets("Sheet1").Range("H7").Value

'This updates and refreshes the PIVOT table
With pt
Field1.ClearAllFilters
Field1.CurrentPage = NewCat1
Field2.ClearAllFilters
Field2.CurrentPage = NewCat2
pt.RefreshTable
End With

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.