TextBox - Validate Date on Exit and resume field on TAB

R

Rob W

Greetings,

I have a text box with the default date in ("dd/mm/yyyy") format.

The user can then type over this date or leave it alone, and exits the text
box by means of the TAB key.
Within the exit code all the date validation takes place (See below).

If there is a problem the idea is to not allow the user to leave the textbox
until it is corrected.
The code executes and the error messages are displayed, HOWEVER there is
also code which executes when the TAB key is pressed.
This code does no validation as is all done within the exit event, the
KEYPRESS envent disables the textbox and makes the next form on the field
visible.

However as when you press the TAB key you are both EXITING and activitaing
the KEYPRESS event it executes them both and allows the user to bypasss the
validation (change even code below too).
You can only EXIT the field using the TAB key as there are no fields to TAB
too unless activated within the code.

I simply cant think of a logical way out of this, any ideas?

Private Sub txtDateAdmitted_Exit(ByVal Cancel As MSForms.ReturnBoolean)

If txtDateAdmitted.Visible = True And Not IsDate(txtDateAdmitted.Text)
Then
MsgBox "A date is required in this field", vbInformation +
vbOKOnly
txtDateAdmitted.Text = Format(Now(), "dd/mm/yyyy")
Cancel = True
'format date if it is data
ElseIf txtDateAdmitted.Visible = True And IsDate(txtDateAdmitted.Value)
Then
txtDateAdmitted.Value = Format(CDate(txtDateAdmitted.Value),
"dd/mm/yyyy")

'Date comparison with date registered
If CDate(lblDateRegistered.Caption) > CDate(txtDateAdmitted.Value)
Then
MsgBox "Warn: Please enter a date after registration date",
vbInformation + vbOKOnly
Cancel = True
End If

End If

End Sub

Private Sub txtDateAdmitted_KeyUp(ByVal KeyCode As MSForms.ReturnInteger,
ByVal Shift As Integer)

If KeyCode = vbKeyTab Then

On Error Resume Next

With Me.comboWard
.Visible = True
.SetFocus
End With

txtDateAdmitted.Enabled = False
KeyCode = 0

End If
End Sub
 
D

David Heaton

Hi Rob,

Have you tried putting your validation code in the 'LostFocus' event of the
textbox.

hth

David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top