2014-03-18 92 views
1

VBScript中得到Access列我試圖列出它們出現在數據,而不是按字母順序排列的順序在Access表中的列。數據順序

這是我嘗試的第一個方法。它按字母順序獲取列。

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 

我也試過使用ADOX目錄,表和列,但也按字母順序得到一切。所以,如果一個名爲Table 1表中具有的順序B,A,C柱,我已經試過這兩種方法將打印出A B C代替B A C的

任何人都可以闡明這一些輕?

回答

2

adSchemaColumns的記錄集給你COLUMN_NAMEORDINAL_POSITION字段。所以,你可以將這些字段值加載到Scripting.Dictionary,後來走字典中ORDINAL_POSITION秩序和.Echo COLUMN_NAME

下面是在一個表中的列一個VBScript例子。

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 
+1

這非常完美,正是我需要的。非常感謝! –