View Single Post
 
Old 06-03-2012, 07:05 PM
joatmon joatmon is offline Windows 7 64bit Office 2010 64bit
Novice
 
Join Date: May 2012
Posts: 14
joatmon is on a distinguished road
Default Restricting User Input on a TextBox (and setting focus)

I have a textbox on a userform that I am trying to restrict user input to only allow integer values. I am able to do this, but the behavior is a little weird. First, here is my code:

Code:
Private Sub txtAnswer_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    If (KeyAscii >= 48) And (KeyAscii <= 57) Then
        Me.txtAnswer.SetFocus
    Else
        KeyAscii = 0
        Me.txtAnswer.SetFocus
    End If
End Sub
The problem is that after the user has entered a value, the focus seems to go away from the textbox. Further, if the user does enter an integer value, this value is deleted from the textbox. The SetFocus lines are my attempt to make the control behave correctly, bu they seem to have no effect.

All I want to do is make sure that the user doesn't enter something like "r" (or any other non-integer value) in the textbox. Any integer value >= 0 is perfectly acceptable (including multiple digit values like 10 or 1000000).

Can anybody see why my approach isn't working? I've tried a few different approaches and have searched around quite a bit, but I can't find something that works.

Thank you.
Reply With Quote