title: Automating Word Mailmerge not working as expected
body: <p>I'm having a problem with some mail merge code that is supposed to produce letters within our application. I'm aware that this code is a bit rough at the moment, but we're in the "Get something working" phase before we tidy it up.</p>
  
  <p>Now the way this is supposed to work, and the way it works when we do it manually, is we have a file (the fileOut variable + ".template") which is a template for the letter. We open that template, merge it, and then save it as the filename in the fileOut variable.</p>
  
  <p>However, what it is doing is saving a copy of the template file to the fileout filename, instead of the output of the merge.</p>
  
  <p>I've searched, and I seem to be banging my head against a brick wall.</p>
  
  <p>datafile is the datafile that contains the merge data.</p>
  
  <p>Using the same files, it all works if you do it manually.</p>
  
  <pre><code>Public Function processFile(ByVal datafile As String, ByVal fileOut As String) As String
      Dim ans As String = String.Empty
  
      errorLog = "C:\Temp\Template_error.log"
  
      If (File.Exists(datafile)) Then
  
          Try
  
              ' Create an instance of Word  and make it invisible.'
  
              wrdApp = CreateObject("Word.Application")
              wrdApp.Visible = False
  
              ' Add a new document.'
  
              wrdDoc = wrdApp.Documents.Add(fileOut &amp; ".template")
              wrdDoc.Select()
  
              Dim wrdSelection As Word.Selection
              Dim wrdMailMerge As Word.MailMerge
  
  
              wrdDoc.MailMerge.OpenDataSource(datafile)
  
              wrdSelection = wrdApp.Selection()
              wrdMailMerge = wrdDoc.MailMerge()
              With wrdMailMerge
                  .Execute()
              End With
  
              wrdDoc.SaveAs(fileOut)
  
              wrdApp.Quit(False)
  
              ' Release References.'
              wrdSelection = Nothing
              wrdMailMerge = Nothing
              wrdDoc = Nothing
              wrdApp = Nothing
  
  
              ans = "Merged OK"
  
              Call writeToLogFile(errorLog, "This worked, written to  " &amp; fileOut)
  
          Catch ex As Exception
              ans = "error : exception thrown " &amp; ex.ToString
              Call writeToLogFile(errorLog, ans)
          End Try
  
      Else
          ans = "error ; unable to open Date File : " &amp; datafile
          If (logErrors) Then
              Call writeToLogFile(errorLog, "The specified source csv file does not exist. Unable " &amp; _
                 "to process it. Filename provided: " &amp; datafile)
          End If
      End If
  
      Return ans
  
  End Function
  </code></pre>