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

时间:2017-02-15 16:38:05

标签: excel vba filtering pivot-table

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

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

感谢您的帮助!

1 个答案:

答案 0 :(得分: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