How can I check if a value entered into a text box is numeric or not? Thanks.
Printable View
How can I check if a value entered into a text box is numeric or not? Thanks.
If IsNumeric(Text1.Text) Then
IsNumeric Function Example:
This example uses the IsNumeric function to determine if a variable can be evaluated as a number.
VB Code:
Dim MyVar, MyCheck MyVar = "53" ' Assign value. MyCheck = IsNumeric(MyVar) ' Returns True. MyVar = "459.95" ' Assign value. MyCheck = IsNumeric(MyVar) ' Returns True. MyVar = "45 Help" ' Assign value. MyCheck = IsNumeric(MyVar) ' Returns False.
This stuff should work for integers -- off the top of my head (haven't tried it out though):
VB Code:
Private Function IsNumeric(ByVal argData As String) As Boolean Dim chrCtr As Long ' loop counter Dim curChr As String ' current character If Len(argData) = 0 Then Exit Function ' Run through the passed-in argument. For chrCtr = 1 To Len(argData) Let curChr = Mid$(chrCtr, argData, 1) ' get a character If curChr < "0" Or curChr > "9" Then Exit Function ' << BOOMER! not numeric Next chrCtr Let IsNumeric = True ' set retval (return value) End Function
BTW, I've developed an OCX which is basically a textbox that restricts input to numeric values. It doesn't allow the use of a mask but in addition to the numeric-only restriction and the normal textbox properties it has three new properties which I hope are self-explanatory:
CanBeNegative (Boolean)
CanHaveDecimals (Boolean)
MaxDecimals (Integer)
If anyone is interested I'll attach the OCX.
I'm interested.
(Source code included??)
Sure, why not. Make sure you store the OCX in your Windows System folder. Use the OCX and the code at your own risk. I just wrote it a couple of days ago and haven't spent a lot of time testing it although it seems to work correctly. If you find any bugs or if you have suggestions for improvement, please let me know.
I found a bug, but it should be simple to work around.Quote:
Originally posted by MartinLiss
...I just wrote it ... and haven't spent a lot of time testing it... If you find any bugs ... please let me know.
I downloaded the OCX and tried it out. The code seems pretty much OK for English locales ONLY. The decimal point is a comma in most European countries. Anyway, that is not a bug per se ... it is more like a lack of internationalization. The real bug is here:
1) In the number box, type "-153.45"
2) Press <Shift>+<Home>
3) Press <Shift>+<Delete>
4) Press <Shift>+<Insert>
5) Repeat step 4
After these 5 steps, your box will contain "-153.45-153.45".
You need to handle the <Insert> key either by disabling it, but will it then be possible to cause this error using the context menu? I think it would be better to move some of your code from the KeyPress event to the Change event.
Just a suggestion.
Thanks for the feedback. I probably won't do anything about the locale issue because I didn't write the code with distribution in mind, but I will certainly look into the bug you found.