I'm trying to query a MS access (2007-2010) database using microsoft excel and print the qeury to my spreadsheet.
The below code prints only the field header into a specified cell and none of the other data in the selected field. Where am I going wrong? hints etc welcome.
Option Explicit
' Add reference to Microsoft ActiveX Data Objects Lib
Public Sub main(): On Error GoTo Err_handler
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
'open DB connection
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Databaselocation
cn.Open
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
'Query Stuff
rs.ActiveConnection = cn
rs.Open "SQL Query here;"
'does something
Dim fld As ADODB.Field
Dim rng As Range
Set rng = [a2]
For Each fld In rs.Fields
rng.Value = fld.Name
Set rng = rng.Offset(0, 2)
Next fld
Set rng = rng.Offset(2, -rs.Fields.Count)
rng.CopyFromRecordset rs
' closes db connection
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
Exit Sub
Err_handler:
MsgBox Err.Description
End Sub
Set rng = rng.Offset(0, 2)
do you mean to skip right by two columns every time you print a value? Second: CopyFromRecordset "might" only work if the worksheet is active - what happens if you add a WorkSheet.Activate line? Of course I am assuming you have confirmed that your query returns valid data... – Floris Feb 26 '13 at 22:59