使用ADODB

时间:2017-03-17 17:21:07

标签: excel vba ado adodb

我能够连接和查询特定表格。某些文件可能具有不同或更改的第一个工作表名称,有时可能有多个。

我尝试了几个不同的函数来返回完整列表。但是,没有一个按照它们在Excel中显示的顺序给我工作表选项卡名称。

最简单的方法就是这样。

Set cat = CreateObject("ADOX.Catalog")
Set cat.ActiveConnection = objConnection
Debug.Print cat.Tables.Count

For Each tbl In cat.Tables
Debug.Print tbl.Name
Debug.Print tbl.datecreated
Debug.Print tbl.datemodified
Next tbl

我以为我可以通过datecreated或datemodified来确定,但所有4的日期都是相同的。

> This prints for me:
> Avion$
> 3/17/2017 12:43:19 PM
> 3/17/2017 12:43:19 PM
> Meow$
> 3/17/2017 12:43:19 PM
> 3/17/2017 12:43:19 PM
> Sheet1$
> 3/17/2017 12:43:19 PM
> 3/17/2017 12:43:19 PM
> Sheet2$
> 3/17/2017 12:43:19 PM
> 3/17/2017 12:43:19 PM

因此,它为我提供了工作表标签名称列表的字母排序。

但是工作表顺序是:

>[Sheet1][Avion][Sheet2][Meow]

我找不到任何财产来告诉我订单。

2 个答案:

答案 0 :(得分:1)

改编自:https://www.mrexcel.com/forum/excel-questions/406243-get-sheet-number-using-adox.html

Sub GetSheetNames()
    '###Requires a reference to Microsoft DAO x.x Object Library

     Dim FName As String, i As Long, WB As DAO.Database

     FName = ThisWorkbook.Path & "\ADOXSource.xlsx"


     Set WB = OpenDatabase(FName, False, True, "Excel 8.0;")

     With WB.tabledefs
         For i = 1 To .Count
             Debug.Print i, .Item(i - 1).Name '<< TableDefs Is zero based
         Next i
     End With

     WB.Close

End Sub

答案 1 :(得分:0)

这是我前几天用DAO建造的,但我还是想弄清楚ADO ......

Public Function GetSheets(ByVal FileToOpen As String, ByVal FileExt As String)
    Dim Shts() As String, ShtCnt As Integer: ShtCnt = 0
    ReDim Shts(0 To ShtCnt)

    Dim dbE As Object, db As Object, tbl As Object

    On Error Resume Next
    Set dbE = CreateObject("DAO.DBEngine")
    Set dbE = CreateObject("DAO.DBEngine.35")
    Set dbE = CreateObject("DAO.DBEngine.36")
    On Error GoTo 0

    Set db = dbE.OpenDatabase(FileToOpen, False, False, FileExt & ";HDR=Yes;")

    For Each tbl In db.TableDefs
       Shts(ShtCnt) = Mid(tbl.Name, 1, Len(tbl.Name) - 1)
       ShtCnt = ShtCnt + 1
       ReDim Preserve Shts(0 To ShtCnt)
    Next

    Set dbE = Nothing
    Set db = Nothing
    Set tbl = Nothing

    GetSheets = Shts
End Function

然后运行我有一堆开放对话框的代码,然后它确定格式和字符串:

Select Case Right(FileToOpen, Len(FileToOpen) - InStrRev(FileToOpen, "."))
    Case "xls", "XLS"
        Provider = "Microsoft.Jet.OLEDB.4.0;"
        FileExt = "Excel 8.0"
    Case "xlsx", "XLSX"
        Provider = "Microsoft.ACE.OLEDB.12.0;"
        FileExt = "Excel 12.0"
    Case "csv", "CSV"
        Provider = "Microsoft.Jet.OLEDB.4.0;"
        FileExt = "Excel 8.0"
    Case Else
        GoTo Err:
End Select

然后我有:

'Get Spreadsheets
Dim FileSpreadsheets() As String    
FileSpreadsheets = GetSheets(FileToOpen, FileExt)

然后你可以做任何你需要做的事情,但作为一个例子来获得一个msgbox:

mymsg = "Count: " & UBound(FileSpreadsheets) & vbNewLine & vbNewLine & _
"Sheets:" & vbNewLine & vbNewLine

For Each Sheet In FileSpreadsheets
    mymsg = mymsg + Sheet & vbNewLine
Next Sheet

MsgBox mymsg