AutoFilter DateTime values - Local decimal point issue

Viewed 239

Background

While I was trying to solve a problem for another user I ran into, seemingly, a local issue.

Imagine some very simple sample data (being true date-time values):

| DateTimeVals   |
|----------------|
| 1-1-2019 01:00 |
| 2-1-2019 01:00 |
| 3-1-2019 01:00 |
| 4-1-2019 01:00 |
| 5-1-2019 01:00 |

It doesn't need to be more complicated to show you the issue at hand. Let's imagine we would want to filter on 3-1-2019 01:00 (3rd of Jan). Simply using:

Range("A1").AutoFilter Field:=1, Criteria1:="3-1-2019 01:00"

Works just fine, A hardcoded string variable does work, but I thought about something more dynamic filtering on the true numeric values as below.


Code

Sub test()

Dim SearchNum As Double: SearchNum = DateValue("3-1-2019") + TimeValue("1:00")
Range("A1").AutoFilter Field:=1, Criteria1:=">=" & SearchNum, Operator:=xlAnd, Criteria2:="<=" & SearchNum

End Sub

Keeping an eye out on this variable through WATCHES shows the following:

enter image description here

But the filter applied shows 0 results:

enter image description here

And here is the odd part, the filter applied tells me that I apparently filtered between the full value without a decimal comma.

enter image description here

Manually adding the comma to this number made the number turn into a formatted date/time value. But no result is shown.


Workaround

I've found a way around it using the following code:

Sub test()

Dim str As String: str = DateSerial(2019, 1, 3) & " " & Format(TimeSerial(1, 0, 0), "hh:mm")
Range("A1").AutoFilter Field:=1, Criteria1:=str

End Sub

Question

While I did read about how MS might have neglected the AutoFilter, I'm thinking my issue described must have something to do with local settings. How would VBA insert the criteria as a whole number? And how to avoid it? Any other way around than my workaround (or a helper column)?


Note:

  • Changing the long number by manually inserting a comma changed the value in the correct date/time formatted value.
  • Working with a TimeValue is prone to floating point errors, as 1:00 has much more decimals then the shown ones. Inserting the full numeric value in a string variable solved the disappearance of the comma and showed a formatted date/time value, however no result is shown.
1 Answers

Have you tried to ROUND() pior to giving the varaibles?

As you don't need the seconds in your filter you can make a workaround by rounding and that maybe gives "exact" values for finding within the filter.

Related