Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 DateTo for use with a Date filter in a pivot table. Both are in the format DD/MM/YYYY. The data feeding into the table is also in this format. The pivot table also returns the dates in the same format. All my settings are in English UK and I've tried this on a separate machine with the same results.

I then use the following code to feed into the pivot table:

ActiveSheet.PivotTables("Pivot").PivotFields("Date").PivotFilters. _
    Add Type:=xlDateBetween, Value1:=Range("DateFrom").Value, Value2:=Range("DateTo").Value

The code reads the two cells as string and then applies this to the pivot table as if they were US format (MM/DD/YYYY). Ridiculous!

This is how I got around it:

I had two more cells looking at these two cells in numeric format and aimed the code at these two cells instead. Not sure about any of you but I would struggle to convert any date into numeric in my head...!

If you have a simplified solution and/or explanation to this utter craziness I'd be much obliged!

like image 466
JJ Moore Avatar asked Apr 08 '14 13:04

JJ Moore


People also ask

How do I fix the date format in a PivotTable?

To change the date format: Right-click a date in the pivot table (not the pivot chart). Click on Field Settings. Change the Number Format to the date format that you want.

Why are dates not grouping in PivotTable filter?

Reason 1: Grouping dates in filters is disabled In Excel, go to File. Click on Options (usually in the left bottom corner of the screen). Go to the Advanced tab in the left pane of the Options window). Scroll down to the workbook settings and set the check at “Group dates in the AutoFilter menu”.

How do I find the difference between two dates in Excel VBA?

DateDiff function in VBA is an inbuilt function in VBA, categorized under the Date and Time function in VBA. We can use this function to get the difference between two dates. This function takes three arguments.


1 Answers

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)
like image 184
MP24 Avatar answered Sep 30 '22 17:09

MP24