我不得不安装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 ...
- 罗伯特·
| 归档时间: |
|
| 查看次数: |
33019 次 |
| 最近记录: |