Currently I'm testing how to export data from SQL Server Management Studio to Excel for an upcoming project.
I looked up online and came upon a code as follows:
Function ImportSQLtoRange(ByVal conString As String, ByVal query As String, ByVal target As Range) As Integer
On Error Resume Next
' Object type and CreateObject function are used instead of ADODB.Connection,
' ADODB.Command for late binding without reference to
' Microsoft ActiveX Data Objects 2.x Library
' ADO API Reference
' http://msdn.microsoft.com/en-us/library/ms678086(v=VS.85).aspx
' Dim con As ADODB.Connection
Dim con As Object
Set con = CreateObject("ADODB.Connection")
con.ConnectionString = conString
' Dim cmd As ADODB.Command
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")
cmd.CommandText = query
cmd.CommandType = 1 ' adCmdText
' The Open method doesn't actually establish a connection to the server
' until a Recordset is opened on the Connection object
con.Open
cmd.ActiveConnection = con
' Dim rst As ADODB.Recordset
Dim rst As Object
Set rst = cmd.Execute
If rst Is Nothing Then
con.Close
Set con = Nothing
ImportSQLtoRange = 1
Exit Function
End If
Dim ws As Worksheet
Dim col As Integer
Set ws = target.Worksheet
' Column Names
For col = 0 To rst.Fields.Count - 1
ws.Cells(target.row, target.Column + col).Value = rst.Fields(col).Name
Next
ws.Range(ws.Cells(target.row, target.Column), ws.Cells(target.row, target.Column + rst.Fields.Count)).Font.Bold = True
' Data from Recordset
ws.Cells(target.row + 1, target.Column).CopyFromRecordset rst
rst.Close
con.Close
Set rst = Nothing
Set cmd = Nothing
Set con = Nothing
ImportSQLtoRange = 0
End Function
Sub TestImportUsingADO()
Dim conString As String
conString = "data source = server name; initial catalog = database; uid = name; password = password"
Dim query As String
query = "my query goes here"
Dim target As Range
Set target = ThisWorkbook.Sheets(2).Cells(3, 2)
target.CurrentRegion.Clear
Select Case ImportSQLtoRange(conString, query, target)
Case 1
MsgBox "Import database data error", vbCritical
Case Else
End Select
End Sub
When I try to use the macro, I receive a message box as set in Case 1 in ImportSQLtoRange. But I'm not sure if that means that the code works and can access the query or this is an error message. If this shows that it does work how do I modify it so that it gives me the table I want based on my query?
Edit: Upon following Kazimierz Jawor suggestion, I commented on
On Error Resume Next
Now I get an error as follows:
Clicking Debug show the error coming from
con.open
What does that mean?

On error resume nextline and you get error exactly in the line where it is produced. Next provide more information about error: error number, error name, in which line it happened