Search code examples
excelvbakeypress

How to prevent cursor from moving to next textbox when Enter key is pressed?


I want to prevent the cursor from moving to next textbox when the textbox is empty and Enter key is pressed. Suppose I have two textbox, Textbox1 and Textbox2 and what I want is until unless I enter anything in Textbox1, it should not allow moving cursor from Textbox1 to Textbox2 when enter key is pressed. But it should allow moving cursor manually using mouse or arrow keys. Hope it explains everything. I tried following,

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

    If Trim(Me.txtCode) = "" And KeyCode = 13 Then
        Me.txtCode.SetFocus
    End If

End Sub

But no good


Solution

  • You were close. Try the following:

    Private Sub txtCode_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
       If Trim(Me.txtCode) = "" And KeyCode = 13 Then
           KeyCode = 0
       End If
    End Sub
    

    Setting the KeyCode to 0 effectively cancels the keystroke.