Textbox edit

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a text box in a form I would like the user to enter numbers only in.
On this forum, some code was posted:

Private Sub TextBox1_Key Press
If KeyAscii <48 or Key Ascii >57 Then
KeyAscii=0
End If

This works great EXCEPT it will not allow input of a negative number, which
I need. How can I modify this code to allow a negative number to be input?

Thanks!
 
The ASCII code for "-" is 45, so you can allow that; i.e:
If (KeyAscii < 48 and KeyAscii <>45) or KeyAscii > 57 Then...
The only problem: the user could enter something like 34-56 unless you also
check to see if it is the first character in the textbox, so you may need to
write some code to deal with this possibility.
 
Hi Paul

Use this (45 = -)

Private Sub TextBox1_KeyPress(ByVal keyascii As MSForms.ReturnInteger)
Select Case keyascii
Case 45
Case 48 To 57 'Numbers
Case Else 'Discard anything else
keyascii = 0
End Select
End Sub
 
Check separately, for the first char being a - and there not already being
one, or have a checkbox to signify negative.

--

HTH

RP
(remove nothere from the email address if mailing direct)
 
Only once, and at start Ron

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Static fHyphen As Boolean
Select Case KeyAscii
Case 45
If fHyphen Or Len(TextBox1.Text) > 1 Then
KeyAscii = 0
End If
Case 48 To 57 'Numbers
Case Else 'Discard anything else
KeyAscii = 0
End Select
End Sub


Regards

Bob
 
Hi Bob


Or maybe

Case 45: If TextBox1.SelStart <> 0 Then keyascii = 0
 
even nicer!

A better solution, and highlighting that my fHyphen variable was superfluous
(in such a nice way :-))

Bob


Ron de Bruin said:
Hi Bob


Or maybe

Case 45: If TextBox1.SelStart <> 0 Then keyascii = 0
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top