How to check if a input textbox contains numerical values only?

C

cyberdude

Hi,

In an userform, I assign a textbox, say textbox1, to be an input
textbox that takes numerical values only. I would like to use some
VBA codes that check if the user inputs an numerical value in
textbox1. If he doesn't, it prompts the user to input again. May I
ask what the code should be?

Mike
 
H

Helmut Weber

Hi Mike,
In an userform, I assign a textbox, say textbox1, to be an input
textbox that takes numerical values only.

In case you mean only digits,
as Isnumeric would be true for quite a lot of expressions,
like "100.000,45" or "100,000.45" or "1E12", try:

Private Sub TextBox1_Change()
If Len(TextBox1.Text) > 0 Then
If Asc(Right(TextBox1.Text, 1)) < 48 Or _
Asc(Right(TextBox1.Text, 1)) > 58 Then
TextBox1.Text = Left(TextBox1.Text, Len(TextBox1.Text) - 1)
End If
End If
End Sub

which allows for digits only (or for an empty textbox).

--

Greetings from Bavaria, Germany

Helmut Weber, MVP WordVBA

Vista Small Business, Office XP
 
C

Cindy M.

Hi Cyberdude,
In an userform, I assign a textbox, say textbox1, to be an input
textbox that takes numerical values only. I would like to use some
VBA codes that check if the user inputs an numerical value in
textbox1. If he doesn't, it prompts the user to input again. May I
ask what the code should be?
You can use the IsNumeric function, which will return False if the
content passed to the function (textbox1.text) is not numerical.

Cindy Meister
INTER-Solutions, Switzerland
http://homepage.swissonline.ch/cindymeister (last update Jun 17 2005)
http://www.word.mvps.org

This reply is posted in the Newsgroup; please post any follow question
or reply in the newsgroup and not by e-mail :)
 
C

cyberdude

Hi Mike,


In case you mean only digits,
as Isnumeric would be true for quite a lot of expressions,
like "100.000,45" or "100,000.45" or "1E12", try:

Private Sub TextBox1_Change()
If Len(TextBox1.Text) > 0 Then
If Asc(Right(TextBox1.Text, 1)) < 48 Or _
Asc(Right(TextBox1.Text, 1)) > 58 Then
TextBox1.Text = Left(TextBox1.Text, Len(TextBox1.Text) - 1)
End If
End If
End Sub

which allows for digits only (or for an empty textbox).

--

Greetings from Bavaria, Germany

Helmut Weber, MVP WordVBA

Vista Small Business, Office XP

Hi,

Thanks for your reply.

But how is your solution different from function IsNumeric?

Mike
 
H

Helmut Weber

Hi Mike,

as I wrote:

Isnumeric would be true for quite a lot of expressions, like
"100.000,45"
"100,000.45"
"1E12":

My solution allows only digits.
 

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