|
-
Dec 7th, 2001, 05:09 PM
#1
Thread Starter
New Member
How to stop users typing in anything but numbers in txtbox.
This is a simple one.
How do I make sure I don't get a type miss match error. For example if I have 2 text boxes which I only want integers typed in and not letters how would I code this.
Once I have got the code going, would it be better to make say letters off limits or should I chuck up a msgbox and tell the user that only numbers can be typed?
Is there a way of stopping all but numbers being typed into a textbox?
Thanks
-
Dec 7th, 2001, 05:13 PM
#2
PowerPoster
There is a way to only allow numbers without alerting the user that he/she types a wrong character.
Try this code:
VB Code:
Private Sub Text1_KeyPress(KeyAscii As Integer)
'ensure we only accept numeric input
KeyAscii = NumericOnly(KeyAscii)
End Sub
Public Function NumericOnly(KeyAscii As Integer) As Integer
'if the key passed to this function is not a number
If Not IsNumeric(Chr$(KeyAscii)) And Not KeyAscii = vbKeyBack Then
'return 0
NumericOnly = 0
Else
'return the same key
NumericOnly = KeyAscii
End If
End Function
-
Dec 7th, 2001, 05:17 PM
#3
Hyperactive Member
Here is a code I am using which only allows type numeric numbers positive or negative and also use . or , for decimal separation depending on Windows configuration
VB Code:
Private Sub Text1_KeyPress(KeyAscii As Integer)
Dim texte As String, decimalpoint As String
decimalpoint = Mid$(Format(0, "0.0"), 2, 1)
texte = Text1.Text
If Text1.SelStart = 0 And Text1.SelLength = 0 And InStr(texte, "-") Then
KeyAscii = 0
Exit Sub
End If
If KeyAscii > 31 And (KeyAscii < 44 Or KeyAscii > 57 Or KeyAscii = 47) Then KeyAscii = 0
If (KeyAscii = 46 Or KeyAscii = 44) And (InStr(texte, ".") Or InStr(texte, ",")) Then
KeyAscii = 0
ElseIf (KeyAscii = 46 Or KeyAscii = 44) Then KeyAscii = Asc(decimalpoint)
End If
If KeyAscii = 45 Then
If Left$(texte, 1) <> "-" And Len(texte) > 0 Then
KeyAscii = 0
Text1.Text = "-" & texte
Text1.SelStart = Len(Text1.Text)
ElseIf Len(texte) > 0 Then
KeyAscii = 0
End If
End If
End Sub
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|