I've written the following code to find the oldest of five dates. It works as expected, but I'm curious if there's a more elegant way to compare five dates. Does anyone have any ideas?
Dim sTemp
sTemp = ""
If IsDate(dtOne) Then
If IsDate(dtTwo) Then
If CDate(dtOne) < CDate(dtTwo) Then
sTemp = dtOne
Else
sTemp = dtTwo
End If
Else
sTemp = dtOne
End If
ElseIf IsDate(dtTwo) Then
sTemp = dtTwo
End If
If IsDate(dtThree) Then
If IsDate(sTemp) Then
If CDate(dtThree) < CDate(sTemp) Then
sTemp = dtThree
End If
Else
sTemp = dtThree
End If
End If
If IsDate(dtFour) Then
If IsDate(sTemp) Then
If CDate(dtFour) < CDate(sTemp) Then
sTemp = dtFour
End If
Else
sTemp = dtFour
End If
End If
If IsDate(dtFive) Then
If IsDate(sTemp) Then
If CDate(dtFive) < CDate(sTemp) Then
sTemp = dtFive
End If
Else
sTemp = dtFive
End If
End If
How about something like this, it does each comparison and if neither passed variables are date it restores sTemp to "":
I would use something like this:
GetOldestOf()
returns the second argument (converted to a date) if the argument is a valid date and the first argument is eitherEmpty
or newer than the second argument. Otherwise the function returns the (unmodified) first argument, which by definition is eitherEmpty
or the current oldest date.You asked for an elegant approach, then use an ArrayList, fill it and sort it. Underneath the proof of concept code, it does not handle exceptions like none of the dates are valid: