如何在数据透视表中过滤列值

时间:2019-02-12 04:29:37

标签: excel vba excel-2010

我正在尝试过滤枢轴代码,以便仅显示value = 2的列。我该如何编码?

尽管我手动尝试了筛选,方法是选择一个与表格接壤的单元格(但位于枢轴区域之外),然后从“数据”选项卡中选择“筛选器”。但是,从操作上讲,这是不可持续的,我想创建一个代码来实现自动化。

Sub getpivotUI2()



    ' getpivotUI2 Macro

    ' Create PivotTable from Task_Sheet to filter duplicate bill (UI2)



    Dim P2Sheet As Worksheet, TSheet As Worksheet

    Dim P2Cache As PivotCache

    Dim P2Table As PivotTable

    Dim P2Range As Range

    Dim L2Row As Long, L2Col As Long



    ' Declaring the variables above



    Set TSheet = ThisWorkbook.Worksheets("Task_Sheet")

    Set P2Sheet = ThisWorkbook.Worksheets("pivot_UI2")



    With TSheet

        L2Row = .Cells(.Rows.Count, 1).End(xlUp).Row

        L2Col = .Cells(4, .Columns.Count).End(xlToLeft).Column



        Set P2Range = .Range(.Cells(4, 1), .Cells(L2Row, L2Col)) ' set the data source of the Pivot-Cache

    End With



    'Macros above determine where the cursor is referenced



    P2Sheet.Cells.Delete 'Removing all previous data the pivotTable worksheet



    ' set the Pivot-Cache object

    Set P2Cache = ActiveWorkbook.PivotCaches.Add(xlDatabase, P2Range.Address(0, 0, xlA1, xlExternal))



    ' set the Pivot-Table object

    Set P2Table = P2Sheet.PivotTables.Add(PivotCache:=P2Cache, TableDestination:=P2Sheet.Range("A3"), TableName:="PivotTableUI2")



    'Macros above create a pivot cache and address to insert the new pivot table



    ' ~~~ For Debug Only ~~~

    Dim PTFld As PivotField



    For Each PTFld In P2Table.PivotFields

        Debug.Print PTFld.Name

    Next PTFld



    With P2Table.PivotFields("UI2")

        .Orientation = xlRowField

        .Position = 1

    End With



    With P2Table.PivotFields("Count_UI2")

    .Orientation = xlDataField

    .Function = xlCount

    .Name = "Count of UI2"

    .Position = 1

    End With



    With P2Table.PivotFields("R Patient" & Chr(10) & "Count")

    .Orientation = xlDataField

    .Function = xlCount

    .Name = "Count of R Patient"

    .Position = 2

    End With



    With P2Table.PivotFields("PR Patient" & Chr(10) & "Count")

    .Orientation = xlDataField

    .Function = xlCount

    .Name = "Count of PR Patient"

    .Position = 3

    End With



'Macros above inserts a row field and data field in the pivot table



    With P2Table.PivotFields("data")

    .Orientation = xlColumnField

    End With



'Macros above is to arrange the data in the datafield in columns







End Sub







Sub filterUI2pivot()



Dim UI2PT As PivotTable

Set UI2PT = ActiveSheet.PivotTables("PivotTableUI2")

With UI2PT

    .ClearAllFilters

    .PivotFields("Count of UI2").PivotFilters.Add Type:=xlValueEquals, Value1:=2  ßRun-time error 1004 <> Application-defined or object-defined error

End With



End Sub

I expect an output where pivot table rows are strunk to show items that has a value of 2 in the datafield.

    enter code here

0 个答案:

没有答案