VBA - 从电子表格的内容创建ADODB.Recordset

rob*_*ult 4 excel vba adodb recordset

我正在研究一个查询SQL数据库的Excel应用程序.查询可能需要很长时间才能运行(20-40分钟).如果我错过了编码,可能需要很长时间才能出错或达到断点.我可以将结果保存到工作表中,当我使用记录集时,事情会爆炸.

当我调试跳过查询数据库时(第一次之后),有没有办法将数据加载到ADODB.Recordset?

我会用这样的东西吗?

在MS-Access VBA中查询Excel工作表(使用ADODB记录集)

rob*_*ult 7

我不得不安装MDAC来获取msado15.dll,一旦我拥有它,我就从(在Win7 64bit上)添加了一个引用:

C:\ Program Files(x86)\ Common Files\System\ado\msado15.dll

然后我创建了一个函数,通过传入当前活动工作簿中存在的工作表名称来返回ADODB.Recordset对象.这是其他任何人的代码,如果他们需要它,包括一个Test()Sub来查看它是否有效:

Public Function RecordSetFromSheet(sheetName As String)

Dim rst As New ADODB.Recordset
Dim cnx As New ADODB.Connection
Dim cmd As New ADODB.Command

    'setup the connection
    '[HDR=Yes] means the Field names are in the first row
    With cnx
        .Provider = "Microsoft.Jet.OLEDB.4.0"
        .ConnectionString = "Data Source='" & ThisWorkbook.FullName & "'; " & "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"
        .Open
    End With

    'setup the command
    Set cmd.ActiveConnection = cnx
    cmd.CommandType = adCmdText
    cmd.CommandText = "SELECT * FROM [" & sheetName & "$]"
    rst.CursorLocation = adUseClient
    rst.CursorType = adOpenDynamic
    rst.LockType = adLockOptimistic

    'open the connection
    rst.Open cmd

    'disconnect the recordset
    Set rst.ActiveConnection = Nothing

    'cleanup
    If CBool(cmd.State And adStateOpen) = True Then
        Set cmd = Nothing
    End If

    If CBool(cnx.State And adStateOpen) = True Then cnx.Close
    Set cnx = Nothing

    '"return" the recordset object
    Set RecordSetFromSheet = rst

End Function

Public Sub Test()

Dim rstData As ADODB.Recordset
Set rstData = RecordSetFromSheet("Sheet1")

Sheets("Sheet2").Range("A1").CopyFromRecordset rstData

End Sub
Run Code Online (Sandbox Code Playgroud)

Sheet1数据:Field1 Field2 Field3 Red A 1 Blue B 2 Green C 3

什么应该复制到Sheet2:红色A 1蓝色B 2绿色C 3

每次我想要进行更改并测试时,这样可以节省大量的时间来查询SQL ...

- 罗伯特·