Sean,
Here's some code. It almost works. You'll have to Reference "Microsoft
ActiveX Data Objects 2.5 Library" (msado15.dll) into your project. This
worked in an ASP script I messed with a few months ago. I've compiled it
into an Excel project, but I haven't gotten to work just yet. I think
there's something missing in the connection string. I also think the DAO
2.5 is outdated now. You should find th latest and greatest at
msdn.microsoft.com.
This is pretty generic. I've got a database called AEC-CALogs.mdb with a
table called tblSubmittals. The fields are listed in the SQL string. You
can manipulate it with a user form if you need to create a more variable and
sophisitcated query. I learned most of this from a Wrox book Beginning ASP
3.0. Since most web programmers use ADO for dynamic pages, it's got a
pretty extensive description of all the nuances of ADO.
I hope this helps.
Brian Johnson
Public Sub AccessToExcel()
Dim objConn As ADODB.Connection
Dim objRS As ADODB.Recordset
Dim strConnect As String
Dim strSQL As String
Dim strProjectField As String
Dim objWorksheet As Worksheet
Dim objField As ADODB.Field
Dim intColIndex As Integer
Set objConn = CreateObject("ADODB.Connection")
Set objRS = CreateObject("ADODB.Recordset")
'Assembly connection string. Datasource is the full path to Access
database.
strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\My Documents\AEC-CALogs.mdb;" & _
"Persist Security Info=False"
'Setup SQL
strProjectField = "99028"
strSQL = "SELECT SubmittalNum, Description, DateCreated, DateReceived,
DateDue, DateReturned " & _
"FROM tblSubmittals " & _
"WHERE DatedReturned Is Null " & _
"AND Project='" & strProjectField & "'"
'Open a connection to the database.
objConn.Open strConnect
'Open a recordset (Access table or query)
objRS.Open strSQL, objConn, adOpenForwardOnly, adLockReadOnly, adCmdText
'Populate Sheet1
Set objWorksheet = ThisWorkbook.Worksheets("Sheet1")
objWorksheet.Range("A1").Value = strProjectField
'Build table headers
intColIndex = 1
For Each objField In objRS.Fields
objWorksheet.Cells(3, intColIndex).Value = objField.Name
Next
'Populate table
While Not objRS.EOF
intColIndex = 1
For Each objField In objRS.Fields
objWorksheet.Cells(4, intColIndex).Value = objField.Value
Next
objRS.MoveNext
Wend
objRS.Close
objConn.Close
Set objRS = Nothing
Set objConn = Nothing
End Sub
"Sean Jman"
wrote in message
news:[email protected]...
> Can anyone post a simple example of using SQL, VBA and ADO? Say, for
> instance, you want to query an Access (mdb) table and place the results in
> an excel spreadsheet.
>
> Just a shot in the dark. I learn better from example than from scratch.:)
>