Filtering between two dates in pivot table using VBA. UK to US date format issue

后端 未结 2 1527
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 07:33

I have found a workaround for this but if anyone has a cleaner way of doing this I\'d be interested/grateful.

I have two boxes on a spreadsheet, called DateFrom and

相关标签:
2条回答
  • 2020-12-10 07:55

    I found your method truncated the dates to days. This might be what you want, for me I wanted to get down to the hour. I kept getting the error:

    Unable to Set Filter

    Level_Trend_Date_From = 14/05/2020 22:00:00
    Level_Trend_Date_To = 16/05/2020 00:00:00
    Error # 1004 was generated by VBAProject
    Application-defined or object-defined error

    My fix for this was to just clear the filter before I set it:

    Sub Level_Trend_Set_Dates()
    '
    ' Level_Trend_Set_Dates Macro
    ' Recorded and tweaked
    ' Some input from https://stackoverflow.com/questions/22938973/filtering-between-two-dates-in-pivot-table-using-vba-uk-to-us-date-format-issue
    
    '
        On Error GoTo ErrorCatch
    
        Level_Trend_Date_From = Range("Level_Trend_Date_From").Value
        Level_Trend_Date_To = Range("Level_Trend_Date_To").Value
    
        Level_Trend_Date_From = Format(Level_Trend_Date_From, "DD/MM/YYYY  HH:MM")
        Level_Trend_Date_To = Format(Level_Trend_Date_To, "DD/MM/YYYY  HH:MM")
    
        'If filter is not cleared before being set, always get Error# 1004: Application-defined or object-defined error
        ActiveSheet.PivotTables("PivotTable1").PivotFields("Date/Time").ClearAllFilters
    
        ActiveSheet.PivotTables("PivotTable1").PivotFields("Date/Time").PivotFilters.Add _
            Type:=xlDateBetween, _
            Value1:=Level_Trend_Date_From, _
            Value2:=Level_Trend_Date_To
            'Value1:=CLng(Level_Trend_Date_From), _
            'Value2:=CLng(Level_Trend_Date_To)
        GoTo EndSub
    
    
    ErrorCatch:
        ErrorMsg = "Unable to Set Filter" & vbCr
        ErrorMsg = ErrorMsg & vbCr & "Level_Trend_Date_From = " & Level_Trend_Date_From
        ErrorMsg = ErrorMsg & vbCr & "Level_Trend_Date_To = " & Level_Trend_Date_To
        ErrorMsg = ErrorMsg & vbCr & "Error # " & Str(Err.Number)
        ErrorMsg = ErrorMsg & vbCr & "was generated by " & Err.Source
        ErrorMsg = ErrorMsg & vbCr & Err.Description
    
        MsgBox ErrorMsg, vbCritical, "Level_Trend_Set_Dates - Error", Err.HelpFile, Err.HelpContext
    
    EndSub:
    End Sub
    

    Info: UK Date format!

    0 讨论(0)
  • 2020-12-10 08:07

    Indeed, this is strange. I've reproduced your issue with Excel 2007 and German locale settings.

    However, when converting the date values to Longs using CLng, everything works:

    ActiveSheet.PivotTables("Pivot").PivotFields("Date").PivotFilters. _
    Add Type:=xlDateBetween, Value1:=CLng(Range("DateFrom").Value), Value2:=CLng(Range("DateTo").Value)
    
    0 讨论(0)
提交回复
热议问题