我必须安装MDAC得到MSADO15.DLL,一旦我拥有了我从添加对它的引用(Win7上64位):
C:\ Program Files文件(86 )\ Common Files \ System \ ado \ msado15.dll
然后,我创建了一个函数,通过传递存在于当前活动工作簿中的工作表名称来返回ADODB.Recordset对象。下面是其他任何的代码,如果他们需要,包括测试()子,看看它的工作原理:
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中的数据: 字段1字段2字段3 红A 1 蓝B 2 绿色的C 3
什么应该被复制到Sheet2:从每次查询针对SQL 红A 1 蓝B 2 绿色的C 3
这是节省了我的时间量巨大我想做出改变并测试它...
--Robert
对我来说这看起来很好,如果您使用的版本大于2003,请注意连接字符串。 – Fionnuala 2010-03-20 21:06:06
感谢您的评论。虽然希望获得一些代码或者更直接的例子。可以说,我的问题基本上是要求是/否的回应。我的错。 :) – robault 2010-03-21 22:25:01