EnterKey click a button in VBA Userform

I have a custom form in Excel that asks for a username and password. After entering the password, if you press Enter , it simply “selects” the next element, which is the LogIn button, but does not click on it. To actually press the button, you need to press Enter again.

How can I do this when the user presses the enter button on his keyboard, the login button is pressed and the code associated with it ( Logincode_click ) is Logincode_click ?

+7
vba excel
source share
6 answers

You can also use the TextBox 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 

Text field1 is an example. Make sure that you select the text field that you want to access, as well as Logincode_Click - an approximate sub that you call (run) with this code. Make sure you link to your preferred south

+8
source share

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

In this case, we could use vbKeyReturn to specify the key of the input key (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.

Hooray!

+6
source share

It 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 
+4
source share

Use the TextBox Exit event handler:

 Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean) Logincode_Click End Sub 
+1
source share

In addition to the comment by @Penn, and in case of breaking the link, you can also achieve this by setting the Default property to the True button (you can set this in the properties window, open it by pressing F4 )

That way, when Return is triggered, VBA knows to trigger a button click event. Likewise, setting the Cancel property of a button to True will cause the button's click event to be triggered whenever the ESC key is pressed (useful for gracefully exiting a user form).


Source: Olivier Jacot-Descombes answer is available here

0
source share

Here you can simply use:

SendKeys "{ENTER}" at the end of the code associated with the Username field.

And you can skip pressing the ENTER key once (once).
And as a result, the next button will be activated (the "Login" button). And when you press ENTER once (your desired result), it will run the code associated with the Login button.

0
source share

All Articles