Making a program which uses text boxes to input numbers but at the moment it also allows characters. how can i make it so it only allows numbers i have tryed the data format but it isnt working.
Printable View
Making a program which uses text boxes to input numbers but at the moment it also allows characters. how can i make it so it only allows numbers i have tryed the data format but it isnt working.
Make use of the ASC code for the allowable character in the KEYPRESS event of the text box so that only the required characters are allowed.
eg.
To Allow letter "A",
Code:
Select KeyAscii
Case ASC("A"),.........
Case Else
KeyAscii=0
End Select
Use this piece of code
Code:Private Sub Text1_Change()
If Not ValidateNumeric(Text1.Text) Then
Text1.Text = ""
End If
End Sub
Private Function ValidateNumeric(strText As String) _
As Boolean
ValidateNumeric = CBool(strText = "" _
Or strText = "-" _
Or strText = "-." _
Or strText = "." _
Or IsNumeric(strText))
End Function
To do a better code for allowing only numbers ,
Code:Select KeyAscii
Case ASC("0") to ASC("9")
Case Else
KeyAscii=0
End Select
Don't forget to allow for Del, Backspace, (Decimal Point, + and - if necessary) though.
Yes Doogle, you are right, i forget it in my sample.....:cool:
Try thisvb Code:
'Place in keypress event of text box to prevent 'typing in non numeric text Private Sub Text1_KeyPress(KeyAscii As Integer) If (KeyAscii < 48 Or KeyAscii > 57) And KeyAscii <> 46 And KeyAscii <> 13 Then MsgBox "Only numbers are allowed for this entries" KeyAscii = 0 Exit Sub End If End Sub 'also, in the change event put this code 'to prevent pasting in non numeric text Private Sub Text1_Change() If Not IsNumeric(Text1.Text) Then MsgBox "Only Numbers Are Allowed" Text1.Text = vbNullString Exit Sub End If End Sub
Might want to modify that change event some, the Msgbox can pop up twice and you loose everything you already had if you do enter a character.
Hows This?
Code:Private Sub Text1_Change()
Static LastGood As String
If Len(Text1) > 0 Then
If Not IsNumeric(Text1.Text) Then
MsgBox "Only Numbers Are Allowed"
Text1.Text = LastGood
Text1.SelStart = Len(LastGood)
Exit Sub
Else
LastGood = Text1.Text
End If
Else
LastGood = ""
End If
End Sub
cheers guys very useful :)
If you have no further questions and you consider this resolved, you could help us out by pulling down the Thread Tools menu and clicking the Mark Thread Resolved menu item. That will let everyone know that you have your answer.
Thank you. :)