Each time the user types a character into a text box the KeyPress event is triggered. The Ascii value of the typed character is passed as the parameter KeyAscii. The keystroke may be rejected by setting KeyAscii to zero.
There's an example function below that only accepts numbers, the '.' character (for a decimal point) and the backspace character to allow the user to edit.
To test the sample code below:
1 Start a new VB project
2 Put a text box named Text1 (the default name) on the form
3 Double click on the form and copy the code below into the code window.
4 Press F5 to run the sample application. You should not be able to enter any characters other than 0123456789. into the text box.
[tt]
Option Explicit
Function OnlyNumericKeys(KeyAscii As Integer) As Integer
Select Case KeyAscii
Case 8, 46, 48 To 57 ' allow backspace, '.' and digits
Case Else: KeyAscii = 0 ' reject everything else
End Select
OnlyNumericKeys = KeyAscii
End Function
Private Sub Text1_KeyPress(KeyAscii As Integer)
KeyAscii = OnlyNumericKeys(KeyAscii)
End Sub
[/tt]
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.