Results 1 to 6 of 6

Thread: Winword Mail Merge Using VB.net

  1. #1

    Thread Starter
    Learning .Net danasegarane's Avatar
    Join Date
    Aug 2004
    Location
    VBForums
    Posts
    5,853

    Winword Mail Merge Using VB.net

    This code helps to AutoMate WinWord Using Mail Merge

    Main Method



    vb Code:
    1. Imports System.Data
    2. Imports System.IO
    3. Imports System.Reflection
    4. Imports Microsoft.Office.Interop
    5. 'Mark a Reference to Microsoft word Object from Com Tab
    6. Module Module1
    7.  
    8.     Sub Main()
    9.  
    10.         Dim sqlQry As String = "SELECT TOP 2 ContactName,ContactTitle,Address from customers"
    11.         'Get the values from table
    12.         Dim dttable As DataTable = DatabaseOperation.DatabaseOperation(sqlQry, DataBaseQueryType.Datatable)
    13.         Dim sTemplateFileName As String = "DocumentTemplate.doc"
    14.         'Word merging
    15.         Dim moApp As Object
    16.  
    17.         moApp = CreateObject("Word.Application")
    18.         If IsNothing(moApp) = False Then
    19.             moApp.visible = False
    20.             Dim sDocFileName As String
    21.             For Each row As DataRow In dttable.Rows
    22.                 'Open the Document
    23.                 moApp.Documents.Open(Path.Combine(ApplicationPath, sTemplateFileName))
    24.                 sDocFileName = Convert.ToString(row(0)) & ".doc"
    25.                 Dim intCount As Integer = 0
    26.                 For Each MergeField As Word.MailMergeField In moApp.ActiveDocument.MailMerge.Fields
    27.                     'Select the text
    28.                     MergeField.Select()
    29.                     'Type the text
    30.                     moApp.Selection.TypeText(Convert.ToString(row(intCount)))
    31.                     intCount += 1
    32.                 Next
    33.                 'Save the document
    34.                 moApp.ActiveDocument.SaveAs(Path.Combine(ApplicationPath, sDocFileName))
    35.                 'Close the document
    36.                 moApp.Documents.Close()
    37.             Next
    38.             'Dont save the template changes
    39.             moApp.Quit(Word.WdSaveOptions.wdDoNotSaveChanges)
    40.             'Dispose
    41.         End If
    42.         moApp = Nothing
    43.         dttable.Dispose()
    44.         dttable = Nothing
    45.  
    46.     End Sub
    47.  
    48.     Private Function ApplicationPath() As String
    49.         Return _
    50.         Path.GetDirectoryName([Assembly].GetEntryAssembly().Location)
    51.     End Function
    52.  
    53. End Module

    Database Operations

    vb Code:
    1. Imports System.Data
    2. Imports System.Data.SqlClient
    3. Imports System.Text.StringBuilder
    4. Imports System.Configuration
    5. Module DatabaseOperation
    6.  
    7.  
    8.     Public Enum DataBaseQueryType
    9.         Datatable = 1
    10.  
    11.     End Enum
    12.  
    13.  
    14.  
    15.     Dim con As SqlConnection
    16.     Dim cmd As SqlCommand
    17.     Dim sConstring As String
    18.  
    19.     Private Sub OpenConnection()
    20.         Dim connectionString As String = _
    21.         "Integrated Security=SSPI;Persist Security Info=False;" + _
    22.         "Initial Catalog=Northwind;Data Source=localhost"
    23.         con = New SqlConnection(connectionString)
    24.         If con.State = ConnectionState.Closed Then
    25.             con.Open()
    26.         End If
    27.     End Sub
    28.  
    29.     Private Sub CloseConnection()
    30.         If con.State = ConnectionState.Open Then
    31.             con.Close()
    32.         End If
    33.     End Sub
    34.  
    35.     Public Function DatabaseOperation(ByVal qry As String, ByVal type As DataBaseQueryType) As Object
    36.         Dim objDB As New Object
    37.         Dim dt As DataTable
    38.         Dim da As SqlDataAdapter
    39.         If type = DataBaseQueryType.Datatable Then
    40.             OpenConnection()
    41.             Dim cmd As New SqlCommand(qry)
    42.             cmd.Connection = con
    43.             dt = New DataTable
    44.             da = New SqlDataAdapter(cmd)
    45.             da.Fill(dt)
    46.             objDB = dt
    47.             dt.Dispose()
    48.             CloseConnection()
    49.             Return objDB
    50.         End If
    51.  
    52.         Return objDB
    53.  
    54.     End Function
    Attached Files Attached Files
    Please mark you thread resolved using the Thread Tools as shown

  2. #2
    Junior Member
    Join Date
    Nov 2010
    Posts
    30

    Re: Winword Mail Merge Using VB.net

    This is exactly what I need, thank you! I spent the day on google looking literally at hundreds of searches for "mail merge vb.net sql server" I'll be doing my searching more here, Thanks again!

  3. #3
    Lively Member
    Join Date
    Jan 2008
    Posts
    98

    Re: Winword Mail Merge Using VB.net

    Sorry to bump such an old thread, but stumbled across this the other day, and it works almost how I want it. One thing I cannot work out though, is if the the sql statement needs to bring back the fields in the same order as the mail merge fields within the word document?

    My merge is working to an extent, but puts the fields from the dataset in to random merge fields, not the correct ones.

    Any ideas?

    Also, the above example creates a new word document for each record, ideally I would like to insert a new page for each row, instead of a new document. Any ideas on that one? I spent the entirety of yesterday trying ways to insert a page break, but no luck.

    Thanks

  4. #4
    Frenzied Member
    Join Date
    Oct 2012
    Location
    Tampa, FL
    Posts
    1,187

    Re: Winword Mail Merge Using VB.net

    Quote Originally Posted by samo8076 View Post
    Sorry to bump such an old thread, but stumbled across this the other day, and it works almost how I want it. One thing I cannot work out though, is if the the sql statement needs to bring back the fields in the same order as the mail merge fields within the word document?

    My merge is working to an extent, but puts the fields from the dataset in to random merge fields, not the correct ones.

    Any ideas?

    Also, the above example creates a new word document for each record, ideally I would like to insert a new page for each row, instead of a new document. Any ideas on that one? I spent the entirety of yesterday trying ways to insert a page break, but no luck.

    Thanks
    Looking at the code:

    Code:
     For Each MergeField As Word.MailMergeField In moApp.ActiveDocument.MailMerge.Fields
                        'Select the text
                        MergeField.Select()
                        'Type the text
                        moApp.Selection.TypeText(Convert.ToString(row(intCount)))
                        intCount += 1
                    Next
    It is assuming that the mergefields will be in the same order as the columns of the datatable. In your case, this is most likely not so. What you should probably do is keep the data table column names the same as the merge field names, then inside the mergefield loop above, get the string name of the mergefield after Mergefield.Select() occurs, match it to the string name column in the datatable, then assign that value using .TypeText()

  5. #5
    Lively Member
    Join Date
    Jan 2008
    Posts
    98

    Re: Winword Mail Merge Using VB.net

    Thanks, works great now

  6. #6
    New Member
    Join Date
    Dec 2014
    Posts
    1

    Re: Winword Mail Merge Using VB.net

    The example on this forum thread is using Interop, which can cause trouble in server-side application (see Microsoft's KB 257757).

    My advice would be to use fully managed .NET solution with OpenXML. Since OpenXML has steep learning curve, it would probably make sense to look for a toolkit which uses that kind of approach.

    I have good experience with Docentric Toolkit. I have been using it for three years now. So here are its pros and cons:

    Pros:
    - plain simple Word Add-in for template generation
    - OpenXML based, server side friendly
    - support for images, data-bound graphs, tables
    - conditional elements in templates
    - support for placeholders in headers and footers
    - very fast report generation

    Cons:
    - not free
    - support for PDF output is still somewhat limited.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width