Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

One again manipulate users entry in a TextBox 2

Status
Not open for further replies.

Mollethewizard

IS-IT--Management
Nov 18, 2002
93
SE
I’ve learnt that one can prevent the user to insert nothing but numbers in a textbox by using the following code in the KeyPress event relating to a TextBox.

If KeyAscii < 48 Or KeyAscii > 57 Then KeyAscii = 0

But I also would like the user to be able to use the – (asciicode 45) as well. He or she should be able to write for example, 145-03 in the box. How the heck do I write code to accomplish that?

Greetings from Sweden

Christer
 
How about:
Code:
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
  If KeyAscii < 45 Or KeyAscii > 57 Then KeyAscii = 0
  If KeyAscii > 45 And KeyAscii < 48 Then KeyAscii = 0
End Sub


Chris

Varium et mutabile semper Excel
 
Hi Mollethewizard,

All sorts of ways to code that. Here's one:

Code:
Select Case KeyAscii
    Case 45, 48 to 57
    Case Else: KeyAscii = 0
End Select

Enjoy,
Tony
 
That's very elegant Tony! Less typing too! [laughtears]

Have a STAR from me.

Chris

Varium et mutabile semper Excel
 
Thanks, Chris.

I like to minimise typing as I'm never going to learn how to do it properly [wink]

Enjoy,
Tony
 
Chris and Tony I’ve tested your code and neither work in the KeyPress event. Should I put it somewere else?

Greetings

Christer
 
Hi Christer,

Both should work in exactly the same way as your original (apart from allowing the extra character).

I tested mine before posting and it did what you asked. In what way don't they work?

Enjoy,
Tony
 
Hi Christer,

I agree with Tony; I tested mine before posting, and I've just tried his and they both work just dandy. What error(s) are you getting?

&quot;If there are several ways of doing something, Relmanz2000's will invariably be the least efficient&quot; - Me [rofl]

Chris

Varium et mutabile semper Excel
 
When I talked nicely to my VBA and entered the code once more – it worked!

Thanks Tony

You certainly deserve the STAR I’ve given you!

Christer
 
Thanks, Christer,

I always try and talk nicely to my computer - don't always succeed but I always try [smile]

Enjoy,
Tony
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top