Restricting Entry in a text box to numeric values

jeffreyccs

New member
Local time
Yesterday, 21:52
Joined
Nov 10, 2012
Messages
29
Hi

I have a query regarding the above, I have tried using the keypress event to restrict entry to numeric values only and that functions correctly. The issue that I have is that there are a number of textboxes and like most people I will use the enter or tab keys to move between them. unfortunately the on keypress event does not work with enter or tab and triggers the error message.

Code:
Private Sub tb1l_KeyPress(KeyAscii As Integer)

If (KeyAscii > 47 And KeyAscii < 58) Or (KeyAscii = 8) Or (KeyAscii = 9) Or (KeyAscii = 10) Then
      KeyAscii = KeyAscii
      Else:
      MsgBox "Numberic Data Only!", vbOKOnly, "Invalid Data"
      KeyAscii = 0
   End If
  
End Sub

I would be grateful if anyone has an alternative method that I could try.
 
Why aren't the fields for those controls numeric?

See if you can use the Regex expressions here.
 
unfortunately the on keypress event does not work with enter or tab and triggers the error message.
You should use the Forms BeforeUpdate event for that sort of thing. Just get rid of your key press code and use this instead.

Code:
If IsNull(Me.txtMyControl) Or Not Me.txtMyControl.TEXT Like "*[!0-9]*" Then
    MsgBox "number must be an integer"
    Cancel = True
End If
 
Or you give the Format property of the unbound text box a number format. Then only numbers are accepted.
A bound text box accepts definitions of the associated table field, which means that only numbers can be entered in a number field.
 
Code:
Private Sub Text0_KeyPress(KeyAscii As Integer)

    AllowOnlyNumbers KeyAscii, Me.Text0

End Sub


Public Sub AllowOnlyNumbers(ByRef KeyAscii As Integer, ctl As TextBox)


    Select Case KeyAscii

        Case 48 To 57           '0 to 9
            'do nothing
        Case 46                 'comment out if a "." is not needed  (ie. 2.1)
            'do nothing


        Case Else
       
            MsgBox "Only Numbers Permitted"
            ctl.SetFocus
            ctl.SelStart = Len(ctl.Text)
            KeyAscii = 0
     
    End Select
     
End Sub
 
To be honest, I was doing a rendition of it in the before update and quickly realized that it was not working as well as the simple formatting of the control as a number. So I tend to agree with ebs17 in this case.
 

Users who are viewing this thread

Back
Top Bottom