EnterKey to press button in VBA Userform
Asked Answered
H

6

19

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)?

Hillel answered 1/10, 2013 at 20:24 Comment(2)
This is a duplicate of #22793336 (and the other one has a much better answer than any of these)Ramulose
Possible duplicate of Press enter in textbox and execute button function in VBAMarguritemargy
U
21

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

Uyekawa answered 1/10, 2013 at 21:56 Comment(9)
+1. This may be better or more precise than my answer, which would also fire the event on the Tab key, or a mouse-click out of the textbox.Racquelracquet
@DavidZemens, I get Compile error: Procedure declaration does not match description of event or procedure having the same name but I'm sure I don't have another EnterTextBox named procedure. TextBox1=EnterTextBox and Logincode_Click = CommandButton1_Clickin my example. What would I'm missing?Elector
@Elector I would suggest asking your own question :) it will before much easier to assist you if you ask a good question and include the code you're trying to use. it's v unlikely that anyone will respond to a comment on a 3 year old answer to someone else's question!Racquelracquet
haahah @DavidZemens I definitely know your point of view but I'm sure if I'll ask my own question people will mark it as duplicate, because it's really duplicate, even I might vote for duplication :) Jacob D seems like not visiting this site and as you were active in this question once upon a time I tagged you, but anyway sorry for inconvenience and thanks for your response. (ps: it's actually 4 years old! :) )Elector
@Elector people will be less-inclined to mark it as a duplicate if you link to this question (and/or this one and show the code you're using, explaining the specific problem and that you've tried to implement the other solutions (unsuccessfully). I'm sure you will have an answer that way :0Racquelracquet
+1, side note: KeyPress works in Access, but not in Excel mrexcel.com/forum/excel-questions/…Sodalite
Rather than the cryptic KeyCode = 13 use KeyCode = KeyCodeConstants.vbKeyReturn. This makes it clear in the code which button triggers that code. Plus, when searching for a button, you can type KeyCodeConstants. and intellisense shows a list of all available buttons. @drognisep posted a similar answer.Symphonia
In Excel, this code goes in the same worksheet module as the ActiveX button.Symphonia
@Elector I was also getting the Compile error: Procedure declaration does not match description of event or procedure having the same name error. Instead of using the arguments KeyCode As Integer, Shift As Integer I instead used ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer which fixed the issue.Knepper
R
21

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!

Retro answered 29/6, 2015 at 20:28 Comment(3)
+1 for using built in constants instead of cryptic numbers. Plus, if your looking for a specific button's keycode you can type KeyCodeConstants. and intellisense shows a drop-down list of keycodes for all buttons.Symphonia
I got an error without using the ByVal lines which the VBA Editor populated for me. As well, I love the rec to use vbXXX constants. vbKeyEscape Here is the list for anyone else! learn.microsoft.com/en-us/office/vba/language/reference/…Renascence
Also worth noting, I was able to use KeyUp for vbKeyEscape, but not for vbKeyReturn. While both worked w/ KeyDown. There for I'll only use KeyDown moving forward.Renascence
P
5

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
Paul answered 9/9, 2014 at 13:35 Comment(0)
D
3

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://mcmap.net/q/665472/-press-enter-in-textbox-and-execute-button-function-in-vba

Dasteel answered 22/3, 2017 at 12:51 Comment(0)
R
1

Use the TextBox's Exit event handler:

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Logincode_Click  
End Sub
Racquelracquet answered 1/10, 2013 at 21:11 Comment(5)
this doesnt seem to be working. where am i supposed to put this code. In the module of the userform?Hillel
Yes, this goes in the UserForm's module and make sure that the sub name TextBox1_Exit corresponds to your text box's name. So, if your textbox is called MyTextBox then it should be Private Sub MyTextBox_Exit(...Racquelracquet
But I think Jacob's answer below is more precise than mine. Same caveats to naming and placement of the subroutine in the UserForm's module.Racquelracquet
I get a compile error: Procedure declaration does not match description of event or procedure having the same name. it highlights the forst line :"Private Sub pwBox_KeyDown(KeyCode As Integer, Shift As Integer)" pwBox is the name of the textbox where they enter the password. thats where the average person just presses enter after having written their password and thus the code should run. Any idea why this doesn't compile?Hillel
If you're using @Jacob D's answer, I suggest you ask him :)Racquelracquet
A
0

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.

Ancell answered 28/8, 2017 at 8:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.