【问题标题】:If Monday then filter the last 3 days, if not, filter the last day如果是星期一,则过滤最后 3 天,如果不是,则过滤最后一天
【发布时间】:2018-03-14 05:54:01
【问题描述】:

尝试构建一些东西来检查今天是什么日子,然后基于此过滤数据透视表。如果今天是星期一,则需要在过去 3 天(星期五/星期六/星期日)的“报告日期”上过滤枢轴。如果是其他日期,则只需过滤前一天的“报告日期”即可。

If Weekday(Now(), vbMonday) = 1 Then
    rDate = Format(Now() - 3, "dd/mm/yyyy")
Else: rDate = Format(Now() - 1, "dd/mm/yyyy")
End If

但是我不知道如何使用这个变量来创建过滤器。 有人可以帮忙吗?

谢谢!

【问题讨论】:

    标签: vba variables filter pivot


    【解决方案1】:

    试试下面的代码,代码的 cmets 里面的解释:

    Option Explicit
    
    Sub FilterPivot()
    
    Dim PvtTbl As PivotTable
    Dim DateStart As Double, DateFinish As Double
    Dim PvtFld As PivotField
    Dim PvtItm As PivotItem
    
    Application.ScreenUpdating = False
    
    ' set the Pivot-Table Object
    ' Modify "Sheet1" to where your Pivot-Table lies, and "PivotTable1" to your Pivot-Table name
    Set PvtTbl = Worksheets("Sheet1").PivotTables("PivotTable1")
    
    ' set the Pivot Field Object
    ' Modify "Date" to the Pivot Field's name you want to filter
    Set PvtFld = PvtTbl.PivotFields("Date")
    
    If Weekday(Now(), vbMonday) = 1 Then
        DateStart = DateAdd("d", -3, Date) ' the first date in the range of dates to display (current date -3 days)
    Else
        DateStart = DateAdd("d", -1, Date) ' the first date in the range of dates to display (current date -1 day)
    End If
    DateFinish = DateAdd("d", -1, Date) ' the last date in the range of dates to display (current date -1 day)
    
    PvtFld.ClearAllFilters ' clear all existing filters
    For Each PvtItm In PvtFld.PivotItems ' loop through items in PivotField
        ' check if the value of the date is between the scanned ranges of dates (1 day, or 3 days)
        If CDbl(DateValue(PvtItm.Name)) >= DateStart And CDbl(DateValue(PvtItm.Name)) <= DateFinish Then
            PvtItm.Visible = True
        Else
            PvtItm.Visible = False
        End If
    Next PvtItm
    
    Application.ScreenUpdating = True
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2022-07-06
      • 1970-01-01
      • 2020-03-04
      • 1970-01-01
      • 2017-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      相关资源
      最近更新 更多