This one has got me baffled.
I'm trying to validate an entry in a control in the control before update event. In this case it is a function to ensure a user enters a valid UK date. The reason is because of the differences between UK and US dates and the propensity to change to a us format. e.g. a user enters 29/02/19, access will reinterpret that as 19/02/29 - a valid US date, but not what the user wants - they have made an incorrect entry.
Code:
Function isUKDate(optional ctrl as Control) As Boolean
Dim da() As String
if ctrl is nothing then Set ctrl = Screen.ActiveControl
If InStr(ctrl.Text, "/") > 0 Then 'this is dd/mm/yy format
da = Split(ctrl.Text, "/")
If UBound(da) = 2 Then 'has the right number of elements
Select Case Val(da(1))
Case 1, 3, 5, 7, 8, 10, 12
isUKDate = da(0) < 31
Case 4, 6, 9, 11
isUKDate = da(0) < 31
Case 2
isUKDate = da(0) < 28 - (da(2) Mod 4 = 0) 'no leapyear on the century, but not going to worry about that
Case Else
isUKDate = False
End Select
Else
isUKDate = False
End If
ElseIf InStr(ctrl.Text, "-") > 0 Then 'this is dd-mmm-yy format
da = Split(ctrl.Text, "-")
If UBound(da) = 2 Then 'has the right number of elements
Select Case da(1)
Case "Jan", "Mar", "May", "Jul", "Aug", "Oct", "Dec"
isUKDate = da(0) < 31
Case "Apr", "Jun", "Sep", "Nov"
isUKDate = da(0) < 31
Case "Feb"
isUKDate = da(0) < 28 - (da(2) Mod 4 = 0) 'no leapyear on the century, but not going to worry about that
Case Else
isUKDate = False
End Select
Else
isUKDate = False
End If
Else
isUKDate = False
End If
If Not isUKDate Then
MsgBox "Not a UK date, please reenter", vbOKOnly
'On Error Resume Next
'ctrl.Text = ""
'ctrl.Undo
'ctrl.Cancel = True
' ctrl.Parent.Text2.SetFocus
' ctrl.SetFocus
Else
'ctrl = Format(ctrl, "dd-mmm-yyyy")
End If
End Function
So I now have an isUKDate function which reports the date is invalid. So far so good. The problem comes that once the user has clicked the OK button, I cannot get the cursor to stay on the control - you can see my attempts in the commented out section at the bottom. Note that for this to work, the format cannot be set (to a date type) and the calendar has to be disabled.
Anybody any thoughts?