EnterKey to press button in VBA Userform EnterKey to press button in VBA Userform vba vba

EnterKey to press button in VBA Userform


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

'Keycode for "Enter" is 13Private Sub TextBox1_KeyDown(KeyCode As Integer, Shift As Integer)    If KeyCode = 13 Then         Logincode_Click    End IfEnd 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


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!


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 IfEnd Sub