0

The code I am using is this:

If Asc(e.KeyChar) < 65 Or Asc(e.KeyChar) < 90 _
And Asc(e.KeyChar) < 97 Or Asc(e.KeyChar) > 122 Then
    MessageBox.Show("Please enter letters only")
    e.Handled = True
End If

How to allow backspace and space when validating letters in VB?

Visual Vincent
  • 18,045
  • 5
  • 28
  • 75
Faika
  • 1

1 Answers1

3

Character code for backspace is 8 and for space is 32, so your code should be:

If (Asc(e.KeyChar) < 65 OrElse Asc(e.KeyChar) < 90) _
AndAlso (Asc(e.KeyChar) < 97 OrElse Asc(e.KeyChar) > 122) _
AndAlso Asc(e.KeyChar) <> 8 AndAlso Asc(e.KeyChar) <> 32 Then
    MessageBox.Show("Please enter letters only")
    e.Handled = True
End If

Note that I used AndAlso, to stop the evaluation when the first False is encountered.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • 2
    Since you switched to `AndAlso` you might want to use [**`OrElse`**](https://stackoverflow.com/q/8409467) as well ;). Also, consider grouping the `Or/OrElse` checks with brackets. That way it is easier to read, but you also ensure that it executes correctly. – Visual Vincent Dec 21 '17 at 12:02