I need to create a personalized letter in word from vb code that will have a name of person and address taken from db table that has this info. Then after creation I have to save it in my directory.
I did something similar to this. The way I did it is, I created a word doc with bookmarks in all of the locations where I wanted to insert text into. A bookmark is a Word thing, they can be created easily. I saved off this doc in a shared folder where I used it as a template for my VB program. In the program, you can reference the Microsoft Word library so that you can open up the already created template. When this is open, insert the values into the bookmarks, then do a "Save As" into your directory. This leaves your template unmodified. Hope this helps...
I managed writing the letter ok, but can't figure out how to find the name the user saved it to so's I can pop that in the database. Heres my code. It's Access, but similar enough. All the me.things are controls on my form, but they may just as well be recordset things.
Sub WriteALetter()
'On Error GoTo ContactLetter_err
Dim cCompany As String
' Create an instance of Microsoft Word 97.
Set WordApp = CreateObject("Word.Application"
' Create a new, empty document.
Set WordDoc = WordApp.Documents.Add
WordApp.Visible = True
With WordApp.Selection
.TypeParagraph
.TypeParagraph
.TypeText Text:=Me.tMainName & " "
.TypeParagraph
If IsNull(Me.tCorresAdd1) Then
If Not IsNull(Me.tAddress1) Then
.TypeText Text:=Me.tAddress1 & " "
.TypeParagraph
End If
If Not IsNull(Me.tAddress2) Then
.TypeText Text:=Me.tAddress2 & " "
.TypeParagraph
End If
If Not IsNull(Me.tAddress3) Then
.TypeText Text:=Me.tAddress3 & " "
.TypeParagraph
End If
If Not IsNull(Me.tTown) Then
.TypeText Text:=Me.tTown & " "
.TypeParagraph
End If
If Not IsNull(Me.tCounty) Then
.TypeText Text:=Me.tCounty & " "
.TypeParagraph
End If
If Not IsNull(Me.tPostcode) Then
.TypeText Text:=Me.tPostcode & " "
.TypeParagraph
End If
Else
If Not IsNull(Me.tCorresAdd1) Then
.TypeText Text:=Me.tCorresAdd1 & " "
.TypeParagraph
End If
If Not IsNull(Me.tCorresAdd2) Then
.TypeText Text:=Me.tCorresAdd2 & " "
.TypeParagraph
End If
If Not IsNull(Me.tCorresAdd3) Then
.TypeText Text:=Me.tCorresAdd3 & " "
.TypeParagraph
End If
If Not IsNull(Me.tCorresTown) Then
.TypeText Text:=Me.tCorresTown & " "
.TypeParagraph
End If
If Not IsNull(Me.tCorrescounty) Then
.TypeText Text:=Me.tCorrescounty & " "
.TypeParagraph
End If
If Not IsNull(Me.tCorrespcode) Then
.TypeText Text:=Me.tCorrespcode & " "
.TypeParagraph
End If
End If
.TypeParagraph
' If IsNull(Me.Dear) Then
.TypeText Text:="Dear " & Me.tMainName & " "
' Else
' .TypeText Text:="Dear " & Me.Dear
' .TypeParagraph
' End If
.TypeText Text:=" "
.TypeParagraph
End With
' Show the instance of Microsoft Word.
WordApp.Visible = True
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.