Date Validation

B

Ben Allen

I have a text box on my userform. What code do i need to add to the add
button so that it will check that it is a date (dd/mm/yyyy).
Thanks.
--
Cheers,
Ben

Remove your.tonsils to reply
"You only live once but if you do it right once is enough!"
 
J

Jake Marx

Hi Ben,

Something like this may work for you:

With TextBox1
If Not IsDate(.Text) Then
MsgBox "Invalid date"
.SetFocus
.SelStart = 0
.SelLength = Len(.Text)
End If
End With

--
Regards,

Jake Marx
MS MVP - Excel
www.longhead.com

[please keep replies in the newsgroup - email address unmonitored]
 
B

Bob Phillips

Ben,

You can also trap the values as they are entered

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
With TextBox1
If Not IsDate(.Text) Then
MsgBox "Invalid date"
.SelStart = 0
.SelLength = Len(.Text)
.SetFocus
Cancel = True
End If
End With
End Sub

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
Case 45 To 47 '/ - or .
Exit Sub
Case 48 To 57 'Nos 0 - 9
Exit Sub
Case Else
Application.EnableEvents = False
KeyAscii = 0
Application.EnableEvents = True
Beep
End Select

End Sub

--

HTH

Bob Phillips
... looking out across Poole Harbour to the Purbecks
(remove nothere from the email address if mailing direct)

Jake Marx said:
Hi Ben,

Something like this may work for you:

With TextBox1
If Not IsDate(.Text) Then
MsgBox "Invalid date"
.SetFocus
.SelStart = 0
.SelLength = Len(.Text)
End If
End With

--
Regards,

Jake Marx
MS MVP - Excel
www.longhead.com

[please keep replies in the newsgroup - email address unmonitored]


Ben said:
I have a text box on my userform. What code do i need to add to the
add button so that it will check that it is a date (dd/mm/yyyy).
Thanks.
 
Top