如何使用 VBA/ADO 将已关闭的 XLS 文件中的 excel 工作表复制到字符串数组中?

How can I copy an excel worksheet from a closed XLS file into a string array using VBA/ADO?

我需要快速有效地从大量 xls 文件中获取一些数据。 为每个打开 excel 的新实例很慢并且会导致各种问题。 我已经看到一些关于如何使用 ADO 打开 XLS 文件的基本答案。

我想要一个以文件名和工作sheet名称作为输入,以字符串数组作为输出的适当函数。

可以直接调用的东西windows,这里有一个例子/

sheet 的例子

立即window:

print XLStoArray("C:\test.xls","Sheet1$")(1,1)
hello, test !

这是我迄今为止的最佳答案,它可能不是 fastest/cleanest 可能的方式,但它有效!

'In VBA IDE, go to Tools -> References... and add "Microsoft ActiveX Data Objects 2.1 Library"  (may work with other versions)
Function ADOXLStoArray(FilePath As String, SheetName As String, Optional ColumnLimit As Long) As String()
    
    If FileExists(FilePath) = False Then Debug.Print "file does not exist": Exit Function
    
    Dim Connection As ADODB.Connection, RecordSet As ADODB.RecordSet, myArray() As String
    Set Connection = ADOGetDBConnection(FilePath)
    Set RecordSet = ADOGetRecordSet(Connection, SheetName)
    ReDim myArray(RecordSet.RecordCount, RecordSet.Fields.Count - 1)
    
    Dim x As Long, y As Long
    
    For y = 0 To RecordSet.Fields.Count - 1
        myArray(x, y) = IIf(IsNull(RecordSet.Fields(y).Name), "", RecordSet.Fields(y).Name)
    Next y
    
    x = x + 1
    
    While (Not RecordSet.EOF)
        For y = 0 To RecordSet.Fields.Count - 1
            myArray(x, y) = IIf(IsNull(RecordSet.Fields(y).Value), "", RecordSet.Fields(y).Value)
        Next y
        x = x + 1
        RecordSet.MoveNext
    Wend

    ADOXLStoArray = myArray
End Function

Function ADOGetDBConnection(FilePath As String) As ADODB.Connection
    Set ADOGetDBConnection = New ADODB.Connection
    ADOGetDBConnection.Provider = "Microsoft.ACE.OLEDB.12.0"
    ADOGetDBConnection.ConnectionString = "Data Source=" & FilePath & ";Extended Properties = 'Excel 12.0 Xml;HDR =YES'"
    ADOGetDBConnection.Open
End Function

Function ADOGetRecordSet(Connection As ADODB.Connection, SheetName As String) As ADODB.RecordSet
    Dim myRecordSet As New ADODB.RecordSet
    myRecordSet.CursorType = adUseClient
    myRecordSet.Open "Select * FROM [" & SheetName & "]", Connection
    Set ADOGetRecordSet = myRecordSet
End Function