I am working on a macro whereby the user enters a search term which is used to query an Access Database. My question is how do I return those records to Excel in separate rows?
For example, a database contains home address information. If the user searches for a zip code, the records that are selected would go into row 1, 2, 3, etc. for as many records as are returned in the query.
Below is some example code - the part I am missing is clearly marked.
I appreciate any help!
Sub DatabaseQuery()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim stDB As String, stSQL As String, stProvider As String
Dim SearchTerm As String
stDB = "Data Source= C:\Database.accdb" ' Change accordingly
stProvider = "Microsoft.ACE.OLEDB.12.0"
With cn
.ConnectionString = stDB
.Provider = stProvider
.Open
End With
SearchTerm = Range("A1").Value ' Change accordingly
stSQL = "SELECT Field1, Field2, Field3 " & _
"FROM Table1 WHERE Field4= '" & SearchTerm & "'"
rs.Open stSQL, cn, adOpenStatic
' *** Put all the records in Sheet2! *** Help me! :)
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
Bookmarks