EnterKey to press button in VBA Userform

后端 未结 6 950
春和景丽
春和景丽 2020-12-31 04:45

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 <

相关标签:
6条回答
  • 2020-12-31 05:14

    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.

    0 讨论(0)
  • 2020-12-31 05:15

    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!

    0 讨论(0)
  • 2020-12-31 05:15

    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
    
    0 讨论(0)
  • 2020-12-31 05:28

    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

    0 讨论(0)
  • 2020-12-31 05:29

    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

    0 讨论(0)
  • 2020-12-31 05:31

    Use the TextBox's Exit event handler:

    Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        Logincode_Click  
    End Sub
    
    0 讨论(0)
提交回复
热议问题