Tab order can be a little tricky since
1. the order can be rearranged by the developer:
Capture.JPG
2. You can't rely on the .Name of the control
3. Other types of controls can receive the Focus in the TabOrder
Try the attachment
Standard module
Option Explicit
Public aTextBoxes() As clsTextBox
Public aTabOrders() As Long
Sub drv()
Load UserForm1
UserForm1.Show
End Sub
Class module
Option Explicit
Public WithEvents enhTextBox As MSForms.TextBox
Private Sub enhTextBox_Change()
Dim i As Long
If Not enhTextBox.Text Like "#" Then
Application.EnableEvents = False
enhTextBox.Text = vbNullString
Application.EnableEvents = True
Else
For i = LBound(aTabOrders, 1) To UBound(aTabOrders, 1)
If aTabOrders(i, 0) = enhTextBox.TabIndex Then
If i = UBound(aTabOrders, 1) Then
aTextBoxes(LBound(aTabOrders, 2)).enhTextBox.SetFocus
Else
aTextBoxes(aTabOrders(i + 1, 1)).enhTextBox.SetFocus
End If
Exit For
End If
Next I
End If
End Sub
Userform
Option Explicit
Private Sub UserForm_Initialize()
Dim oControl As Control
Dim cnt As Long, i As Long, j As Long, x As Long
cnt = 0
For Each oControl In Me.Controls
If TypeName(oControl) = "TextBox" Then
cnt = cnt + 1
ReDim Preserve aTextBoxes(0 To cnt - 1)
Set aTextBoxes(cnt - 1) = New clsTextBox
Set aTextBoxes(cnt - 1).enhTextBox = oControl
End If
Next
'row = number aTextBoxes, col = tab order and aTexbox index
ReDim aTabOrders(LBound(aTextBoxes) To UBound(aTextBoxes), 0 To 1)
For cnt = LBound(aTextBoxes) To UBound(aTextBoxes)
aTabOrders(cnt, 0) = aTextBoxes(cnt).enhTextBox.TabIndex
aTabOrders(cnt, 1) = cnt
Next cnt
For i = LBound(aTabOrders, 1) To UBound(aTabOrders, 1) - 1
For j = i To UBound(aTabOrders, 1)
If aTabOrders(i, 0) > aTabOrders(j, 0) Then
x = aTabOrders(i, 0)
aTabOrders(i, 0) = aTabOrders(j, 0)
aTabOrders(j, 0) = x
x = aTabOrders(i, 1)
aTabOrders(i, 1) = aTabOrders(j, 1)
aTabOrders(j, 1) = x
End If
Next j
Next i
End Sub
Private Sub UserForm_Terminate()
Erase aTextBoxes
End Sub