Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

excluding keypress characters

Status
Not open for further replies.

spannerman70

Programmer
Apr 9, 2001
6
GB
basically what i`m trying to do is allow text to be entered in a text box but not to allow a "-" in it unless its the very first character entered? want to bring up a msgbox then if it happens. Any help?
 
Spanner,
This is a link that will bring you to a chart that displays all of the ascii char codes and their corresponding ascii value

Here is an easy way to do it though. You don't even have to know the corresponding ascii value.
Put this in the textbox's keypress event...

If KeyAscii = Asc("-") Then
KeyAscii = 0
End If

Hope this helps!
Josh
 
Private text1_KeyPress(KeyAscci as Integer)
If KeyAscii = 8 then exit sub ' Backspace
With text1
' If after 0 or inserting any character before a "-"
If (Chr$(KeyAscii) = &quot;-&quot; and .SelStart <> 0) Or _
(.SelLength = 0 and Left$(.Text, 1) = &quot;-&quot;) then
KeyAscii = 0 ' Drop it
'MsgBox ' good idea???
Exit Sub
End if
End With
End Sub Compare Code (Text)
Generate Sort in VB or VBScript
 
Along the same lines as Josh has written you can then add this code to display a message and if it is the first character.

Private Sub textbox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)

If Len(textbox1) = 1 And KeyAscii = 45 Then
keyAscii = 0
MsgBox &quot;Error&quot;

End If

End Sub

Hope this helps Matt Smith

No two nulls are the same
 
That does not allow for inserting a &quot;-&quot; as first character or replacing the first character with a &quot;-&quot; and allows &quot;-&quot; as any character after the 2nd character.
At least change
If Len(textbox1) = 1 And KeyAscii = 45 Then
to
If Len(textbox1) >= 1 And KeyAscii = 45 Then


Compare Code (Text)
Generate Sort in VB or VBScript
 
Thanks for all your help people, this has given me enough to get on with it now, Cheers!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top