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
        Cancel = True
End If

I need it to allow hyphens also...

Who is Participating?
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
        Cancel = True
End If

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

Private Sub txtNumber_KeyPress(KeyAscii As Integer)
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)
'End Sub

On Error GoTo HandleErr

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

  Exit Function

  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
SariffAuthor Commented:
Actually I am using the code in the 'Before Update" event. It works well. The hyphen part does not work...
SariffAuthor Commented:
I found my answer. Thanks!
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.