Solved Comparing Dates and String

Saphirah

Active member
Local time
Today, 06:50
Joined
Apr 5, 2020
Messages
163
Hello everyone,

in my VBA code i have 2 variables. VDate as Date and VString as String.

VString = "22.2"
VDate = 22.02.2021

I am now comparing those 2 in an if and the code inside the if is executed.

Code:
If VString = VDate Then
    Debug.Print("Hello World")
End If

Output: Hello World

Is this intended behaviour? This does not make sense for me. Can someone explain this please?
Thank you very much in advance :)
 
Last edited:
put Option Explicit to your Code.
you did not Declare them properly.
if you have declared them, then there would be error on:

VDate = "22.02.2021"

To Declare your variable:

Dim VDate As Date
Dim VString As String
VString = "22.2"
VDate = "22.02.2021" <== you will got error here.
 
Sorry, i should have been more clear here. This was just an example. My actual code looks different from what i have written on top, but uses some custom functions, so i can not just copy paste my original code here.

I have Option Explicit in my code.
I do have a date value that is coming from another function, and i can be 100% sure that VDate is a date, and that VString is a String.

Back to my original question, when i compare the string "22.2" with the date 22.02.2021 this returns true.
Why is this happening?
 
Last edited:
is your Date separator a Dot (.)?

compare it in immediate window:

?"22.2" = #22.02.2021#

i think the correct separator is "/" and either in mm/dd/yyyy or yyyy/mm/dd format:


?"22.2" = #02/02/2021#
?"22.2" = #2021/02/22#
 
That's Access trying to be helpful and interpreting the dates (assuming the dot is your date separator.
I expect it will return false with e.g. 22.2 & #22.02.2020# or with e.g. 8.2 & #08.02.2021#
Can you see why that is.
 
That's Access trying to be helpful and interpreting the dates (assuming the dot is your date separator.
I expect it will return false with e.g. 22.2 & #22.02.2020# or with e.g. 8.2 & #08.02.2021#
Can you see why that is.
Thank you. So access is trying to interpret the string as a date, even though a big chunk of it is missing? This is interesting... Then if i want my comparison to work correctly i just have to convert my Date to a String and then compare those two...

CStr(VDate)=VString is working as intended..

I will mark the thread as solved.
 
Whenever you compare two fields of unequal data types, you run the risk of your compiler or interpreter regardless of language platform, making the wrong assumption. Defensive programming is always proactive in these situations. You force the conversion you want.
 

Users who are viewing this thread

Back
Top Bottom