VBA Excel - 自动过滤基于其他字段值的多个过滤器

时间:2017-06-16 10:33:19

标签: vba excel-vba excel

我正在尝试根据另一个工作表上的单元格值自动过滤数据透视表。需要做什么? 我在表A上有2个值(C13 =位置,M3 =材料) 基于这两个值,工作表B上的数据透视表“库存”应相应地自动过滤(单元格M1中的过滤器位置和单元格M2中的过滤器材料)

如果表A中的值不在过滤器中(因为没有数据),我应该得到一个空的数据透视表(没有弹出错误)。

我从这个论坛中找到的示例代码开始,但这些只包括单元格值和过滤器在同一张纸上,只有一个过滤器。当我添加另一个过滤器时,我不断收到错误。

感谢您的帮助!

从此开始:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If Intersect(Target, Range("????")) Is Nothing Then Exit Sub

Dim pt As PivotTable 
Dim Field As PivotField
Dim Field2 As PivotField
Dim NewCat As String
Dim NewCat2 As String

Set pt = Worksheets("B").PivotTables("overview")
Set Field = pt.PivotFields("location")
NewCat = Worksheets("A").Range("C13").Value


Set pt = Worksheets("B").PivotTables("overview")
Set Field2 = pt.PivotFields("material")
NewCat2 = Worksheets("A").Range("M3").Value
With pt
Field.ClearAllFilters
Field.CurrentPage = NewCat
pt.RefreshTable
End With

With pt
Field2.ClearAllFilters
Field2.CurrentPage = NewCat2
pt.RefreshTable
End With

End Sub 

现在有了这个:

Private Sub Worksheet_Change(ByVal Target As Range)

Dim KeyCells As Range
Dim pt As PivotTable
Dim Field As PivotField
Dim Field2 As PivotField
Dim NewCat As String
Dim NewCat2 As String

Set KeyCells = Range("T1:T2")

    If Application.Intersect(KeyCells, Range(Target.Address)) _
       Is Nothing Then

        Exit Sub
    End If

Set pt = Worksheets("stock").PivotTables("overview")
Set Field = pt.PivotFields("location")
With pt
Field.ClearAllFilters
End With

Set pt = Worksheets("stock").PivotTables("overview")
Set Field2 = pt.PivotFields("material")
With pt
Field2.ClearAllFilters
End With

Set pt = Worksheets("stock").PivotTables("overview")
NewCat = Worksheets("stock").Range("T1").Value
With pt
Field.CurrentPage = NewCat
pt.RefreshTable
End With

Set pt = Worksheets("stock").PivotTables("overview")
NewCat2 = Worksheets("stock").Range("T2").Value
With pt
Field2.CurrentPage = NewCat2
pt.RefreshTable
End With
End Sub

0 个答案:

没有答案