Library code snippets

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

Comments

  1. 01 Jan 1999 at 00:00

    This thread is for discussions of Numeric Text with fixed decimal.

Leave a comment

Sign in or Join us (it's free).

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.

Related discussion

Related podcasts

  • Christian Beauclair

    14 mai 2008 (�mission #0074) ::.Christian Beauclair: Stratégies de migration VB6 vers .NET Nous discutons avec Christian Beauclair des stratégies de migration VB6 vers .NET. Entre autres, nous discutons comment utiliser le "VB 6 Code Advisor" et le "Interop Forms Toolkit" pour ajouter la puiss...

Want to stay in touch with what's going on? Follow us on twitter!