问题
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:
But the filter applied shows 0 results:
And here is the odd part, the filter applied tells me that I apparently filtered between the full value without a decimal comma.
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, as1: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.
来源:https://stackoverflow.com/questions/58199518/autofilter-datetime-values-local-decimal-point-issue