Connect SQL Server with VBA to import table

Option Explicit

Sub sqltovba()

Dim con As String

con = "Driver={SQL Server}; Server=DESKTOP-R8EOO8P;Database=Dbmay"


Dim cn As New ADODB.Connection

Dim rs As New ADODB.Recordset


cn.Open con

Set rs = cn.Execute("Select * from Student")


Dim col, i As Integer


For col = 0 To rs.Fields.Count - 1

    Cells(1, col + 1).Value = rs.Fields(col).Name

Next

Range("A2").CopyFromRecordset rs

cn.Close

End Sub



Comments