We help IT Professionals succeed at work.

Inkey function in Visual Basic 6

Medium Priority
Last Modified: 2013-12-25
I need to check a value to make sure that there are no spaces or special characters in it. Alpha numeric characters are valid. But not any other characters like space, *, %, etc.
Watch Question

Top Expert 2005

Better to put function to check character on Key Press Event

Private Sub text1_KeyPress(KeyAscii As Integer)
    Dim iNumbers As Integer
    Dim sMsg As String
    iNumbers = KeyAscii

    If ((iNumbers < 48 Or iNumbers > 57) And (iNumbers < 65 Or iNumbers > 90) and (iNumbers < 97 Or iNumbers > 122)) Then
        sMsg = MsgBox("Could Not")
        KeyAscii = 0
    End If
End Sub
Private Sub text1_KeyPress(KeyAscii As Integer)
Select case Keyascii
case 48 to 57
msgbox ("text is valid")
case else
msgbox("text not valid")
end select
end sub

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
leclairm.Net Developer  ERP integration

Don't forget about backspace:

    If ((iNumbers < 48 Or iNumbers > 57) And (iNumbers < 65 Or iNumbers > 90) And (iNumbers < 97 Or iNumbers > 122) And iNumbers <> 8 ) Then

leclairm.Net Developer  ERP integration

Actually, better to use a case like JackOfPH did:

Select Case KeyAscii
    Case 8, 48 To 57, 65 To 90, 97 To 122
    Case Else
        MsgBox ("Invalid")
End Select
Top Expert 2005

Mike what the different
"better to use a case like JackOfPH did"
leclairm.Net Developer  ERP integration

Much clearer and easier to read /maintain if valid keys are to be added or removed from validity check, that's all.
Top Expert 2005

Sorry,Not differents.It depend what from personal choice
leclairm.Net Developer  ERP integration

Didn't say it was different, just clearer.  Both will give the same result, but compare your if to the case I put and tell me which one is easier to read.
Top Expert 2005

It just discussion.
Personaly I like If Statement more,but it again depent of personal choice.

leclairm.Net Developer  ERP integration

Agreed.  I guess it does boil down to personal choice or style of programming that your used to.
leclairm.Net Developer  ERP integration

The answer you accepted only accepts 0-9.  Is that what you wanted??
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.