Does anyone know how I can put fields from my database in a Word document using VB code (a bit like a mail merge but just for the opened doc and only from one record on the database?)
Printable View
Does anyone know how I can put fields from my database in a Word document using VB code (a bit like a mail merge but just for the opened doc and only from one record on the database?)
you need special tables or anything or you just need to put the text in the doc?
Just address and salutation from the database - but automatically have it in the word doc when I open it from my app.
here ya go
Code:'uses ADO 2.x and MS Word object library
On Error GoTo Err_Handler
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim objWord As Word.Application
Dim objDoc As Word.Document
Set cn = New Connection
Set rs = New Recordset
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\nwind.mdb"
rs.Open "Select * from Customers", cn, adOpenStatic, adLockReadOnly, adCmdText
If rs.EOF = False Then
'use the first record
Set objWord = New Word.Application
objWord.Visible = True
Set objDoc = objWord.Documents.Add
'document text goes here
objDoc.Content.Text = "Dear " & rs.Fields("ContactName") & "," & _
vbCrLf & vbCrLf & "If you don't pay your bill of " & _
"$1, we will break your kneecaps. Thank you"
objDoc.Activate
End If
cn.Close
Set cn = Nothing
Set objDoc = Nothing
Set objWord = Nothing
Exit Sub
Err_Handler:
On Error Resume Next
'quit & release word object, avoid crashes if errors
objWord.Quit False
Set objWord = Nothing
MsgBox Err.Description