Mailmerge with VBA

  • Thread starter Thread starter bmvanheek
  • Start date Start date
B

bmvanheek

Guest
Can anybody tell me how I can do a mailmerge to MS Word with one single button on a form?

Let say the data should come from table: tblUser and the following fields should be included in the word document:

useNaam
useAddress
usePostalCode
useCity

Thanks!
 
ok, that's for the current record..... but...

Can you also help me if the datasource is not the current record but a query (or multiple records)?

This is already a lot of help!
 
Do you want to filter some records to be sent to Word? Or all records. If you want to use parametered query, you have to supply the Parameters to the code as showed below.

Try this out.

Dim objWord As Object
Dim dbs As Database, rst As Recordset, I As Integer, qdf As QueryDef
Dim strSubName As String, strDeptName As String, strFacName As String

Set dbs = CurrentDb
Set qdf = dbs.QueryDefs("qryLogistics")
qdf.Parameters![packageid] = Me.cmbPackageID
Set rst = qdf.OpenRecordset()

If Not rst.EOF Then
rst.MoveLast
rst.MoveFirst

For I = 1 To rst.RecordCount
Set objWord = CreateObject("Word.Application")
With objWord
' Make the application visible?.
.Visible = True
' Open the document.
.Documents.Open ("c:\docs\mailmerge.doc")
.ActiveDocument.Bookmarks("subno").SELECT
.Selection.Text = rst(0)
...

End With
If MsgBox("Do you want to continue?" & vbCrLf & rst.RecordCount - I & _
" Recodrs left", vbOKCancel) = vbOK Then
' Close the document without saving changes.
objWord.ActiveDocument.Saved = True
objWord.ActiveDocument.Close
' Quit Microsoft Word 97 and release the object variable.
objWord.Quit
Set objWord = Nothing
Else
objWord.ActiveDocument.Saved = True
objWord.ActiveDocument.Close
objWord.Quit
Set objWord = Nothing
Set rst = Nothing
Set dbs = Nothing
Exit Sub
End If

rst.MoveNext
Next I

'Else of If Not rst.EOF
Else
MsgBox "There is no record in this package", vbOKOnly, "No Records!"
End If

I use Message Box to pause on each record, just in case that a user want to stop the process. You can remove this part out.

Good luck.
 
OK, this is not exactly what I am looking for. In your example a new document is created for each record, the file is printed (or whatever) and word is closed. Then it opens word again for the next record. I want a merge in one document with on each page a new letter.

I found some eaxmples at the above mentioned website. That was of great help. Thanks again.
 

Users who are viewing this thread

Back
Top Bottom