restrict textbox on userform to mm/yyyy

L

lcoreilly

Does anyone know how to restrict a textbox on a userform to a date in
the format mm/yyyy? Thanks.
 
R

Rick Rothstein

You could try the following set of event code procedures for the TextBox to
control the user's input. NOTE that, as I have written the code, the user
does not have to (actually, they can't) type in the slash... my code will
enter it automatically for them. The user will be able to leave the TextBox
**only** if the TextBox is empty or if it contains a valid date (two-digit
month/four-digit year). In addition, the user will only be able to type
digits into the TextBox... no other characters can be entered. If you have
other required event code of your own that use event procedures I have
employed below, then you will have to integrate your required code into my
code. To implement my code, just copy/paste all of the code between the
START and END OF CODE markers into the UserForm's code window.

'*************** START OF CODE ***************
Dim LastPosition As Long

Private Sub TextBox1_Change()
Dim Cursor As Long
Static LastText As String
Static SecondTime As Boolean
If Not SecondTime Then
SecondTime = True
With TextBox1
If .Text Like "*[!0-9/]*" Then
Beep
SecondTime = True
.Text = LastText
.SelStart = LastPosition
Else
Cursor = .SelStart
Do While InStr(.Text, "/")
.SelStart = InStr(.Text, "/") - 1
.SelLength = 1
.SelText = ""
Cursor = Cursor - 1
Loop
If Len(.Text) > 2 Then
.SelStart = 2
.SelText = "/"
Cursor = Cursor + 1
End If
.SelStart = IIf(Cursor < 0, 0, Cursor)
LastText = .Text
LastPosition = Cursor
End If
End With
SecondTime = False
End If
' Place any other Change event checking code here
End Sub

Private Sub TextBox1_MouseDown(ByVal Button As Integer, ByVal Shift As
Integer, ByVal X As Single, ByVal Y As Single)
With TextBox1
LastPosition = .SelStart
' Place any other MouseDown code here
End With
End Sub

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
With TextBox1
LastPosition = .SelStart
' Place any other KeyPress checking code here
End With
End Sub

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If Len(TextBox1.Text) Then
Cancel = Len(TextBox1.Text) <> 7 Or Not IsDate(TextBox1.Text)
End If
' Place any other Exit checking code here
End Sub
'*************** END OF CODE ***************
 

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

Similar Threads


Top