424,946 Members | 734 Online
Need help? Post your question and get tips & solutions from a community of 424,946 IT Pros & Developers. It's quick & easy.

# How to solve this problem

 100+ P: 284 i am using vb6. in a form i had a text box where i only want to accept numeric values it may be decimal value so i use the following code in key press event of the textbox Expand|Select|Wrap|Line Numbers   Private Sub amounttxt_KeyPress(KeyAscii As Integer) Dim comp As Boolean comp = Chr(KeyAscii) Like "[0-9.]" If Chr(KeyAscii) = vbBack Then Exit Sub If comp = False Then KeyAscii = 0 End If End Sub the code is working fine the problem arises when the user mistaken writes some values like this Expand|Select|Wrap|Line Numbers  200.62.365 instead of 20062.365 or  20..36 instead of 20.36    (by mistake user may enter two time decimal in the box )     as i am also doing some more calculations in it so it give error . so how to avoid this . what is the solution? thanks Jun 23 '08 #1
5 Replies

 100+ P: 142 Hello Nasir Try This Expand|Select|Wrap|Line Numbers Private Sub Text1_KeyPress(KeyAscii As Integer) Dim TmpStr As String TmpStr = "0123456789." If KeyAscii = 8 Then Exit Sub If InStr(TmpStr, Chr(KeyAscii)) = 0 Then KeyAscii = 0 Dim Tmp As Integer Tmp = InStr(Text1.Text, ".") If Tmp > 0 And KeyAscii = 46 Then KeyAscii = 0 End Sub       I Think This Solve ur Problem Faisal Jun 23 '08 #2

 Expert 100+ P: 1,295 I'd rather use the ISNUMERIC function. it does the same thing: Expand|Select|Wrap|Line Numbers Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) If (KeyAscii = 8 Or KeyAscii = 45) Then Exit Sub If Not IsNumeric(TextBox1.Text & Chr(KeyAscii)) Then KeyAscii = 0 End Sub HTH Now that i read my code, you should check that the Ascii 45 only is valid when len(textbox1.text) = 0 Jun 23 '08 #3

 100+ P: 284 i think isnumeric function is much easier Jun 23 '08 #4

 100+ P: 284 Hy i haved used this
• [font='Courier New', Courier, monospace]If (KeyAscii = 8 Or KeyAscii = 45) Then Exit Sub[/font] [font='Courier New', Courier, monospace]If Not IsNumeric(TextBox1.Text & Chr(KeyAscii)) Then KeyAscii = 0[/font] but this is acceptiong + and - also (i-e +2336.36 or -36693) i had reduced the keyascii codes and try till 35 but still its accpting + but - is remonve. how can i remonved both thanks Jun 23 '08 #5

•  Expert 100+ P: 1,295 well, something like this will do: Expand|Select|Wrap|Line Numbers If Not IsNumeric(TextBox1.Text & Chr(KeyAscii)) Or KeyAscii = 45 Or KeyAscii = 43 Then KeyAscii = 0 HTH Jun 23 '08 #6