Press Enter in the text box and execute the button function in VBA

I have a login form to my database, made in Access 2010, and using VBA code. I want to be able to press Enter on txtboxPassword and automatically execute the btnLogin_Click event. I tried this:

 Private Sub txtboxPassword_KeyDown(KeyCode As Integer, Shift As Integer) If KeyCode = 13 Then btnLogin_Click End If End Sub 

What I get is a makeshift error as the password is incorrect. If I'm debugging, I see that txtPassword is actually null , but I just typed in it!

However, if I click the Login button with the mouse, it works perfectly. Why does VBA behave like this? How can I make it work?

NOTE I also tried:

  • KeyPress: after pressing Enter, the focus switches to btnLogin (possibly also because the tab order is similar to this), but the btnLogin_Click event btnLogin_Click not executed.
  • KeyUp: same as KeyPress.
+4
vba ms-access ms-access-2010
source share
4 answers

Buttons in Access have a Default property (on the Other property page). If you set it to Yes, the form calls it automatically when you press Enter . There is no need to handle key events.

There is also a Cancel property. If you set the Yes button for it, the form will automatically activate it when the user types Esc-key . Very practical for cancel buttons.

+5
source share

to activate KeyCode, you need to set the Key Preview property in the YES form (it will be at the bottom)

 If KeyCode = vbKeyReturn Then Your_fuction_here End If 
+1
source share

It is impossible to reproduce exactly your problem, but some time ago I had a somewhat similar problem and it was solved by adding:

 Private Sub txtboxPassword_KeyDown(KeyCode As Integer, Shift As Integer) If KeyCode = 13 Then btnLogin_Click KeyCode.Value = 0 End If End Sub 
0
source share

On the button you want to take, go to the "Other" properties and set the "Default" to "Yes." Then, when you press enter, when the button will act in the text box.

0
source share

All Articles