将excel切片器设置为今天的日期

时间:2015-10-26 12:37:58

标签: excel vba

我有一个连接到pivottable和两个pivotcharts的日期切片器。我希望这个切片器能够自动过滤到今天的日期。我想我必须使用VBA代码执行此操作,因此我用Google搜索并从以下代码中找到以下代码: https://social.msdn.microsoft.com/Forums/office/en-US/2542f1dc-ca62-4ea4-b686-bfa78b53c699/automatically-select-last-available-date-slicer-value-when-opening-workbook?forum=exceldev

Private Sub Workbook_Open()
    Dim today As Date
    today = Now
    Dim todayString As String
    todayString = Format$(today, "d mmm yyyy")

    Dim item As SlicerItem

    For Each item In ThisWorkbook.SlicerCaches("Date Slicer").SlicerItems
        If item.Name = todayString Then
            item.Selected = True
        Else
            item.Selected = False
        End If
    Next item

    ThisWorkbook.RefreshAll

End Sub

但是,当我应用此代码时,出现以下错误:

Run-time error '2004':
Application-defined or object-defined error

有没有人有工作代码来操纵日期切片器,或者知道为什么这不起作用?

2 个答案:

答案 0 :(得分:1)

名称Date Slicer可能不正确。如果我录制一个宏并选择一个日期,然后查看我的代码,我得到这个:

With ActiveWorkbook.SlicerCaches("Slicer_Date")
    .SlicerItems("1/1/2015").Selected = False
    .SlicerItems("10/5/2015").Selected = False
    .SlicerItems("10/26/2015 13:46").Selected = False
End With

因此切片器的对象名称在我的宏代码Slicer_Date中。尝试录制宏以查找切片器的对象名称。然后在上面的代码中使用该名称。

修改评论

我已将代码更改为适合我的日期格式:

Sub SlicerSelectToday()

    Dim today As Date
    today = Now
    Dim todayString As String
    todayString = Format$(today, "m/d/yyyy") ' I have US date

    Dim item As SlicerItem

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

    ThisWorkbook.RefreshAll

End Sub

sub正在运行,并在切片器中选择今天的日期。

答案 1 :(得分:0)

@ lars-rotgers对于没有pivottable的情况,回答是100_%正确,但对于有可转换表的情况,这是正确的解决方案:

Sub SetTodaysDate()

    Dim today As Date
    today = Now
    Dim todayString As String
    todayString = Format$(today, "dd.mm.yyyy")
    ThisWorkbook.SlicerCaches("Slicer_Date").ClearManualFilter
    ActiveWorkbook.SlicerCaches("Slicer_Date").VisibleSlicerItemsList = Array( _
        "[Period].[Date].&[" & todayString & "]")
End Sub

[期间]。[日期]必须与您的多维数据集中的维度等对应。