VBA Code to Import Data from SQL Server into Excel

VBA Code:

Sub ImportDataFromSQLServer()
    Dim conn As Object
    Dim rs As Object
    Dim sqlQuery As String
    Dim connectionString As String
    Dim rowNum As Long
    
    ' Set the SQL query to retrieve the data
    sqlQuery = "SELECT * FROM TableName" ' Replace TableName with the actual table name
    
    ' Set the connection string for the SQL Server database
    connectionString = "Provider=SQLOLEDB;Data Source=ServerName;Initial Catalog=DatabaseName;User ID=Username;Password=Password"
    ' Replace ServerName, DatabaseName, Username, and Password with the actual values
    
    ' Create a new connection object
    Set conn = CreateObject("ADODB.Connection")
    
    ' Open the connection to the SQL Server database
    conn.Open connectionString
    
    ' Create a new recordset object
    Set rs = CreateObject("ADODB.Recordset")
    
    ' Execute the SQL query and retrieve the data into the recordset
    rs.Open sqlQuery, conn
    
    ' Set the starting row number to paste the data in the Excel worksheet
    rowNum = 2
    
    ' Loop through each record in the recordset and copy the data to Excel
    Do Until rs.EOF
        ' Copy each field value from the recordset to Excel
        For i = 1 To rs.Fields.Count
            Worksheets("Sheet1").Cells(rowNum, i).Value = rs.Fields(i - 1).Value ' Change the sheet name as desired
        Next i
        
        ' Move to the next row in Excel
        rowNum = rowNum + 1
        
        ' Move to the next record in the recordset
        rs.MoveNext
    Loop
    
    ' Close the recordset
    rs.Close
    
    ' Close the connection to the SQL Server database
    conn.Close
    
    ' Inform the user that the data has been imported
    MsgBox "Data imported from SQL Server successfully."
End Sub

Check All VBA Codes

Join Our Telegram Group

Join the TechGuruPlus Telegram group

Join Our WhatsApp Group

Join the TechGuruPlus WhatsApp group
Nazim Khan, founder of TechGuruPlus.com

— Founder & Editor, TechGuruPlus.com
[MBA in Finance]

Nazim Khan has spent over ten years working with Excel, Tally and office documentation in accounts, finance and MIS roles. He has been running TechGuruPlus.com since 2016, where he publishes free editable templates for office work, and the YouTube channel Business Excel. He has trained more than 50,000 people online. Every template on this site is built and checked by him before it is published.

Contact  Â·  Excel Course

Leave a Comment