Keep focus on textbox after pressing enter

rubenploneda picture rubenploneda · Jul 13, 2011 · Viewed 20.6k times · Source

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.

Answer

Oneide picture Oneide · Jul 14, 2011

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.