Using If Then statements to validate input text

NewJerseyDevils

New Member
Joined
Jan 14, 2004
Messages
1
I would like to use If Then statements to validate input text for a simple VB program. I am using:

Private Sub txtDecDegs_KeyPress(KeyAscii As Integer)
If KeyAscii < 47 And KeyAscii > 57 Then
MsgBox "Please enter numbers"
End If

But keypresses outside of my specified range (i.e. 47 to 57 or 0 to 9) are not bringing up the message box.

Any ideas?
 

Excel Facts

Move date out one month or year
Use =EDATE(A2,1) for one month later. Use EDATE(A2,12) for one year later.

anvil19

Board Regular
Joined
Nov 18, 2003
Messages
230
Hi NewJerseyDevils

No number can be less than 47 and greater than 57.

What you are looking for is a value that, if KeyAscii is not a number between 0 and 9, will fire the messageBox and end your Sub.

Try This:

Code:
Private Sub txtDecDegs_KeyPress(KeyAscii As Variant) 
Dim vara As Boolean
vara = True
vara = isnumeric(KeyAscii)
If vara = False or KeyAscii < 0 or KeyAscii > 9 Then
MsgBox "Please enter numbers between 0 and 9 only" 
End If
End Sub

This code doesn't do anything but determine if a value is a number between 0 and 9, or if it is indeed a number ,so we allow all input to be validated by the code.

Once you are clear about the code, you could adapt it to a Function that would return a value to a Sub that determines if a value is a number between 0 and 9 [Chr(47) to Chr(57)] and asks a user to only input these values.

By the way I'm not a fan of using the KeyPress Sub to validate values because it will be used every time the key is pressed rather than when you wish to validate text.

Try That

anvil19
:eek:
 

Watch MrExcel Video

Forum statistics

Threads
1,130,119
Messages
5,640,219
Members
417,131
Latest member
Seanr19871

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top