Option Compare Database
Option Explicit
Public Sub AlphabetizeTable(TableName As String)
Dim tdf As TableDef
Dim colSort As New Collection
Dim fld As DAO.Field
Dim db As DAO.Database
Dim i As Integer
Set db = CurrentDb
Set tdf = db.TableDefs(TableName)
For Each fld In tdf.Fields
If colSort.Count = 0 Then
colSort.Add fld.Name, fld.Name
Else
For i = 1 To colSort.Count
If IsPK(tdf, fld.Name) Then
colSort.Add fld.Name, fld.Name, i
Exit For
ElseIf fld.Name < colSort(i) And Not IsPK(tdf, colSort(i)) Then
colSort.Add fld.Name, fld.Name, i
Exit For
ElseIf colSort.Count = i Then
colSort.Add fld.Name, fld.Name
Exit For
End If
Next i
End If
Debug.Print "fld " & fld.Name
Next fld
For i = 1 To colSort.Count
Debug.Print colSort(i)
tdf.Fields(colSort(i)).OrdinalPosition = i
Next i
End Sub
Public Function IsPK(tdf As TableDef, fldName As String) As Boolean
Dim idx As DAO.Index
Dim fld As DAO.Field
For Each idx In tdf.Indexes
'Debug.Print "IDX" & idx.Name
If idx.Name = "Primarykey" Then
For Each fld In idx.Fields
If fld.Name = fldName Then
IsPK = True
Exit Function
End If
Next fld
End If
Next idx
End Function
Public Sub testit()
AlphabetizeTable "customers"
End Sub
Public Sub TestAll()
Dim tdf As TableDef
For Each tdf In CurrentDb.TableDefs
If Left(tdf.Name, 4) <> "MSYS" Then AlphabetizeTable (tdf.Name)
Next tdf
End Sub