Search code examples
vbams-accessms-wordoffice-2010

Exporting fields of a highlighted row in Access Databse to a Word document


I have an access database and I want to export fields from ONE highlighted row to a word document and email it to a recepient.

From the Access database I want to export the following fields: Initials (character string), HospNo (Character and Number string), date, comment (character string)

and I want to export these fields from the row of my choice to a word document, c:\test.docx, with 4 MERGEFIELD's bookmarked as Inits, HosNumber, ScanDate, Diagnosis, respectively.

I think MailMerge is the solution and that's why I used Mergefileds in Word. But I know very little VBA and don't know where to start from.

I have Office 2010 on my PC.

Is that information sufficient to explain the problem?


Solution

  • From a very high level, you're probably going to need to create a recordset in VBA that contains just the one record you want to export. You can then use that recordset as your source for your mailmerge.

    I've never done mailmerges, but this should get you started:

    Dim db as Database
    Dim rec as Recordset
    
    Set db = CurrentDB
    Set rec = db.OpenRecordset("SELECT Initials, HospNo, [date], comment FROM MyTableName WHERE SomeFilterCriteria")
    
    'Mailmerge based on "rec"
    

    Obviously you need to change MyTableName and MyFilterCriteria based on your specific info, you didn't give us the table name or how you want to determine which record of data to mailmerge.

    Either that or you can build a query, set up the mailmerge from the query, and then put filters in the query that point to your form. In the Criteria line in a query (if you open it in Design View), you would put something like

    [Forms]![MyFormName].[MyFieldName]
    

    Also, if you have the ability to do so, change your date field name. The word "date" is a reserved word, which means you have to enclose it in brackets so Access doesn't think it's a built-in command. Change the field name to scandate or something to avoid future problems.