Sample VB .NET source code to create mailing labels or customized letters using MS Word MailMerge

M

Mikey

Sample VB .NET source code to create mailing labels or customized letters
using MS Word MailMerge

This VB .NET source code will start MS Word and call methods and set
properties in MS Word to execute a MailMerge to create mailing labels or
customized letters.

A label name known to MS Word MailMerge mailing label wizard may be used or
a template file containing the field names Line1 thru Line5 for each record
to be printed. If a template file is used ("bUseTemplate"=True),
"strLabelName" contains the full path filename to the template file
otherwise it contains a label name known to the MS Word MailMerge mailing
label wizard (e.g. "5162").

The "strFileName" parameter contains the full path filename to a data file
containing TAB delimited records with exactly 5 fields in each record. Each
record contains the name and address information. The first record of the
data file contains the field names (Line1, Line2, Line3, Line4, Line5)
delimited by a TAB character.

The "wd_AlignmentCode" parameter and the "intOffset" parameter are used only
when "bUseTemplate" is False. They specify the alignment of the fields
within the label and their offset from the left margin of the label table
cell respectively. "intOffset" is specified in inches.

Add References to:
Microsoft Word 10.0 Object Library
Microsoft Office 10.0 Object Library
or equivalent for older or newer releases of MS Office

Imports:
Microsoft.VisualBasic
_____________________________________________________
Sub CreateWordMailMerge(ByVal strLabelName As String, _
ByVal wd_AlignmentCode As Word.WdCellVerticalAlignment, _
ByVal intOffset As Single, _
ByVal strFileName As String, _
ByVal bUseTemplate As Boolean)
Dim oApp As Word.Application
Dim oDoc As Word.Document
Dim x As Integer
Dim bOK As Boolean = False
Dim oAutoText As Word.AutoTextEntry

Try
'Start a new document in Word
oApp = CType(CreateObject("Word.Application"), Word.Application)
If bUseTemplate Then
Try
oDoc = oApp.Documents.Open(CType(strLabelName,
System.Object), False, True, _
False, , , True, , , _
Word.WdOpenFormat.wdOpenFormatDocument,
, True)
Catch MyException As System.Exception
MsgBox(String.Concat("Unable to open ", strLabelName, _
ControlChars.Cr.ToString, ControlChars.Cr.ToString,
_
"Error Message: ", MyException.Message,
ControlChars.Cr.ToString, _
"Source: ", MyException.Source,
ControlChars.Cr.ToString, _
"InnerException: ",
MyException.InnerException.Message, ControlChars.Cr.ToString), _
MsgBoxStyle.Critical, "Label Template Open Failure")
CType(oApp, Word._Application).Quit()
oApp = Nothing
Exit Sub
End Try
Else
oDoc = oApp.Documents.Add
End If
oApp.Visible = True ' Make MS Word visible
Application.DoEvents()
' Do MailMerge
With oDoc.MailMerge
If Not bUseTemplate Then
With .Fields
.Add(oApp.Selection.Range, "Line1")
oApp.Selection.TypeParagraph()
.Add(oApp.Selection.Range, "Line2")
oApp.Selection.TypeParagraph()
.Add(oApp.Selection.Range, "Line3")
oApp.Selection.TypeParagraph()
.Add(oApp.Selection.Range, "Line4")
oApp.Selection.TypeParagraph()
.Add(oApp.Selection.Range, "Line5")
End With
oAutoText =
oApp.NormalTemplate.AutoTextEntries.Add("wordAutoTextTemp", oDoc.Content)
oDoc.Content.Delete()
End If ' If bUseTemplate
' Set up the mail merge type as mailing labels and use
' a tab-delimited text file as the data source.
.MainDocumentType =
Word.WdMailMergeMainDocType.wdMailingLabels
.OpenDataSource(strFileName, _
Word.WdOpenFormat.wdOpenFormatText, _
False, True, False, False)
If Not bUseTemplate Then
'
'Create the new document for the labels using the
AutoText entry
'
oApp.MailingLabel.CreateNewDocument( _
CType(strLabelName, String), _
"", _
"wordAutoTextTemp", _
False, _
Word.WdPaperTray.wdPrinterManualFeed)
End If ' If bUseTemplate
'
'Execute the mail merge to generate the labels.
.Destination =
Word.WdMailMergeDestination.wdSendToNewDocument
.Execute()
'
If Not bUseTemplate Then
'Delete the AutoText entry
oAutoText.Delete()
End If ' If bUseTemplate
End With
'
'Close the original document so that
'the Mail Merge results are displayed
CType(oDoc, Word._Document).Close(False)
'
If Not bUseTemplate Then
' Apply vertical alignment
For x = 1 To oApp.ActiveDocument.Tables.Count

oApp.ActiveDocument.Tables.Item(x).Range.Cells.VerticalAlignment = _
wd_AlignmentCode
Next
Application.DoEvents()
For x = 1 To oApp.ActiveDocument.Tables.Count
oApp.ActiveDocument.Tables.Item(x).LeftPadding =
oApp.InchesToPoints(intOffset)
oApp.ActiveDocument.Tables.Item(x).Rows.LeftIndent =
oApp.InchesToPoints(intOffset)
Next
Application.DoEvents()
End If
If oApp.ActiveWindow.View.Type <> Word.WdViewType.wdPrintView
Then
If oApp.ActiveWindow.View.SplitSpecial =
Word.WdSpecialPane.wdPaneNone Then
oApp.ActiveWindow.ActivePane.View.Type =
Word.WdViewType.wdPrintView
Else
oApp.ActiveWindow.View.Type =
Word.WdViewType.wdPrintView
End If
End If
'
'Prevent save to Normal template when user exits Word
oApp.NormalTemplate.Saved = True
oApp = Nothing
oDoc = Nothing
Catch MyException As System.Runtime.InteropServices.COMException
MsgBox(String.Concat("Error occured while communicating with MS
Word", _
ControlChars.Cr.ToString, ControlChars.Cr.ToString, _
"ErrorCode: ", MyException.ErrorCode,
ControlChars.Cr.ToString, _
"Error Message: ", MyException.Message,
ControlChars.Cr.ToString, _
"Source: ", MyException.Source, ControlChars.Cr.ToString, _
"StackTrace: ", MyException.StackTrace,
ControlChars.Cr.ToString), _
MsgBoxStyle.Critical, "MS Word Problem")
End Try
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top