[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 938
  • Last Modified:

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
0
Sariff
Asked:
Sariff
  • 2
2 Solutions
 
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

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now