VB CAD Tips

www.vbcad.com

Allow only numbers to be typed into a text box control
 
When customizing AutoCAD, we often work with lines, circles, arcs, etc.   These geometric entities are based on numeric values.  For example, a circle can be entirely based on a center point and a radius.  The center point is composed of X, Y, and Z numeric values.  The radius is also a numeric value.  So, when you want to have a user type a number in a text box, how do you keep the entry numeric?

To restrict or allow specific characters in a text box, we use the KeyDown event of the text box.

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    Select Case KeyAscii
        Case Asc("0") To Asc("9")
        Case Else
            KeyAscii = 0
    End Select
End Sub

The KeyAscii value we are given to work with tells us the ASCII code number of the character that the user entered.  If we set it to 0 in code, nothing is entered into the text box.  The code above looks at the KeyAscii value and sets KeyAscii to 0 if the value of KeyAscii is anything other than the values for the numbers between 0 and 9.   The result of the above code?  The user can only enter numbes from 0 to 9 in the text box.  This works well if you are looking for an integer value.  What happens if you need to allow a decimal value too?  A careful look at the above code may get us placing a decimal character as a valid character as well.  However, if all we do is allow the decimal character, what is to stop the user from typing "4.5.6.7.8"?  Nothing.  We need take a peek at the contens of the text box and perod.  If a period is already in the text box and the user hits the period key, we need to set KeyAscii to 0 and exit.

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    If InStr(1, TextBox1.Text, ".") > 0 And KeyAscii = Asc(".") Then
        KeyAscii = 0
        Exit Sub
    End If
    Select Case KeyAscii
        Case Asc("0") To Asc("9"), Asc(".")
        Case Else
            KeyAscii = 0
    End Select
End Sub

This code will now work as we want - it allows a numeric value to be entered into a text box.  It even allows for the use of a decimal, but only one decimal.

Good luck and happy programming!

Back to Tips ©2000 by VB CAD  All rights reserved.         www.vbcad.com