简体   繁体   English

Excel数据透视表:无法按日期过滤

[英]Excel pivot table: Can't filter on dates

I need to filter at number of data to show either containing one specific date or with the datefield left blank. 我需要过滤一些数据,以显示包含一个特定日期或日期字段留空。

The macro below works with numbers and text (minor corrections naturally) but I cant make it work with date entries. 下面的宏适用于数字和文本(自然会进行较小的更正),但我无法使其适用于日期输入。 Did not code the date value to avoid any language related issues. 没有对日期值进行编码,以避免任何与语言相关的问题。

Sub YesterdayBlank()
    ActiveSheet.PivotTables("PivotTable2").ClearAllFilters
    Dim yesterday As String
    yesterday = ActiveSheet.Range("F1").Value

With ActiveSheet.PivotTables("PivotTable2").PivotFields("OrderDate")
    For i = 1 To .PivotItems.Count
        If .PivotItems(i) = ("blank") Or .PivotItems(i) = yesterday Then
            .PivotItems(i).Visible = True
        Else
            .PivotItems(i).Visible = False
        End If
    Next i
End With
End Sub

The macro stops at: .PivotItems(i).Visible = False in the first round (i=1) 宏在以下.PivotItems(i).Visible = False停止: .PivotItems(i).Visible = False在第一轮(i = 1)

Any suggestions on this? 有什么建议吗?

My apologies for the delay, and not helping with your issue. 对于造成的延误,我深表歉意,对您的问题没有帮助。 What if you try explicitly defining the PivotTable objects and working with their properties? 如果尝试显式定义数据透视表对象并使用它们的属性该怎么办? This seems to work for me: 这似乎为我工作:

Sub YesterdayBlank()

    Dim yesterday As String
    Dim pt As PivotTable
    Dim pf As PivotField
    Dim pi As PivotItem

    yesterday = ActiveSheet.Range("F1").Value

    Set pt = ActiveSheet.PivotTables("PivotTable2")
    pt.ClearAllFilters

    Set pf = pt.PivotFields("OrderDate")

    For Each pi In pf.PivotItems
        If pi.Value = "(blank)" Or pi.Value = yesterday Then
            pi.Visible = True
        Else
            pi.Visible = False
        End If
    Next

    Set pf = Nothing
    Set pt = Nothing

End Sub

There is also a PivotFilters.Add2 method for the PivotField object. PivotField对象还有一个PivotFilters.Add2方法。 There are various FilterTypes you can add, though it isn't obvious to me that this will help you because you are looking to include blanks within your results. 您可以添加多种FilterType,尽管对我来说这并不明显,因为您希望在结果中包括空白,但这样做不会对您有所帮助。 But I figured I'd share this as it may be useful for you in some other context: 但是我想分享一下,因为它在其他情况下可能对您有用:

pf.PivotFilters.Add2 XlPivotFilterType.xlSpecificDate, Value1:=yesterday

Here is some additional info about this method VBA Filter error 这是有关此方法的一些其他信息VBA过滤器错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM