使用vba过滤数据透视表

时间:2016-08-17 19:18:03

标签: excel vba activex pivot-table

我有一个图表,可以从每日数据的数据透视表中选择信息。 我正在尝试创建activeX按钮,以便它可以过滤数据,如ROW LABEL,以查看我的数据在上周和上个月的表现

所以,到目前为止我所拥有的并不起作用的是:

Private Sub weekbtn1_Click()     Dim i As Integer

If weekbtn1 = True Then
i = 0
Do Until Datavalue(date) - i = 42005
With ActiveSheet.PivotTables("Pivotcompsprice").PivotFields("Date")
    .PivotItems DateValue(Date) - i.Visible = False
    i = i + 1
End With    
Loop

i = 0
Do Until i = 7
With ActiveSheet.PivotTables("Pivotcompsprice").PivotFields("Date")
    .PivotItems Datevalue(date) - i.Visible = True
End With
Loop
Else
End If

End Sub

我把这个42005,因为它是我拥有2015年1月1日数据的最后一个日期...我当时认为有可能将所有数据过滤为“false”然后将其变为真我想要,但它不起作用!

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

无法隐藏数据透视表中的所有项目。你总是要留下至少一个可见的。

如果您使用VBA来利用内置的日期过滤器功能,那将会更快更容易,即: DateFilter

这是一个示例文件,我这样做: https://1drv.ms/x/s!Ah_zTnaUo4DzjhezQ3OTq9tq1APC

请注意,此功能仅适用于RowFields或ColumnFields。所以我的代码不适用于PageFields。

这是一个通用例程,可让您选择要在其上过滤枢轴字段的间隔类型和间隔时间段,以及选择要向前/向后计数的日期。

Sub Pivots_FilterPeriod(sInterval As String, _
                        lNumber As Long, _
                        Optional vRelativeTo As Variant, _
                        Optional pf As PivotField)

    'Programmer:        Jeff Weir
    'Contact:           weir.jeff@gmail.com
    'Description:       Lets you programatically filter a Pivot RowField or ColumnField by specifying
    '                   an interval type (e.g. days, weeks, months, quarters, years)
    '                   as well as an interval count (e.g. 7, -7)
    '                   If the optional vRelativeTo field is left blank, it counts back/foward from
    '                   the youngest/oldest item depending on whether lNumber is positive/negative
    '                   It leverages off the inbuilt DateFilters functionality, and as such does not
    '                   work on RowFields.


    Dim dteDateAdd As Date
    Dim dteFrom As Date
    Dim dteTo As Date

    On Error GoTo errhandler

    If pf Is Nothing Then
        On Error Resume Next
        Set pf = ActiveCell.PivotField
        On Error GoTo errhandler
        If pf Is Nothing Then GoTo errhandler
    End If

    With pf
        If .DataType = xlDate _
            And .Orientation <> xlPageField _
            And .Orientation <> xlDataField Then

            If IsMissing(vRelativeTo) Or vRelativeTo = "" Then
                .AutoSort xlAscending, "Date"
                If lNumber > 0 Then
                    vRelativeTo = .PivotItems(1)
                Else
                    vRelativeTo = .PivotItems(.PivotItems.Count)
                End If
            End If

            Select Case UCase(sInterval)
                Case "D", "DD", "DDD", "DDDD", "DAY", "DAYS": sInterval = "d"
                Case "W", "WW", "WWW", "WWWW", "WEEK", "WEEKS": sInterval = "ww"
                Case "M", "MM", "MMM", "MMMM", "MONTH", "MONTHS": sInterval = "m"
                Case "Q", "QQ", "QQQ", "QQQQ", "QUARTER", "QUARTERS": sInterval = "q"
                Case "Y", "YY", "YYY", "YYYY", "YEAR", "YEARS": sInterval = "yyyy"
            End Select

            dteDateAdd = DateAdd(sInterval, lNumber, vRelativeTo)
            If lNumber > 0 Then
                dteDateAdd = dteDateAdd - 1
            Else
                dteDateAdd = dteDateAdd + 1
            End If

            If dteDateAdd < vRelativeTo Then
                dteFrom = dteDateAdd
                dteTo = vRelativeTo
            Else
                dteFrom = vRelativeTo
                dteTo = dteDateAdd
            End If

            With Application
                .ScreenUpdating = False
                .EnableEvents = False
                .Calculation = xlCalculationManual
            End With

            .ClearAllFilters
            .PivotFilters.Add2 _
                Type:=xlDateBetween, _
                Value1:=CStr(dteFrom), _
                Value2:=CStr(dteTo)
        End If
    End With

errhandler:
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = xlCalculationAutomatic
    End With

End Sub

这里有一些截图,展示了它在实践中的外观,使用不同的参数。

这显示了如何根据最新数据过滤最近5天:

Last 5 days from most recent data

通过改变标志,我们必须要从记录中最早的数据开始前5天:

First 5 days from oldest records

如果在RelativeTo字段中指定实际日期,它将从那里向前/向后计数,具体取决于Number参数是正数还是负数。这是我今天写这篇文章后的第5天:

Next 5 days from today

...这是最近5天:

enter image description here

它可以让您指定是否需要天,周,季,月或年。例如,这是从最近的记录中算起的最后两周:

enter image description here

我在这里使用一个Worksheet_Change事件来触发它,但如果你愿意,你可以把它连接到一个按钮,然后输入你想要的参数。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim bContinue As Boolean
    If Not Intersect(Target, Range("Interval")) Is Nothing Then bContinue = True
    If Not Intersect(Target, Range("Number")) Is Nothing Then bContinue = True
    If Not Intersect(Target, Range("RelativeTo")) Is Nothing Then bContinue = True
    If bContinue Then Pivots_FilterPeriod [Interval], [Number], [RelativeTo], Sheet1.PivotTables(1).PivotFields("Date")

End Sub