hey need some help guys. for example i have a text box and i will have input in it. but only numeric ones are allowed to be inputted in the text box if a character for example "a" is pressed the text box will not change and type the "a" and if a numeric button for example is 1, the text box will have 1. how can i do this? thanks.

Dani AI

Generated

Quick, practical way to make a VB6 TextBox accept only numbers (and handle edge cases missed in the thread). pointed toward keystroke filtering — that’s a good start — but also watch for control keys, decimal/negative needs, and paste actions which bypass keystroke checks. The snippets below show a robust KeyPress filter and a simple LostFocus check to catch pasted text.

Private Sub Text1_KeyPress(KeyAscii As Integer)
    Select Case KeyAscii
        Case 8, 9, 13                  ' Backspace, Tab, Enter (allow)
            ' allowed
        Case 45                        ' minus sign
            If InStr(1, Text1.Text, "-") > 0 Or Text1.SelStart <> 0 Then KeyAscii = 0
        Case 46                        ' decimal point
            If InStr(1, Text1.Text, ".") > 0 Then KeyAscii = 0
        Case 48 To 57                  ' digits 0-9 (allow)
            ' allowed
        Case Else
            KeyAscii = 0               ' block everything else
    End Select
End Sub

A keystroke filter still doesn’t stop Ctrl+V paste or programmatic changes. Validate when the user finishes input (LostFocus/Exit) or before you use the value:

Private Sub Text1_LostFocus()
    If Len(Trim$(Text1.Text)) > 0 Then
        If Not IsNumeric(Text1.Text) Then
            MsgBox "Please enter a numeric value.", vbExclamation
            Text1.SetFocus
        End If
    End If
End Sub

Notes and tips: remove the minus/decimal cases if you only want integers. Avoid aggressively modifying Text inside Change (it resets caret/selection); prefer LostFocus validation or implement a careful Change routine that preserves SelStart. Always re-validate and convert with Val/CInt and error handling just before using the value. For complex masks consider the Masked Edit control or a numeric up/down control.

Recommended Answers

All 5 Replies

You need to handle the keyascii in the keypress event .

how can i handle the ascii? can anyone make a sample code? i would really appreciate it thanks.

tryb to use this sample code for reference.

Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii >= 97 And KeyAscii <= 122 Then
KeyAscii = 0
End If
End Sub

hey hello debasisdas. Thanks so much for the help :)

You are most welcome .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.