WoeIs
WoeIs

Reputation: 1083

Is there a way to prevent a text box from accepting letters?

I have the following code which gives an error message if you type anything that isn't a number:

Private Sub TextBox3_Change()
    If Not IsNumeric(TextBox3.Value) Then
        MsgBox "Only digits (0-9) allowed."
        Cancel = True
    End If
End Sub

The problem is that if I were to type a letter in the box, it gives me the error message but still writes the letter in the box. I want the code to completely prevent input from anything that isn't numerical.

Upvotes: 2

Views: 1438

Answers (4)

Steven Carlson
Steven Carlson

Reputation: 83

You can clear the value in the Text Box.

Private Sub TextBox3_Change()
    If Not IsNumeric(TextBox3.Value) Then
        MsgBox "Only digits (0-9) allowed."
        TextBox3.Value = ""
        Cancel = True
    End If
End Sub

Or if you don't want to remove everything you can remove the last character entered.

Private Sub TextBox3_Change()
    If Not IsNumeric(TextBox3.Value) Then
        MsgBox "Only digits (0-9) allowed."
        TextBox3.Value = Left(TextBox3.Value,Len(TextBox3.Value) - 1)
        Cancel = True
    End If
End Sub

Upvotes: 1

Jortx
Jortx

Reputation: 727

You should use the KeyPress Event

Private Sub TextBox3_KeyPress(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TextBox3.KeyPress
    Dim sKeys As String = "1234567890"
    If Not sKeys.Contains(e.KeyChar.ToString()) Then e.Handled = True
End Sub

Upvotes: 0

Luis Curado
Luis Curado

Reputation: 766

u can use keydown event

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
   If Not IsNumeric(Chr(KeyCode)) Then
      KeyCode = 0
   End If
End Sub

Upvotes: 0

SJR
SJR

Reputation: 23081

You can use the KeyPress event to stop any non-numeric entries in the first place.

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

If Not (KeyAscii >= 48 And KeyAscii <= 57) Then
    KeyAscii = 0
End If

End Sub

Upvotes: 0

Related Questions