Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only allow letters in textbox for MS Access

I have a text box in a form in MS Access. I just want users to enter Letters and spaces. No special characters.

I have implemented the following on KeyPress Event. I am wondering is there any better way to implement the same.

Private Sub txtName_KeyPress(KeyAscii As Integer)
If KeyAscii <> 8 And KeyAscii <> 32 Then  'Not Backspace (important for error correction) and not a Space
    If (KeyAscii < 65 Or KeyAscii > 90) And (KeyAscii < 97 Or KeyAscii > 122) Then   'Allowing lower and upper case
    Beep 'Let the user know they hit an illegal key
    KeyAscii = 0 'Don't let the keystroke through
    End If
End If
End Sub
like image 643
Adarsh Madrecha Avatar asked Feb 03 '26 13:02

Adarsh Madrecha


1 Answers

Consider using the BeforeUpdate event of the textbox which is the trigger usually used to validate entry as you have the facility to cancel the update:

Private Sub txtWordsOnly_BeforeUpdate(Cancel As Integer)

    If Me.txtWordsOnly Like "*[0-9]*" Or Me.txtWordsOnly Like "*[@#$%*^&?()<>/\'""!]*" Then
        MsgBox "Invalid entry. Please select only words," _
                 & " NOT numbers or special characters.", vbInformation
        Cancel = -1     ' OR Cancel = True
        Me.txtWordsOnly.Undo
    End If

End Sub
like image 142
Parfait Avatar answered Feb 05 '26 09:02

Parfait



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!