Using KeyAscii and MSForms.ReturnInteger

C

call_me_sol

Hi -

I'm using the following code in a userform to prevent users from
entering a space in a textbox:


Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If (KeyAscii = 32) Then
MsgBox "Please enter customer name without using spaces",
vbOKOnly + vbExclamation
KeyAscii = 0
Exit Sub
End If
End Sub

This works fine -- if the user is typing in the box
This does not work fine if the user copies and pastes into the box
(the box will accept the space)


Can someone suggest a way to fix?

Thank you!
 
D

Doug Robbins - Word MVP

You could use the Instr() function in the Exit event of the textbox to test
if there is a space

--
Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins - Word MVP
 
C

call_me_sol

Thanks Doug -- that worked. Question, though: why? I mean why
(using ByVal KeyAscii As MSForms.ReturnInteger) was I able to paste
into the box without error but typing in the box was correctly
prevented? I have a lot of userforms that use that bit of code and
I'm going to have to fix all of them. While using the InStr function
works, there could be a million things that I'll need to watch out for
(like users copying/pasting any type punctuation in the box)

Private Sub TextBox3_Exit(ByVal Cancel As MSForms.ReturnBoolean)
With Me.TextBox3
If InStr(.Text, " ") Then
MsgBox "Please do not use any spaces in this box"
Cancel = True
End If
If InStr(.Text, "'") Then
MsgBox "Please do not use any spaces in this box"
Cancel = True
End If
If InStr(.Text, ";") Then
MsgBox "Please do not use any spaces in this box"
Cancel = True
End If
If InStr(.Text, "/") Then
MsgBox "Please do not use any spaces in this box"
Cancel = True
End If
End With
End Sub
 
D

Doug Robbins - Word MVP

Because when pasting, you were not inserting an ASCII character 32 from the
keyboard. If it was there, it was coming from the clipboard, not the
keyboard. A slight difference.

--
Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins - Word MVP
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top