select case keypress

Forum home » Delegate support and help forum » Microsoft Excel VBA Training and help » Select Case on Keypress

Select Case on Keypress

resolvedResolved · Medium Priority · Version 2007

Richard has attended:
Excel Advanced course
Excel VBA Intro Intermediate course
Excel VBA Advanced course

Select Case on Keypress

Hi.
I am creating a series of userforms with validations ie "number" fields should be numeric etc and I am using the following code to check this:
Private Sub Assignment_Field_NewEmployeeApplication_UF_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Assignment = Assignment_Field_NewEmployeeApplication_UF.Value
Select Case KeyAscii
'only numbers and - allowed
Case 45, 48 To 57
Case Else
MsgBox "Assignment Number must be Numeric"
End Select
End Sub
This works great however this still allows an incorrect character to be entered into the field.
I have tried simply deleting the last character with this code after the msgbox:
Assignment = Left(Assignment, Len(Assignment) - 1)
Assignment_Field_NewEmployeeApplication_UF.Value = Assignment
But this does not work as at that stage it seems the character is not in the field to be deleted. Stepping through the process does not show when the character is placed, but by running the procedure it places it.
Also - I would like to check the characters if the field was pasted into, I see there is "BeforeDropOrPaste" rather than keypress, but could you advise if I can somehow use a similar process to keypress (ie as above) for this type of event?
Any help is appreciated! Thank you

RE: Select Case on Keypress

Hi Richard

One way to delete the incorrect character is to include the line:
SendKeys "{BS}"
after your Msgbox

The SendKeys statement sends the Backspace keystroke as if typed from the keyboard.

It seems to work!

Doug Dunn
Best STL

RE: Select Case on Keypress

Hi Doug

Thank you for your response. I tried the SendKeys you suggested but this turns off NUMLOCK!
I have done a quick search and (you may well know already) found this is a known Microsoft bug.
I have now however solved my problem by creating a boolean statement and if the result is true, removing the last letter during the change event.

Thank you for your help anyway!

I will mark as resolved.

Kind regards
Richard

 

Training courses

 

Training information:

Welcome. Please choose your application (eg. Excel) and then post your question.

Our Microsoft Qualified trainers will then respond within 24 hours (working days).

Frequently Asked Questions
What does 'Resolved' mean?

Any suggestions, questions or comments? Please post in the Improve the forum thread.


 

Excel tip:

Paste a web address into the hyperlink address field

If you copy a web address the only way to paste into the address field of the hyperlink box is to use CTRL + V. Right click paste does not work.

View all Excel hints and tips


Server loaded in 0.08 secs.