Restrict characters in Text Box

I have text boxes that restrict the characters that are entered. The code is below:

If Me.TextBoxName.Value Like "*[!A-Z]*" Then
        MsgBox
        Cancel = True
End If

I need it to allow hyphens also...

-Sariff
SariffAsked:
Who is Participating?
 
rockiroadsCommented:
why not put a and in it?

Im assuming this is on the keypress function? u can do validation per keypress then

If Me.TextBoxName.Value Like "*[!A-Z]*" and  Me.TextBoxName.Value != "-" Then
        MsgBox
        Cancel = True
End If

0
 
cquinnCommented:
Add the function listed below, then in the Keypress event of the textbox use it like this:

Private Sub txtNumber_KeyPress(KeyAscii As Integer)
    KeyAscii=ValidateEntry(".1234567890",KeyAscii)
End Sub


Replace the characters in quotes with the ones you wish to allow


Public Function ValidateEntry(ValidKeys As String, KeyAscii As Integer) As Integer
'Pass a list of acceptable keys, and the ascii code of the key being pressed
'it will return the ascii code if the key is in the list, or 0 if not
'call it from the On_keypress event of a text box eg the following example will
'restrict key entry to valid numerics plus decimal point

'Private Sub txtNumber_KeyPress(KeyAscii As Integer)
'KeyAscii=ValidateEntry(".1234567890",KeyAscii)
'End Sub



On Error GoTo HandleErr

If InStr(ValidKeys, Chr$(KeyAscii)) > 0 Or KeyAscii = 8 Then  'KeyAscii=8 allows the backspace
    ValidateEntry = KeyAscii
Else
    ValidateEntry = 0
End If

ExitHere:
  Exit Function

HandleErr:
  Select Case Err.Number
    Case Else
       MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "modFunctions.ValidateEntry"
  End Select
  Resume ExitHere
' End Error handling block.
End Function
0
 
SariffAuthor Commented:
Actually I am using the code in the 'Before Update" event. It works well. The hyphen part does not work...
0
 
SariffAuthor Commented:
I found my answer. Thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.