将切片器设置为昨天的日期

时间:2015-02-06 19:42:58

标签: excel-vba vba excel

我需要设置一个切片器来激活昨天日期的条目。我已将下面的代码放在一起,它会根据我的需要停用/激活和交互。缺点是它不断突出显示它不应该的字段(参见:在适当的一天之前几天的条目)。

Private Sub GroundHogDay()

Dim ydate As Date
ydate = Today - 1
Dim YDateString As String
YDateString = Format$(ydate, "mm/dd/yyyy")

Dim item As SlicerItem

For Each item In ThisWorkbook.SlicerCaches("Slicer_Date").SlicerItems
    If item.Name > YDateString Then
        item.Selected = True
    Else
        item.Selected = False
    End If
Next item

ThisWorkbook.RefreshAll

End Sub

任何和所有帮助将不胜感激。

编辑:我已经尝试过 - 没有效果。

Today - 2
Now - 1
Now - 2

1 个答案:

答案 0 :(得分:1)

最终找到答案:

Sub GroundHogDay()
Dim today As Date
today = Now - 2
Dim todayString As String
todayString = Format$(today, "m/d/yyyy")

Dim item As SlicerItem

ThisWorkbook.SlicerCaches("DATE").ClearManualFilter
With ActiveWorkbook.SlicerCaches("DATE")
'earliest data available in the data 
.SlicerItems("1/1/2013").Selected = True
.SlicerItems("(blank)").Selected = False
End With

For Each item In ThisWorkbook.SlicerCaches("DATE").SlicerItems

If item.Name = todayString Then
item.Selected = True
Else
item.Selected = False
End If
Next item

ThisWorkbook.RefreshAll

End Sub