allow only letter in textbox

User avatar
sal21
PlatinumLounger
Posts: 4334
Joined: 26 Apr 2010, 17:36

allow only letter in textbox

Post by sal21 »

Code: Select all

Private Sub TNOMINATIVO_KeyPress(KeyAscii As Integer)

    KeyAscii = Asc(UCase(Chr(KeyAscii)))

    If Not Chr$(KeyAscii) Like "[A-Za-z]" And KeyAscii <> 8 Then KeyAscii = 0

End Sub
is this correct?

if is yes, i cannot use a the space bar, why?

User avatar
SpeakEasy
4StarLounger
Posts: 535
Joined: 27 Jun 2021, 10:46

Re: allow only letter in textbox

Post by SpeakEasy »

Technically space isn't a letter.

But this function is pretty clear in what it does - it just allows characters in the pattern. So just add a space to the pattern

User avatar
HansV
Administrator
Posts: 78232
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: allow only letter in textbox

Post by HansV »

Using Chr, Asc and then Chr again is a rather roundabout approach!
You don't have to check for KeyAscii = 8, for KeyPress doesn't react to the Tab key.
I'd do it like this:

Code: Select all

Private Sub TNOMINATIVO_KeyPress(KeyAscii As Integer)
    Select Case KeyAscii
        Case 32, 65 To 90, 97 To 122
            ' Letters and space are OK
        Case Else
            KeyAscii = 0
    End Select
End Sub
Best wishes,
Hans

User avatar
SpeakEasy
4StarLounger
Posts: 535
Joined: 27 Jun 2021, 10:46

Re: allow only letter in textbox

Post by SpeakEasy »


User avatar
HansV
Administrator
Posts: 78232
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: allow only letter in textbox

Post by HansV »

:rofl:
Best wishes,
Hans