Thursday, May 14, 2009

Tab Index Made Simple

SetTabIndex recursively collects the controls on the form, sorts them from top to bottom, and sets the tab index. Just add "SetTabIndex(Me)" to your form load event.
'SetTabIndex by Chris Hatcher
'http://vbdotsimple.blogspot.com/
Public Sub SetTabIndex(ByVal oParent As Object)
Dim colChildren As New Collection 'Kids under parent
Dim oChild As Control 'Loop variable for kids
Dim iSort() As Integer 'Sort index for kids
Dim iIndex As Integer 'Loop index for kids

For Each oChild In oParent.Controls 'For each kid...
colChildren.Add(oChild) 'Add it to collection
SetTabIndex(oChild) 'Recurse for grandkids
Next 'Next

SortObjByLoc(colChildren, iSort) 'Sort kids by location

For iIndex = 1 To colChildren.Count 'Assign tab index by sort
colChildren.Item(iSort(iIndex)).TabIndex = iIndex
Next
End Sub

'InsertionSort by David B. Ring
'http://www.devx.com/vb2themax/Tip/19469
'Modified to sort controls from top to bottem, left to right
Private Sub SortObjByLoc(ByVal A As Collection, ByRef P() As Integer)
Dim LP As Long
Dim RP As Long
Dim TMP As Long

Dim lTop As Long
Dim lLeft As Long

Dim L As Long = 1
Dim R As Long = A.Count

ReDim P(R)
For TMP = L To R
P(TMP) = TMP
Next

For RP = L + 1 To R
TMP = P(RP)
lTop = A(TMP).Top
lLeft = A(TMP).Left
For LP = RP To L + 1 Step -1
If lTop < A(P(LP - 1)).Top _
Or lTop = A(P(LP - 1)).Top And lLeft < A(P(LP - 1)).Left Then
P(LP) = P(LP - 1)
Else
Exit For
End If
Next LP
P(LP) = TMP
Next RP
End Sub
Enjoy.

No comments:

Post a Comment