Click to See Complete Forum and Search --> : Database fieldsin a Word document
Caro
Jun 27th, 2000, 06:34 PM
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?)
Clunietp
Jun 28th, 2000, 12:47 PM
you need special tables or anything or you just need to put the text in the doc?
Caro
Jun 28th, 2000, 07:42 PM
Just address and salutation from the database - but automatically have it in the word doc when I open it from my app.
Clunietp
Jun 28th, 2000, 11:44 PM
here ya go
'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
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.