Question

I'm trying to list the columns in an Access table in the order in which they appear in the data rather than alphabetically.

This is the first method I tried. It gets the columns in alphabetical order.

Public Const adSchemaColumns = 4
Public Const adSchemaTables = 20

Dim oConn, oRecs
Set oConn = CreateObject("ADODB.Connection")
Set oRecs = CreateObject("ADODB.Recordset")

oConn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source='C:\whatever.mdb'"
Set oRecs = oConn.OpenSchema(adSchemaTables)

Do Until oRecs.EOF
    sTableName = oRecs("TABLE_NAME")

    If UCase(oRecs("TABLE_TYPE")) = "TABLE" Then
        Dim oTable
        Set oTable = oConn.OpenSchema(adSchemaColumns, Array(Null, Null, sTableName))

        Do Until oTable.EOF
            WScript.Echo oTable("COLUMN_NAME")
            oTable.MoveNext
        Loop

        Set oTable = Nothing
    End If

    oRecs.MoveNext
Loop

oRecs.Close
oConn.Close
Set oRecs = Nothing
Set oConn = Nothing

I also tried using ADOX catalogs, tables, and columns, but that also gets everything in alphabetical order. So if a table called Table1 has columns B, A, C in that order, both methods I've tried will print out A B C instead of B A C.

Can anyone shed some light on this?

Was it helpful?

Solution

The recordset from adSchemaColumns gives you COLUMN_NAME and ORDINAL_POSITION fields. So you can load those field values into a Scripting.Dictionary and later walk the dictionary in ORDINAL_POSITION order and .Echo COLUMN_NAME.

Here is a VBScript example for the columns in one table.

Option Explicit
Public Const adSchemaColumns = 4
Dim cn, rs, dct, i

Set dct = CreateObject("Scripting.Dictionary")
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
    "Data Source='C:\share\Access\database1.mdb'"
Set rs = cn.OpenSchema(adSchemaColumns, _
    Array(Null, Null, "tblFoo"))

With rs
    Do While Not .EOF
        dct.Add .Fields("ORDINAL_POSITION").Value, _
            .Fields("COLUMN_NAME").Value
        .MoveNext
    Loop
    .Close
End With

For i = 1 To dct.Count
    WScript.Echo dct(i)
Next

Set dct = Nothing
Set rs = Nothing
cn.Close
Set cn = Nothing

OTHER TIPS

This is a little old but for those scavenging the internet like me (and still using ADO/Access, though in Delphi), an alternative is to use the Sort method for the recordset. So knowing per the previous answer that the field is 'ORDINAL_POSITION' something like this would do, in Delphi or any ADO compatible language:

rs.Sort = 'ORDINAL_POSITION'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top