Search code examples
vbaexcelado

Fastest ADO to copy paste tables from sql-server to Excel


I'm moving tables of data from sql-server into Excel.
I do not need to move through the record set only to grab the data and paste it into a worksheet.

Am I using the correct arguments for the recordset's Open method?

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

Solution

  • This is the approach that I've use to extract the data from MSSQLServer, maybe it will be useful for you:

    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