我正在深入研究VBA数据连接的世界,并希望得到一些帮助。下面的代码是我到目前为止的代码,但有一些我无法弄清楚的奇怪之处。
Sub sbADO()
Dim sSQLQry As String
Dim ReturnArray
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String
DBPath = "C:\USERS\NAME\DOCUMENTS\VBA Work\Data Source.xlsx"
sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"
Conn.Open sconnect
sSQLQry = "SELECT * From [Sheet1$]"
mrs.Open sSQLQry, Conn
Sheet3.Range("A1").CopyFromRecordset mrs
mrs.Close
Conn.Close
End Sub
但是这段代码可行:
感谢任何帮助 谢谢 Caleeco
答案 0 :(得分:1)
试试这个:
Sub sbADO()
Dim sSQLQry As String
Dim ReturnArray
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String,i as integer
'DBPath = ThisWorkbook.FullName
DBPath = "C:\USERS\NAME\DOCUMENTS\VBA Work\Data Source.xlsx"
sconnect= "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" & _
DBPath & """;Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX = 1"""
Conn.Open sconnect
sSQLQry = "SELECT * From [Sheet1$]"
mrs.Open sSQLQry, Conn
if rs.recordcount>0 then
rs.movefirst
for i=0 to rs.fields.count-1
'read here the headers and add them to your sheet in row 1
Sheet3.Cells(1, i + 1) =rs.Fields(i).Name
next
end if
Sheet3.Range("A2").CopyFromRecordset mrs
mrs.Close
Conn.Close
End Sub