Option Explicit Dim database As String Dim userName As String Dim password As String Sub QueryNAME() Dim database As String Dim connectionObject As ADODB.Connection Dim cursor As ADODB.Recordset Dim filed As ADODB.Field Dim theQuery As String Dim row As Long Dim column As Integer Dim theWorkBook As ThisWorkbook Dim otherWorkBook As Worksheet userName = Range("A2").Value password = Range("A3").Value database = Range("A1").Value Set otherWorkBook = ActiveWorkbook.Sheets.Add otherWorkBook.Activate Set theWorkBook = ThisWorkbook Application.ScreenUpdating = False ActiveSheet.Name = database & "_" & Format(Date, "mmddyy") & " _" & Format(Time, "hhmmss") Set connectionObject = New ADODB.Connection Set cursor = New ADODB.Recordset theQuery = " use " & database & ";" & _ "MY QUERY IS HERE " On Error Resume Next connectionObject.ConnectionString = "driver={SQL Server};" & _ "server=myservername;uid=myusername;pwd=mypassword;database=" & database connectionObject.ConnectionTimeout = 30 connectionObject.Open cursor.Open theQuery, connectionObject If cursor.EOF Then MsgBox "no matching records found, or you forgot to enter your user name and password in Cel A2, A3" cursor.Close connectionObject.Close Exit Sub End If row = 1 column = 1 For Each filed In cursor.Fields otherWorkBook.Cells(row, column).Value = filed.Name column = column + 1 Next cursor.MoveFirst row = row + 1 Do While Not cursor.EOF column = 1 For Each filed In cursor.Fields otherWorkBook.Cells(row, column).Value = filed column = column + 1 Next row = row + 1 cursor.MoveNext Loop cursor.Close connectionObject.Close End Sub
connectionObject.ConnectionString = "driver={SQLOLEDB};" & _ "Data Source=MySERVERNAME;Initial Catalog=database;Integrated Security=SSPI"
"Provider=SQLOLEDB;Data Source=[Your DB Name];Trusted_connection=yes;"
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)