How to deal with enter to tab in vb6

vb6

Public Function EnterToTab(KeyAscii As Integer)
    If KeyAscii = vbKeyReturn Then
        SendKeys "{tab}"
        KeyAscii = 0
    End If
End Function

Private Sub txtUserCode_KeyPress(KeyAscii As Integer)
    Call EnterToTab(KeyAscii)
End Sub
  • This code belongs to log-in form.
  • The txtUserCode contains code of specific user stored in database.
  • While running this form, when I enter any number in txtUserCode and press enter it doesn't go to next text box, it's keyascii became 49 which is not equal to 13.
  • The same thing is happening by pressing tab.

Best Answer

What about switching to the next text field using the setFocus method instead of simulating a TAB?

Private Sub txtUserCode_KeyPress(KeyAscii As Integer)
    If (KeyAscii = vbKeyReturn) Then
        txtNextTextField.setFocus
    End If
End Sub

You could also use a controls array (array of all text fields contained in your form) and increment the index. So you could use this code for all text fields of your form without having to write redundant code.

So if the user presses return in text field index 0, you set the focus to index+1 (=1). To create a controls array, copy your first text field and paste it to the form. VB6 will ask you whether you want to create a controls array. If you click "yes", it will do automatically. Then you can use the following code:

Private Sub txtField_KeyPress(Index As Integer, KeyAscii As Integer)
    If (KeyAscii = vbKeyReturn) Then
        If ((Index + 1) < txtField.Count) Then
            txtField(Index+1).setFocus
        Else
            MsgBox "Reached end of form!"
        End If
    End If
End Sub
Related Topic