Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Press enter in textbox and execute button function in VBA

I have a login form to my database done in Access 2010 and using VBA code. I want to be able to press Enter on txtboxPassword and automatically execute 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 self-made error saying Password is incorrect. If I debug I see that actually txtPassword is null, but I just typed the text in it!

However If I click the Login button with the mouse it works perfect. Why does vba behave like that? How can I do it to make it work?

NOTE I also tried with:

  • KeyPress: after I press Enter the focus goes to btnLogin (maybe also because the tab order is like that), but the btnLogin_Click event is not executed.
  • KeyUp: same like KeyPress.
like image 690
EricPb Avatar asked Apr 01 '14 17:04

EricPb


People also ask

How do I run a button in VBA?

Go to the Developer tab in the ribbon. Select the Button Form Control from the menu. Right click and hold the mouse then drag and release to create your button. The Assign Macro window will pop up and you can select the VBA procedure you want to run from the button.

How do I click a command button in VBA?

VBA ActiveX CommandButton Control on the WorksheetGo To Developer Tab and then click Insert from the Controls group. Click on the Command Button from the ActiveX Controls group. Drag a Command Button on the Worksheet. Right click on the Command Button, before that Design Mode should be turned ON.

How do you use TextBox in VBA?

Step 1: Insert a new UserForm in your VBA and add TextBox in it. Step 2: Change the name of TextBox under Properties section to “My_Age”. Step 3: Double click on TextBox or right click on it and select View Code. Step 4: Now, try to add an If the condition which starts with If Not.


1 Answers

The buttons in Access have a property called Default (on the Other property page). If you set it to Yes the form calls the button click event handler automatically, when you press Enter. No need for additional Key-event handling.

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

like image 145
Olivier Jacot-Descombes Avatar answered Sep 19 '22 16:09

Olivier Jacot-Descombes