PDA

View Full Version : Solved: Numerica only input



davidboutche
09-18-2009, 09:03 AM
I've done a lot of research and can't get anywhere with this. I just want a real simple way to restrict the input of a textbox to numerical keys only.

I saw something like this:If KeyAscii < 48 Or KeyAscii > 57 Then KeyAscii = 0
but couldn't get it to work.

davidboutche
09-18-2009, 09:23 AM
Solved it with this
Private Sub TextBox1_Change()
Dim okstop As Boolean
Dim OK_continue As Boolean
Dim mytext As String

okstop = False


Do
mytext = TextBox1.Value
If Left(mytext, 1) = "-" Then
mytext = Right(mytext, Len(mytext) - 1)
End If
If Not IsNumeric(mytext) And mytext <> "" Then
TextBox1.Value = "" 'Clears the TextBox


'Shows a message box that informs you that you typed
'something other than a number.
OK_continue = MsgBox("Please type only numbers." & _
Chr(13), vbOKOnly)
Else
okstop = True 'You typed a number in the TextBox.
End If


'Continue with the loop if you click Yes.
'Stop the loop if they typed a number in the TextBox.
Loop Until (OK_continue = vbNo) Or (okstop = True)


End Sub

lucas
09-18-2009, 11:16 AM
IsNumeric

is the obvious solution. Good job susing it out.

macropod
09-19-2009, 04:54 AM
Hi David,

Try:
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If Len(TextBox1.Text) = 0 And KeyAscii = 45 Then GoTo OK
If Not (KeyAscii > 47 And KeyAscii < 59) Then
Beep
KeyAscii = 0
End If
OK:
End SubThe advantage this has over your code is that the entire input isn't discarded if the preceding characters are valid. Considerably more code would be required to correctly handle thousands separators & decimals - if you need them.

fumei
09-21-2009, 10:03 AM
Nice.

davidboutche
09-23-2009, 03:20 PM
Yeah that's great. Thanks for that. I'll re use that code so many times. Ta