BriggsMonkeyHero
New Member
- Joined
- Apr 28, 2017
- Messages
- 6
https://www.mrexcel.com/forum/excel-questions/317066-force-textbox-date-format.html#post1556884
In reference to this post, I have used the code, except if someone were to just enter 06 and nothing after, it still allows the code to go through. I am looking for an error message to pop up in the case that they don't enter the full date as such: mm/dd/yyyy
In reference to this post, I have used the code, except if someone were to just enter 06 and nothing after, it still allows the code to go through. I am looking for an error message to pop up in the case that they don't enter the full date as such: mm/dd/yyyy
Code:
Private Sub DateTextBox_Change()
Dim Char As String
Dim x As Date
Dim y As Date
Char = Right(DateTextBox.Text, 1)
Select Case Len(DateTextBox.Text)
Case 1 To 2, 4 To 5, 7 To 11
If Char Like "#" Then
If Len(DateTextBox) = 11 Then
On Error Resume Next
x = DateValue(DateTextBox.Text)
y = DateSerial(Right(DateTextBox, 4), Mid(DateTextBox, 4, 2), Left(DateTextBox, 2))
If Err = 0 And x = y Then
On Error GoTo 0
Exit Sub
Else
Err.Clear
On Error GoTo 0
DateTextBox.SelStart = 0
DateTextBox.SelLength = Len(DateTextBox.Text)
MsgBox "Please enter a valid date in the form dd/mm/yyyy", vbCritical + vbOKOnly, "Error"
Exit Sub
End If
Else
Exit Sub
End If
End If
Case 3, 6
If Char Like "/" Then Exit Sub
End Select
Beep
On Error Resume Next
DateTextBox.Text = Left(DateTextBox.Text, Len(DateTextBox.Text) - 1)
DateTextBox.SelStart = Len(DateTextBox.Text)
End Sub