Run VBA when ENTER is pressed

Hi Experts,

I have a form with a text box named txtTicket#.  I want some code that when the Enter button on the keyboard is pressed (only if this field has focus) it will run an update query and set the field back to blank.  I know how to do everything except tell Access to run these commands only when enter is pressed.

Thanks,
Cody
Cody VanceSr. Analyst - ERPAsked:
Who is Participating?
 
DatabaseMX (Joe Anderson - Microsoft Access MVP)Connect With a Mentor Database ArchitectCommented:
Typo:


Private Sub txtYourTextBoxName_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = vbKeyReturn Then
        KeyCode = 0
        'run your code here
    End If
End Sub
0
 
Rey Obrero (Capricorn1)Commented:
you need to set the key Preview property of the form to YES
0
 
DatabaseMX (Joe Anderson - Microsoft Access MVP)Database ArchitectCommented:
Do you mean this:

Private Sub txtYourTextBoxName_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = vbkeyenter Then
        KeyCode = 0
        'run your code here
    End If
End Sub

mx
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
Cody VanceSr. Analyst - ERPAuthor Commented:
Thanks Cap & MX.  DO I need to enable Key Preview with MXs code as well?
0
 
Jeffrey CoachmanMIS LiasonCommented:
For me, I like to reserve the Enter key for it's default functionality.
I just don't like trying to "Tack on" things done when the Enter key is pressed.

I would try to find a more appropriate Event to run this code...
(Before Update event of the form, so it can be canceled if need be)

The enter key can be pressed while a user is in the textbox for any number of reasons, thus triggering your code unintentionally.

What is your plan to roll back the code if the enter key is hit by mistake, or hit more than once?
0
 
DatabaseMX (Joe Anderson - Microsoft Access MVP)Database ArchitectCommented:
"DO I need to enable Key Preview with MXs code as well?"
Yes.

mx
0
 
Rey Obrero (Capricorn1)Connect With a Mentor Commented:
<DO I need to enable Key Preview>  That is the very first thing that you should do.

if not The CODES posted are meaningless (will not execute)
0
 
Cody VanceSr. Analyst - ERPAuthor Commented:
Got it, thank you both.  Points to follow.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.