excelvbadateuntil-loop

How to compare dates in vba for excel


I want to create a Do Until Loop using cells with different dates but it seems as though

"Do Until Range(A1).Value = Range(B1).Value"

doesn't work and only compares the first number in the date (ie. if the date is 6/4/24 and 6/28/24 it thinks the condition has been satisfied)

Any help is appreciated.


Solution

  • If cell A1 contains a date (e.g., 6/4/24) and cell B1 contains a time on the same day (e.g., 6/4/24 8:10:00), CDbl([A1]) and CDbl([B1]) will differ because the latter includes a time component while the former does not.

    Considering that the date format in the cells might vary, you can convert both into the date (as @the7engine's answer) or the string in the same format before performing the comparison.

    Pls try

        If IsDate(Range("A1").Value) And IsDate(Range("B1").Value) Then
            Do Until Format(Range("A1").Value, "yyyymmdd") = Format(Range("B1").Value, "yyyymmdd")
            
            Loop
        End If