I have a UDF to validate date entered by user and to return a collection object consisting a boolean field indicating valid date or not and a date field. The UDF takes a string containing the date entered by user as an argument. The UDF works perfectly fine if a user enters date containing some text e.g. "01 January 2020"; "15-Jan-19" etc. The problem arises the moment the user enters a date in all numeric e.g. "01/01/2020"; "15-01-2019" etc. With the help of some debug.print code within UDF block, I observe that UDF is not getting called at all for numeric date value while it works perfectly fine and returns desired collection variable for date input with some text in it. The code is pretty long, hence I have provided only the relevant section below.
dim strDateInput as String
Dim colValidDate As Collection
Dim validDate As Boolean
...
Private Sub Worksheet_Change(ByVal Target As Range)
...
ElseIf Not Intersect(Target, Range("C:C")) Is Nothing And Target.Row > 3 Then
Selection.NumberFormat = "General"
strDateInput = Target.Cells.Text
...
validDate = False
Set colValidDate = DateValidation(strDateInput)
validDate = colValidDate.Item(1)
If validDate = True Then
If colValidDate.Item(2) > Date Then 'User entered a future date
Cells(Target.Row, "C").ClearContents
Cells(Target.Row, "C").Select
Cells(Target.Row, "C").NumberFormat = "General"
MsgBox "Date can't be a future date.", vbCritical, "Warning"
Else 'User entered a valid date
Cells(Target.Row, "C").Value2 = colValidDate.Item(2)
Cells(Target.Row, "C").NumberFormat = "[$-F800]dddd, mmmm dd, yyyy"
With Range("D" & CStr(Target.Row)).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="Purchase,SIP,Sale,Switch Out,Switch In,Div. Reinv."
End With
Cells(Target.Row, "D").Select
End If
Else 'User entered an invalid date
Cells(Target.Row, "C").ClearContents
Cells(Target.Row, "C").Select
Cells(Target.Row, "C").NumberFormat = "General"
MsgBox "Invalid date. Enter a valid date in DD/MM/YYYY format.", vbCritical, "Warning"
End If
End Sub
...
*****UDF Block*****
Function DateValidation(ByVal strDateRecd As String) As Collection
<Code validating strDateRecd and return Collection varibale>
...
...
...
End Function
On entering numeric date, it is giving "Run-time error '5': Invalid procedure call or argument" and on clicking "Debug", it is highlighting the below lime as the UDF was not called hence the collection variable doesn't contain any value.
validDate = colValidDate.Item(1)
in debugging mode, on placing the cursor over "strDateInput" variable, it shows the numeric date within quotes like "01/01/2020". This clearly suggests that the variable contains text and not numeric. So it can't be a case of variable type mismatch while passing the argument. I am completely clueless. Any help will be much appreciated.