How to restrict a VBA text box to accept letters only

FaheemAhmadGul
FaheemAhmadGul used Ask the Experts™
on
I have textBox on a VBA form named txtAnswer

I would like to restrict what can be entered in a VBA TextBox (txtAnswer) to letters only.
If the user presses a number key the number will not be typed into the TextBox but instead a Message Box will pop up showing the number key that has been pressed. Also if the user presses the Enter Key a Message Box should pop up saying “You pressed Enter Key”

So if the user starts typing “ a p p p l e  “ then the word “apple” will get typed into txtAnswer, but if the user presses a number key such 3 then the text in the txtAnswer will remain unchanged but a message box will pop saying “You pressed 3 ‘“
Thank you for your help.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Roy CoxGroup Finance Manager
Commented:
Is it a UserForm TextBox?

Try this

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    If KeyAscii < Asc("0") Or KeyAscii > Asc("9") Then
        'do nothing
        Else: MsgBox "Text only allowed"
        KeyAscii = 0
    End If
End Sub

Open in new window

John TsioumprisSoftware & Systems Engineer

Commented:
You can use the onChange event
Excel & VBA Expert
Most Valuable Expert 2018
Awarded 2015
Commented:
If the name of the TextBox is TextBox1, place the following codes on UserForm Module...

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then
    MsgBox "You pressed Enter key."
End If
End Sub

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
    Case 32, 65 To 90, 97 To 122
        'do nothing
    Case Else
        MsgBox "You pressed '" & Chr(KeyAscii) & "'."
        KeyAscii = 0
End Select
End Sub

Open in new window

How to Generate Services Revenue the Easiest Way

This Tuesday! Learn key insights about modern cyber protection services & gain practical strategies to skyrocket business:

- What it takes to build a cloud service portfolio
- How to determine which services will help your unique business grow
- Various use-cases and examples

Author

Commented:
Thank you all experts for taking the time to answer my questions. Both Neeraj’s and Roy’s solution were very helpful and therefore I am accepting both.
Subodh Tiwari (Neeraj)Excel & VBA Expert
Most Valuable Expert 2018
Awarded 2015

Commented:
You're welcome Faheem! Glad we could help.
Thanks for the feedback!
Roy CoxGroup Finance Manager

Commented:
Pleased to help

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial