VBA – 从电子表格的内容创buildADODB.Recordset

我正在查询SQL数据库的Excel应用程序。 查询可能需要很长时间才能运行(20-40分钟)。 如果我错误地编码了一些东西,可能需要很长时间才能出错或达到一个中断点。 我可以把结果保存到一张纸上,这是我使用logging集的时候可能会炸毁的。

有没有办法将数据加载到ADODB.Recordset当我正在debugging跳过查询数据库(第一次后)?

我会用这样的东西吗?

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

我不得不安装MDAC来获得msado15.dll,一旦我有了它,我(Win7的64位上)添加了一个引用:

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

然后,我创build了一个函数,通过传入当前活动工作簿中存在的工作表名称来返回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 

Sheet1数据:Field1 Field2 Field3红色A 1蓝色B 2绿色C 3

应将哪些内容复制到Sheet2:红色A 1蓝色B 2绿色C 3

每次我想要进行更改和testing时,这都为查询SQL节省了大量的时间。

– 罗伯特·

最简单的方法是使用rs.Save "filename"rs.Open "filename"将客户端logging集序列化为文件。