ADODB连接 - 未提取的标题文本&只读问题

时间:2018-01-31 21:38:50

标签: excel vba excel-vba connection-string adodb

我正在深入研究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

但是这段代码可行:

  1. 引入的数据不包括数据集的第1行(因此不会引入标题)
  2. 如果源工作簿'Data Source.xlsx'已打开。代码将导致工作簿再次打开,但处于只读模式。这可以避免吗?
  3. 是否可以编辑连接字符串,以便源文件永远不会被锁定?即。在只读模式下查询,其他用户可以在查询完成时打开它吗?
  4. 感谢任何帮助 谢谢 Caleeco

1 个答案:

答案 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