Q: Insert Data to Excel from SQL Table using a Stored Procedure I would like to insert data from a SQL Table to an Excel sheet everyday using a stored procedure. It has to delete the data in excel and insert the new data to same sheet.
How do I do this?
I get an error in this code
Sub Connecion()

' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection

' Provide the connection string.
Dim strConn As String

'Use the SQL Server OLE DB Provider.
strConn = "PROVIDER=SQLOLEDB;"

'Connect to the Pubs database on the local server.
strConn = strConn & "DATA SOURCE=(10.200.157.110);INITIAL CATALOG=Brickstream_DEVMGR;"

'Use an integrated login.
strConn = strConn & " INTEGRATED SECURITY=sspi;"

'Now open the connection.
cnPubs.Open strConn



End Sub


A: Below code worked for me
Sub GetDataFromADO()
    'Declare variables'
        Set objMyConn = New ADODB.Connection
        Set objMyRecordset = New ADODB.Recordset
        Dim strSQL As String

    'Open Connection'
        objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=10.200.157.110;Initial Catalog=Brickstream_DEVMGR;User ID=usr_bayi;Password=3Ay1usr;"
        objMyConn.Open

    'Set and Excecute SQL Command'
        strSQL = "select * from DEALER_DETAILED"

    'Open Recordset'
        Set objMyRecordset.ActiveConnection = objMyConn
        objMyRecordset.Open strSQL

    'Copy Data to Excel'
        ActiveSheet.Range("A2").CopyFromRecordset (objMyRecordset)

End Sub


A: Easy ask.
Sub ADOExcelSQLServer()

    Dim Cn As ADODB.Connection
    Dim Server_Name As String
    Dim Database_Name As String
    Dim User_ID As String
    Dim Password As String
    Dim SQLStr As String
    Dim rs As ADODB.Recordset
    Set rs = New ADODB.Recordset

    Server_Name = "your_server_name" ' Enter your server name here
    Database_Name = "Northwind" ' Enter your  database name here
    User_ID = "" ' enter your user ID here
    Password = "" ' Enter your password here
    SQLStr = "SELECT * FROM Orders" ' Enter your SQL here

    Set Cn = New ADODB.Connection
    Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
    ";Uid=" & User_ID & ";Pwd=" & Password & ";"

    rs.Open SQLStr, Cn, adOpenStatic

    With Worksheets("Sheet1").Range("A2:Z500")
        .ClearContents
        .CopyFromRecordset rs
    End With

    rs.Close
    Set rs = Nothing
    Cn.Close
    Set Cn = Nothing
End Sub

