'How can I compare two dates in Excel VBA?
I'm working on a school project to compare if date1 is equal to date2 - 1 (date1 is one day earlier than date2).
date2 is located one cell below date1. This is will be placed in an if/else statement where the comparison will return a Boolean.
This is the code that I am working on,
Sub someLoop()
Dim night As Long
night = 1
Dim c As Long
Dim max_rows As Long
max_rows = UsedRange.Rows.Count
For c = 2 To max_rows
Range("A" & c).Select
If ActiveCell.Value = ActiveCell.Offset(1, 0).Value2 - 1 Then
night = night + 1
Else
ActiveCell.Offset(0, 2).SetValue = night
night = 1
End If
Next c
End Sub
Solution 1:[1]
Dates in Excel can be treated just like numbers.
So, if [A1] has 28-May-14 and [A2] has 29-May-14, then you can just write the formula: =(A1=A2-1)
Solution 2:[2]
I would use DATEDIFF.
For example:
dateDiff("d", date2 , date1) = 1
With date2 = 28.05.2014
and date1 = 29.05.2014
. d
defines that you want the difference by days.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | skiingflea |
Solution 2 | oerl |