Textbox Validation

graviz

Registered User.
Local time
Today, 06:24
Joined
Aug 4, 2009
Messages
167
Is there a way to validate what a person enters into a text box is numeric and is 4 characters long (no more, or less)
 
Yes but I have two issues with it.

1. It won't make sure there are 4 digits entered. It'll limit it to 4 but won't catch if there are only 3.

2. When I click on the textbox it might click on the 2nd digit and then you could only enter 3 digits unless you backspace.
 
Have it check the length...

if len(me.TextBox) <> 4 then
Msgbox "Entry must be 4 digits long"
end if
 
One way would be to use the On Change event and go with

Code:
Private Sub YourControlNameHere_KeyDown(KeyCode As Integer, Shift As Integer)
    Select Case KeyCode
    Case 9 ' tab key
       ' let it through
    Case 48 To 57
       ' let it through
    Case 96 To 105
       ' let it through
    Case Else
       ' cancel the key stroke
        KeyCode = 0
    End Select
    If Len(Me.YourControlNameHere.Text) >= 4 Then
        ' cancel the stroke if we've reached 4 characters
        KeyCode = 0
    End If
End Sub

You might also want to enable the backspace key and enter key, and any others you need.
 
Actually the Len function worked perfectly! Thanks everyone!!
 
Actually the Len function worked perfectly! Thanks everyone!!

The whole code I provided will ensure ONLY numbers can be entered AND that the length is limited to 4 characters.
 
Look ma no code! :D

It is possible to do it without any VBA code.

Use the Input mask ( 0000 ) and a validation rule property of > 999.
 
Look ma no code! :D

It is possible to do it without any VBA code.

Use the Input mask ( 0000 ) and a validation rule property of > 999.
That won't work if you are allowed to enter 0002 for example. OP was not clear if first digit could be 0 or Not
 
That won't work if you are allowed to enter 0002 for example. OP was not clear if first digit could be 0 or Not

Good point.

I was thinking a 4 digit number which would be a number > 999. The OP said the user must enter four characters that must all be digits, which does not mean a number > 999.
 
I have read your topic. What's useful innformation for my job.
I do agree with you. Those are the most effective way
have a blessed day
 

Users who are viewing this thread

Back
Top Bottom