You can use the following basic syntax in VBA to compare two dates:
Sub CompareDates()
Dim i As Integer
For i = 2 To 5
If CDate(Range("A" & i)) < CDate(Range("B" & i)) Then
Result = "First Date is Earlier"
Else
If CDate(Range("A" & i)) > CDate(Range("B" & i)) Then
Result = "First Date is Later"
Else
Result = "Dates Are Equal"
End If
End If
Range("C" & i) = Result
Next i
End Sub
This particular example will compare the dates in the corresponding cells in the ranges A2:A5 and B2:B5 and return the result of the date comparisons in the range C2:C5.
Note: The CDate function converts the value in a given cell to a date.
The following example shows how to use this syntax in practice.
Example: Compare Dates in VBA
Suppose we have the following two columns with dates in Excel:
Suppose we would like to compare the dates in each corresponding row and output the results of the date comparison in column C.
We can create the following macro to do so:
Sub CompareDates()
Dim i As Integer
For i = 2 To 5
If CDate(Range("A" & i)) < CDate(Range("B" & i)) Then
Result = "First Date is Earlier"
Else
If CDate(Range("A" & i)) > CDate(Range("B" & i)) Then
Result = "First Date is Later"
Else
Result = "Dates Are Equal"
End If
End If
Range("C" & i) = Result
Next i
End Sub
When we run this macro, we receive the following output:
The results of the date comparisons are now shown in column C.
Additional Resources
The following tutorials explain how to perform other common tasks in VBA:
VBA: How to Sort Sheet by Multiple Columns
VBA: How to Count Number of Rows in Range
VBA: How to Filter a Column