Search This Blog

Tuesday, 16 August 2016

MAKE NEXT CONTROL VISIBLE ONCE THE FOCUS LOSES FROM FIRST CONTROL (KEYDOWN EVENT)

Below is the code to make next textbox visible once you finish typing in first textbox and press enter key or tab.

Controls on my form:

4 labels: lblCode, lblName, lblDept and lblDesig

4 textboxes: txtCode, txtName, txtDept and txtDesig

1 CommandButton: cmdSubmit

First I have made all the controls invisible except first textbox and label (lblcode & txtcode in my case) while loading the userform.

Private Sub UserForm_Initialize()

Me.txtCode.SetFocus

Me.txtName.Visible = False

Me.txtDept.Visible = False

Me.txtDesig.Visible = False

Me.lblName.Visible = False

Me.lblDept.Visible = False

Me.lblDesig.Visible = False

Me.cmdSubmit.Visible = False

End Sub

Only the first textbox and label will be visible when userform loads.

Below code on KeyDown Event of txtCode will make next set of controls (lblName & txtName) visible when you press enter key or tab key after typing in first textbox (txtCode) and set the focus on txtName.

Below code on KeyDown Event of txtName will make next set of controls (lblDept & txtDept) visible when you press enter key or tab key after typing in second textbox (txtName) and set the focus on txtDept.

Private Sub txtName_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = vbKeyReturn Or KeyCode = vbKeyTab Then
If txtName <> vbNullString Then
txtDept.Visible = True
lblDept.Visible = True
txtDept.SetFocus
End If
End If
End Sub

Below code on KeyDown Event of txtDept will make next set of controls (lblDesig & txtDesig) visible when you press enter key or tab key after typing in third textbox (txtDept) and set the focus on txtDesig.