I have a TextBox and a Listbox in EXCEL VBA project. I need to insert value using textbox control.
Every time I click on Enter, the value in the textbox control is added to the listbox below and the textbox control is emptied.
I need to set set focus on the textbox control for a new insertion. I have a problem with the .SetFocus
, it does not work! I can't set the .SetFocus
on the textbox control after each insertion.
I have also used events _AfterUpdate
, _BeforeUpdate
, _Change
, _Enter
, _KeyDown
and _KeyUp
with the same result.
I used this code
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode <> 13 Then Exit Sub
Me.ListBox1.AddItem Me.TextBox1.Text
Me.TextBox1.Text = ""
Me.TextBox1.SetFocus
End Sub
You are on the right track. No need to set focus back to TextBox1
. All you have to do is set the Keycode
to 0
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode <> 13 Then Exit Sub
Me.ListBox1.AddItem Me.TextBox1.Text
Me.TextBox1.Text = ""
KeyCode = 0
End Sub