2015-01-26 107 views
1

我正在将数据表从sql-server移动到Excel中。
我不需要通过记录集来获取数据并将其粘贴到工作表中。最快的ADO从sql-server复制粘贴表格到Excel

我是否使用正确的参数为记录集的Open方法?

Dim recSet As ADODB.Recordset 
Set recSet = New ADODB.Recordset 
aConnection.Open 
recSet.Open stringSQL, aConnection, adOpenForwardOnly, adLockReadOnly, adCmdText 
wb.Sheets(sName).Cells(1, 1).CopyFromRecordset recSet 
recSet.Close 
If Not (recSet Is Nothing) Then 
    If (recSet.State And 1) = 1 Then recSet.Close 
    Set recSet.ActiveConnection = Nothing 
    Set recSet = Nothing 
End If 
+0

对我来说很好。 – 2015-01-26 23:30:51

+0

根据[MSDN](https://msdn.microsoft.com/en-us/library/windows/desktop/ms675544(v = vs.85).aspx),是的,你的论点是正确的。如果你的'stringSQL'不那么复杂,你的'RecordSet'不是那么大,这应该是即时的。 – L42 2015-01-26 23:35:11

+0

@ L42从不超过5000行×10列? – whytheq 2015-01-26 23:40:30

回答

3

这是一种方法,我用它来抓住从数据的MSSQLServer,也许这将是有用的,你

Sub test() 
    Dim Connection As ADODB.Connection 
    Dim rs As ADODB.Recordset 
    Dim QT As Excel.QueryTable 
    Dim ConnectionString As String 
    Dim SQL As String 
    Set Connection = New ADODB.Connection 
    Set rs = New ADODB.Recordset 

    ConnectionString = "" 
    SQL = "SELECT * FROM SomeTable" 
    Connection.Open ConnectionString 
    rs.Open SQL, Connection, adOpenStatic, adLockReadOnly 

    Set QT = ActiveSheet.QueryTables.Add(rs, ActiveSheet.Cells(1, 1)) 
    QT.Refresh: rs.Close: QT.Delete: Connection.Close 
End Sub 
+1

这很好,因为QueryTables保留列名,与Range.CopyFromRecordset方法不同。 以下链接提供了将现有Excel数据复制到记录集的方法。我知道它可能与第一个问题没有关系,但与您的答案结合起来可以完成缺失的部分,并可以使用excel中的许多方法来处理记录集,谢谢。 https://usefulgyaan.wordpress.com/2013/07/11/vba-trick-of-the-week-range-to-recordset-without-making-connection/ – 2016-12-06 04:10:15