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