Force a text box to contain numbers

E

Erin

Can someone reply with an example of code that can be
written to force a user to enter numeric values into a
text box? Thank you.
 
J

Jezebel

This is actually very hard to do, and tends to upset the users. In principle
you can use the KeyPress event to check what key is used and to prevent
those you don't want; but apart from digits you have to allow for backspace,
ctrl-C, ctrl-X, etc. Then if you allow ctrl-V you have to check that what is
pasted in is also acceptable ... Even the definition of 'numeric' is
problematic if you're working key-by-key. A decimal point is OK, but maximum
one. Thousands separators are OK, but there have to be exactly three digits
between ... etc.

I think it's better to let the user enter anything they like, then validate
the result before you use it. You can use the IsNumeric() function, but be
aware there are some strange strings that pass its test. Or simply cast the
string to the data type you want, check for error, and echo the value back
to the user.

Dim pResult as long

on error resume next
pResult = clng(TextBox)
if err > 0 then
... invalid value
exit sub
end if
on error goto 0
TextBox = cstr(pResult)
 

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

Top