Results 1 to 6 of 6

Thread: Entering Numbers Only

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Nov 2000
    Posts
    217
    I know i have seen this before on the board, but i can't seem to find it. I want the user to be able to only enter numbers, besides backspace and spacebar. Thank you

  2. #2
    Frenzied Member markman's Avatar
    Join Date
    Nov 2000
    Location
    Florida.
    Posts
    1,197
    Even though I am againts relying on Errors:
    Code:
    Text1_Change()
    Dim tester As Integer
    On Error GoTo notnumber
    tester = CInt(Text1.Text)
    notnumber:
    MsgBox 'whatever
    End Sub
    Im not even sure if that will work, but its worth a try.
    retired member. Thanks for everything

  3. #3
    Hyperactive Member
    Join Date
    Oct 2000
    Posts
    400
    The easiest (and in some respects the best) approach is to use the Validate event:
    Code:
    Sub Text1_Validate(Cancel As Boolean)
        Me.Text1 = Val(Me.Text1)
    End Sub
    The other way is through the KeyPress event:
    Code:
    Private Sub Text1_KeyPress(KeyAscii As Integer)
        Select Case KeyAscii
            Case 13 ' Enter
            Case 32 ' Space
            Case Is < 48 ' Under 0
            Case Is > 57 ' Over 9
            Case Else
                KeyAscii = 0
        End Select
    End Sub
    The thing you want to remember is that some characters are not digits, but they are numeric. Period, plus, minus, e, and dollar sign (if you use the IsNumeric function, $ is valid) are all possible additions to the above cases.

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Nov 2000
    Posts
    217
    I was leaning more towards not even allowing the user to enter them, where no msg box is needed

  5. #5
    Hyperactive Member marnitzg's Avatar
    Join Date
    Oct 2000
    Location
    South Africa
    Posts
    372
    Code:
    Private Sub Text1_KeyPress(KeyAscii As Integer)
    If Not (IsNumeric(Chr(KeyAscii))) And KeyAscii > 32 Then
        KeyAscii = 0
    End If
    End Sub

  6. #6

    Thread Starter
    Addicted Member
    Join Date
    Nov 2000
    Posts
    217
    Thank you, I found marnitzg to work best.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width