Keep focus on textbox after pressing enter

蓝咒 提交于 2019-12-07 03:16:38

问题


How can I keep the focus in a textbox after pressing enter in a VBA form?

This code adds the text to a Listbox and I want to keep the focus on the textbox to get ready to receive another item.

When I click in the button Add, it adds the text to the Listbox and returns the focus to the textbox, howerver when I press enter it doesn't, even tough it uses the same code. Any suggestion?

This is my code for the textbox:

Private Sub TxtOtherAsset_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)

    If KeyCode = 13 Then
        CmdAddOtherAsset_Click
    End If

End Sub

and this is the code for my button:

Private Sub CmdAddOtherAsset_Click()

    If TxtOtherAsset.Text <> "" Then
        ListAddedAssets.AddItem TxtOtherAsset.Text
        TxtOtherAsset.Text = ""
    End If

    TxtOtherAsset.SetFocus

End Sub

I've tried several ways, but I'm not able to return the focus to the textbox. After pressing enter, the focus goes to the next in the TabIndex.


回答1:


From the top of my head: try setting the KeyCode to 0. Also, use the KeyCodeConstants class (from the Core library) to determine what value the Enter key is.

Like this:

If KeyCode = KeyCodeConstants.vbKeyReturn Then
    CmdAddOtherAsset_Click
    KeyCode = 0
End If

Remove the line you're trying to set the focus on the other sub (TxtOtherAsset.SetFocus).

Hope it works for you. I did not test it.




回答2:


Are you using the Enter key as a trigger to catch changes to the text box? If that's the case, try the After Update event instead. Also, take a look at the On Exit event. When I looked, I noticed it has a Cancel parameter. If you still want to catch the Enter key in the Key Down event, you could possibly the On Exit event to prevent leaving the text box. Of course, that probably means you're permanently stuck and may need to set up a way to allow exiting.



来源:https://stackoverflow.com/questions/6685661/keep-focus-on-textbox-after-pressing-enter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!