Really basic SQL Server export question

Status
You're currently viewing only Sentipede's posts. Click here to go back to viewing the entire thread.
Not open for further replies.

Sentipede

Seniorius Lurkius
10
Use VBA in Excel. Below is the VBA code to pull from an Access database. You'd need to alter it to work with SQL Server. Should not be hard.

In the example, the sheet is named "Machines". There is a table (list object) on the sheet named "MachinesTable" with three columns: city, state, branch num.

Code:
Sub PullData()
    Application.ScreenUpdating = False
    
    Dim MachinesWs As Worksheet
    Dim Db As DAO.Database
    Dim Rs As DAO.Recordset
    Dim rCell As Range
    
    Set Db = DAO.dbengine.OpenDatabase("\\domain\thepath\yourDB.accdb")     
    Set MachinesWs = ThisWorkbook.Worksheets("Machines")
    Set Rs = Db.Openrecordset("SELECT city, state, branchnumber FROM schedule", dbreadonly)

    targetRow = 2

    Do While Not Rs.EOF
        MachinesWs.Cells(targetRow, MachinesWs.Range("MachinesTable[City]").Column) = Rs.Fields("city")
        MachinesWs.Cells(targetRow, MachinesWs.Range("MachinesTable[State]").Column) = Rs.Fields("state")
        MachinesWs.Cells(targetRow, MachinesWs.Range("MachinesTable[Branch Num]").Column) = Rs.Fields("branchnumber")
        
        Rs.MoveNext
        targetRow = targetRow + 1
    Loop

    MachinesWs.Cells.EntireColumn.AutoFit
    
    Rs.Close
    Set Rs = Nothing
    Db.Close
    Set Db = Nothing
End Sub
 
Status
You're currently viewing only Sentipede's posts. Click here to go back to viewing the entire thread.
Not open for further replies.