Hey everyone!
I have data in 10 SQL tables & I'm trying to write a Macro that will pull the data from these tables into different worksheets in a workbook. I am doing this using ADODB Connection Objects but I am having trouble executing it correctly. I have all the table names & all the worksheet names, each table's data goes into a specific worksheet. I'm trying my hand with this code so far, but I get a compile error at "Dim cn as ADODB.Connection" and I want to integrate this code with Case statements (specifying each worksheet), I just feel like that would be a better approach. I am defining the username & password for the SQL Server Database. Is there a way to do this dynamically instead of defining a username & pass?
Here's the Code:
[VBA]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 = "ServerName"
Database_Name = "DatabaseName"
User_ID = "USER"
Password = "PASSWORD"
SQLStr = "SELECT * FROM AnalysisMaster"
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
' Copy to Worksheet
With Worksheets("sheet1").Range("a1:z100")
.ClearContents
.CopyFromRecordset rs
End With
' Cleaning
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
[/VBA]
Can someone please help me out with this code/suggest a better way to execute this
Thanks