Sub Button1_Click()
' connect to database
Dim connection As New ADODB.connection
connection.ConnectionString = GetSQLServerConnectionString("DESKTOP-DMM2SR0", "TestDb", "", "")
connection.Open
' 1 is successfully connected to database
If connection.State = 1 Then
' sql Query
Dim sqlQuery As String
sqlQuery = "Select * from Books"
' execute sql Query
Dim dbRecords As New ADODB.Recordset
dbRecords.CursorLocation = adUseClient
dbRecords.Open sqlQuery, connection, adOpenStatic
' put dbRecords on first page in range D15
ThisWorkbook.Sheets(1).Range("D15").CopyFromRecordset dbRecords
End If
End Sub
Function GetSQLServerConnectionString(dbServer As String, dbDatabase As String, dbUserName As String, dbPassword As String) As String
If dbUserName = "" And dbPassword = "" Then
' result
GetSQLServerConnectionString = "Server=" & dbServer & ";" _
& "database=" & dbDatabase & ";" _
& "Integrated Security=SSPI; Provider=SQLNCLI11;"
Else
' result
GetSQLServerConnectionString = "Server=" & dbServer & ";" _
& "database=" & dbDatabase & ";" _
& "User Id=" & dbUserName & ";" _
& "Password=" & dbPassword & ";" _
& "MultipleActiveResultSets=true; Provider=SQLNCLI11;"
End If
End Function