I'm trying to write my first ever macro with SQL, to read data from an
Access 2007 database and put it in a spreadsheet.
The database's full path and name is stored in a named cell in the
spreadsheet, [Databasepath]. The table which has this particular
piece of info is tblClientCodes, and the piece of data I'm currently
grabbing is in the "Client surname" column of tblClientCodes. The
client is being uniquely identified by "ClientID" which is equal to a
value in the named cell [ClientID} in the spreadsheet.
First I need to get the basic SQL thing out of the way, then once I
can get this figured out I'll modify it into a much more elaborate
thing which loops through a bunch of named cells and systematically
pulls pieces of info one after the other to populate a hundred or so
named cells in my spreadsheet with database data.
I've done quite a lot of Excel VBA stuff but am a complete novice with
integrating Access and Excel. This macro is based closely on code
from "Microsoft Excel and Access Integration With Microsoft Office
2007" by Michael Alexandeer and Geoffrey Clark, so I'm not sure how to
debug it other than checking that I've definitely not done any typos!
Anyway, the problem I get when I run it is a popup "Run-time error
'-2147217904 (80040e10)': No value given for one or more required
parameters." and the yellow highlighted line in debug is
MyRecordset.Open MySQL, MyConnect, adOpenStatic, adLockReadOnly
There is probably something really basic wrong with it, but I'm
stumped. Can anyone see any obvious reasons why it would not be working?
Sub Grabname()
'Step 1: Declare your variables
Dim MyConnect As String
Dim MyRecordset As ADODB.Recordset
Dim MySQL As String
'Step 2: Declare your connection string
MyConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source= " & [Databasepath].Value
'Step 3: Build your SQL statement
MySQL = "SELECT tblClientCodes.[Client surname] FROM tblClientCodes " & _
"WHERE (((tblClientCodes.[ClientID])= " & [ClientID].Value & "));"
'Step 4: Instantiate and specify your recordset
Set MyRecordset = New ADODB.Recordset
MyRecordset.Open MySQL, MyConnect, adOpenStatic, adLockReadOnly
'Step 5: Copy the recordset to Excel