[excel] EnterKey to press button in VBA Userform

I have a userform in Excel that asks for a username and password. Once you enter your password if you press Enter it just "selects" the next item which is the LogIn button, but it doesn't press it. You have to hit Enter again to actually press the button.

How can I make it so when the user presses enter on his keyboard the LogIn button is pressed and the code associated to is runs (Logincode_click)?

This question is related to excel vba

The answer is


Use the TextBox's Exit event handler:

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Logincode_Click  
End Sub

You could also use the TextBox's On Key Press event handler:

'Keycode for "Enter" is 13
Private Sub TextBox1_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = 13 Then
         Logincode_Click
    End If
End Sub

Textbox1 is an example. Make sure you choose the textbox you want to refer to and also Logincode_Click is an example sub which you call (run) with this code. Make sure you refer to your preferred sub


This one worked for me

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        If KeyCode = 13 Then
             Button1_Click
        End If
End Sub

Be sure to avoid "magic numbers" whenever possible, either by defining your own constants, or by using the built-in vbXXX constants.

In this instance we could use vbKeyReturn to indicate the enter key's keycode (replacing YourInputControl and SubToBeCalled).

   Private Sub YourInputControl_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        If KeyCode = vbKeyReturn Then
             SubToBeCalled
        End If
   End Sub

This prevents a whole category of compatibility issues and simple typos, especially because VBA capitalizes identifiers for us.

Cheers!


Further to @Penn's comment, and in case the link breaks, you can also achieve this by setting the Default property of the button to True (you can set this in the properties window, open by hitting F4)

That way whenever Return is hit, VBA knows to activate the button's click event. Similarly setting the Cancel property of a button to True would cause that button's click event to run whenever ESC key is hit (useful for gracefully exiting the Userform)


Source: Olivier Jacot-Descombes's answer accessible here https://stackoverflow.com/a/22793040/6609896


Here you can simply use:

SendKeys "{ENTER}" at the end of code linked to the Username field.

And so you can skip pressing ENTER Key once (one time).
And as a result, the next button ("Log In" button here) will be activated. And when you press ENTER once (your desired outcome), It will run code which is linked with "Log In" button.