Numeric Text with fixed decimal

Numeric Text with fixed decimal

In some text boxes, you might want to restrict input to a number. To do this, add the following code

Private Sub txtGoto_KeyPress(KeyAscii As Integer)
    'ensure we only accept numeric input
    KeyAscii = NumericOnly(KeyAscii)
End Sub

Public Function NumericOnly(KeyAscii As Integer) As Integer
    If Not IsNumeric(Chr$(KeyAscii)) And Not KeyAscii = vbKeyBack Then
        NumericOnly = 0
    Else
        NumericOnly = KeyAscii
    End If
End Function

This is another method. It also two decimal places to be enterd.

Dim X As Integer
   If txtadd.Text <> "" Then
       If txtadd.Text = "." Then
           txtadd.Text = "0."
       End If
       
       'check for decimal
       If Right(txtadd.Text, 1) = "." Then
           txtadd.Text = Left(txtadd.Text, Len(txtadd.Text) - 1)
       End If
       
       'check for repeating decimal
       X = 1
       Do Until Len(txtadd.Text) = X
           If Mid(txtadd.Text, X, 1) = "." Then
               Exit Do
           End If
           X = X + 1
       Loop
       
       
       If Len(txtadd.Text) <> X Then
           If Right(txtadd.Text, 1) = "." Then
               txtadd.Text = Left(txtadd.Text, Len(txtadd.Text) - 1)
           End If
       End If
       
       'check for long decimals
       X = InStr(txtadd.Text, ".")
       If X < Len(txtadd.Text) - 2 And X <> 0 Then
           txtadd.Text = Left(txtadd.Text, Len(txtadd.Text) - 1)
       End If

       
       'check for -
       If InStr(txtadd.Text, "-") <> 0 Then
           txtadd.Text = Left(txtadd.Text, Len(txtadd.Text) - 1)
       End If
       
       'check for space
       txtadd.Text = Trim(txtadd.Text)
       
       'check for numeric
       If Not IsNumeric(txtadd.Text) Then
           If txtadd.Text <> "" Then
               txtadd.Text = Left(txtadd.Text, Len(txtadd.Text) - 1)
           End If
       End If
   End If
   txtadd.SelStart = Len(txtadd.Text)
End Sub

You might also like...

Comments

Nick Avery I am as a web developer for a small company, working for a small company. I work on banking websites and verious related projects.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“It is practically impossible to teach good programming style to students that have had prior exposure to BASIC. As potential programmers, they are mentally mutilated beyond hope of regeneration.” - E. W. Dijkstra