First time trying to get Excel to connect to a SQL 2012 DB to read/write to some tables. I found a decent snippet that seems to get me close as I'm already using a ADO/Jet connection to query internal worksheet tables I have a little experience getting this to work. Below is the code I'm trying, it seems to properly connect as I can see the fields being pulled but for some reason it always shows the RecordCount as -1. I'm trying to find the easiest method to query a table and dump that to an Array so I can use that in other code.
Code:
Public Sub SQL(ByVal SQLCommand As String, ByRef Results As Variant)
Dim conn As ADODB.Connection
Dim rs As ADODB.RecordSet
Dim sConnString As String
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=Tesbed1\XLTest;" & _
"Initial Catalog=resource;" & _
"User ID=psdbusr;Password=Password"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.RecordSet
' Open the connection and execute.
conn.Open sConnString
Set rs = conn.Execute(SQLCommand & ";")
' Check we have data.
If Not rs.EOF Then
' Transfer result.
'Sheets(1).Range("A1").CopyFromRecordset rs
MsgBox rs.RecordCount
Set Results = rs.GetRows(rs.RecordCount)
' Close the recordset
rs.Close
Else
MsgBox "Error: No records returned.", vbCritical
End If
' Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub