Question : Accessing Access Table and Copying to Excel

I am a novice and got some help with code that accesses and copies data from an Access Database/Table.  The code (attached) opens a new Excel workbook before copying.  Can someone tell me why and how to make the code copy to the current worksheet?
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
Sub GatherDBData()
Set dbconn = Workbooks.OpenDatabase("c:\Test.accdb")
    
    
    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    
    Set cn = New ADODB.Connection
    
    cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=c:\Test.accdb;Persist Security Info=False;Jet OLEDB:Database Password="
    
    Set rs = New ADODB.Recordset
    
    rs.Open "Select * from [users]", cn
    While Not rs.EOF
        fname = rs.Fields("Fname")
        lname = rs.Fields("Lname")
        rs.MoveNext
    Wend

End Sub

Answer : Accessing Access Table and Copying to Excel

This code should not error out on you...

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
Sub GatherDBData()
     
    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
     
    Set cn = New ADODB.Connection
     
    cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=c:\Test.accdb;Persist Security Info=False;Jet OLEDB:Database Password="
     
    Set rs = New ADODB.Recordset
     
    rs.Open "Select * from [users]", cn
    While Not rs.EOF
        fname = rs.Fields("Fname")
        lname = rs.Fields("Lname")
        rs.MoveNext
    Wend
    
    Workbooks.Add
    Range("A1").CopyFromRecordset (rs)
    rs.Close
 
End Sub
Random Solutions  
 
programming4us programming4us