How can I limit the text input to only numbers in Visual Basic?

To only allow users to input numbers in a text box, you can use the KeyPress event to check if the character inputted by the user is a number. Below is an example code:

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    If Not IsNumeric(Chr(KeyAscii)) And KeyAscii <> 8 Then
        KeyAscii = 0
    End If
End Sub

In this example, TextBox1 is the name of the text box. The KeyPress event is triggered when the user presses a key on the keyboard. In the event handler, it is determined if the input character is a number (using the IsNumeric function) and if the Backspace key (ASCII code 8) is pressed to allow input. If it is not a number and not the Backspace key, the KeyAscii is set to 0 to prevent the user from entering non-numeric characters.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds