开发者

Keep focus on textbox after pressing enter

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:

Pr开发者_如何转开发ivate 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜