Hi,
Firstly note that InputBox and Application.InputBox are different. See help
for differences.
The following code will validate a date. Using IsDate on its own is
unreliable. For instance entering IsDate("32/4/10") can return True and
DateValue("32/4/10") converts it to 10 Apr 1932.
The following code splits the enty into its 3 components separated by the
slashes and validates each component. Then the use of IsDate is really only
testing if too many days have been entered for the particular month.
There is no justification for forcing 2 digit entry of the day and month.
The code will validate either two digit or one digit entries. However, the
code will only validate a 4 digit year.
I have tested the code but if you find any conditions where it accepts an
invalid date then please get back to me.
Also, I have included code if the user Cancels to they can abort if necessary.
The If tests of the date components could be combined into one statement but
I did it in a way that is easy to follow the logic.
Sub InputBoxExample()
Dim Response As Variant
Dim dateEntry As Date
Dim strPrompt As String
Dim x
strPrompt = "Enter date as d/m/yyyy."
Do
Response = Application.InputBox _
(Prompt:=strPrompt, _
Title:="Date entry.", _
Type:=2)
If Response = False Then
MsgBox "User cancelled." & vbLf & _
"Processing terminated."
Exit Sub
End If
'x is an array to hold
'elements of the date that
'are separated by "/"
x = Split(Response, "/", -1)
If UBound(x) <> 2 Then
'Must have 3 elements (0 to 2)
GoTo InvalidDate
End If
'Test for day between 1 and 31
If x(0) < 1 Or x(0) > 31 Then
'Invalid day in date entry
GoTo InvalidDate
End If
'Test for month between 1 and 12
If x(1) < 1 Or x(1) > 12 Then
'Invalid month in date entry
GoTo InvalidDate
End If
'Test for year within specified range
'Edit 2000 and 2020 to required valid years
If x(2) < 2000 Or x(2) > 2020 Then
'Invalid year in date entry
GoTo InvalidDate
End If
'An invalid for IsDate indicate incorrect
'number of days for the particular month.
If IsDate(Response) Then
'Assign string date to date variable
dateEntry = DateValue(Response)
'MsgBox for testing only
MsgBox "Date entry is: " & _
Format(dateEntry, "dd mmm yyyy")
Exit Do 'No further testing required
Else
strPrompt = "Error! Invalid date entry." & _
vbLf & "Could be too many days in month." & _
vbLf & "Enter as d/m/yyyy"
End If
'If gets to here then skip the InvalidDate
GoTo PastInvalidDate
InvalidDate:
strPrompt = "Error! Invalid date entry." _
& vbLf & "Enter as d/m/yyyy"
PastInvalidDate:
Loop
End Sub