Text box restrictions

  • Thread starter Thread starter Sheldon
  • Start date Start date
S

Sheldon

In code how do I limit the values entered by the users. I
want only numbers.

Also, how do limit the number of characters entered to 5?

Thanks
 
Hi ,

My name is Dennis Schmidt. Thank you for using the Microsoft Newsgroups.

There are a couple of VBA functions that you could use on an event like
BeforeUpdate. They are the IsNumeric() and Len() functions. Code could
look something like this:

Dim ValueEntered
ValueEntered = Me!<control-name>
If Not IsNumeric(ValueEntered) then
MsgBox "Value is not a number"
Me!<control-name>.SetFocus
End If
If Len(ValueEntered) > 5 then
MsgBox "Value is too long"
Me!<control-name>.SetFocus
End If

I hope this helps! If you have additional questions on this topic, please
reply to this posting.

Need quick answers to questions like these? The Microsoft Knowledge Base
provides a wealth of information that you can use to troubleshoot a problem
or answer a question! It's located at
http://support.microsoft.com/support/c.asp?M=F>.

This posting is provided "AS IS" with no warranties, and confers no rights.
You assume all risk for your use. © 2001 Microsoft Corporation. All rights
reserved.

Regards,
Dennis Schmidt
Microsoft Support
 
The user should set Cancel=True if an error occurs, and the SetFocus is
neither necessary nor >possible< from BeforeUpdate, no?

TC
 
In code how do I limit the values
entered by the users. I want only
numbers.

Private Sub txtNumericOnly_KeyPress(KeyAscii As Integer)
If KeyAscii < Asc("0") Or KeyAscii > Asc("9") Then
KeyAscii = 0
End If
End Sub

This simply ignores any key pressed in the particular Control that is not
between 0 and 9. No error message, etc., but your users will soon get the
message, particularly if you put a little notice near the Control, saying
numeric values only, or, put it in the Status Bar Text for the Control.
Also, how do limit the number
of characters entered to 5?

The following does both, and always allows the Backspace so the user can
correct:

Private Sub txtNumericOnly_KeyPress(KeyAscii As Integer)
If KeyAscii <> 8 Then ' Backspace always valid
If KeyAscii < Asc("0") Or KeyAscii > Asc("9") Then
KeyAscii = 0
End If
If Len(Me!txtNumericOnly.Text) >= 5 Then
KeyAscii = 0
End If
End If
End Sub

Good luck with your project.

Larry Linson
Microsoft Access MVP
 
Back
Top