尝试构建一些可以检查今天是什么日子的内容,然后基于此过滤数据透视表。如果今天是星期一那么,需要在过去3天(星期五/星期六/星期日)的“报告日期”过滤枢轴。如果是其他任何一天,“报告日期”只需要在前一天进行过滤。
If Weekday(Now(), vbMonday) = 1 Then
rDate = Format(Now() - 3, "dd/mm/yyyy")
Else: rDate = Format(Now() - 1, "dd/mm/yyyy")
End If
但是我不知道如何使用这个变量来创建过滤器。 有人可以帮忙吗?
谢谢!
答案 0 :(得分:0)
尝试下面的代码,代码注释中的解释:
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