Re: Required Field for 7 Numeric digits only

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



There has to be an easier way of doing this......

Not sure if this is "easier", but here is a different approach for you to consider. The code below will only let the user type in or Copy/Paste digits into the TextBox. If the user attempts to leave the TextBox where there are not 7 digits in it, the user will get a MessageBox and then be returned to the TextBox to correct their entry. So you don't lose what you have, comment out (or copy/save) your existing code and then Copy/Paste all the code below (exactly as it is shown) into the same work*** code window.

Rick

Dim LastPosition As Long

Private Sub TextBox1_Change()
Static LastText As String
Static SecondTime As Boolean
If Not SecondTime Then
With TextBox1
If .Text Like "*[!0-9]*" Then
Beep
SecondTime = True
.Text = LastText
.SelStart = LastPosition
Else
LastText = .Text
End If
End With
End If
SecondTime = False
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 event 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_LostFocus()
If Len(TextBox1.Text) <> 7 Then
MsgBox "Please enter exactly 7 digits!"
TextBox1.Activate
End If
End Sub

.


Quantcast