code_junkie

Automating Word Mailmerge not working as expected

Nov 11th, 2011
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. Public Function processFile(ByVal datafile As String, ByVal fileOut As String) As String
  2. Dim ans As String = String.Empty
  3.  
  4. errorLog = "C:TempTemplate_error.log"
  5.  
  6. If (File.Exists(datafile)) Then
  7.  
  8. Try
  9.  
  10. ' Create an instance of Word and make it invisible.'
  11.  
  12. wrdApp = CreateObject("Word.Application")
  13. wrdApp.Visible = False
  14.  
  15. ' Add a new document.'
  16.  
  17. wrdDoc = wrdApp.Documents.Add(fileOut & ".template")
  18. wrdDoc.Select()
  19.  
  20. Dim wrdSelection As Word.Selection
  21. Dim wrdMailMerge As Word.MailMerge
  22.  
  23.  
  24. wrdDoc.MailMerge.OpenDataSource(datafile)
  25.  
  26. wrdSelection = wrdApp.Selection()
  27. wrdMailMerge = wrdDoc.MailMerge()
  28. With wrdMailMerge
  29. .Execute()
  30. End With
  31.  
  32. wrdDoc.SaveAs(fileOut)
  33.  
  34. wrdApp.Quit(False)
  35.  
  36. ' Release References.'
  37. wrdSelection = Nothing
  38. wrdMailMerge = Nothing
  39. wrdDoc = Nothing
  40. wrdApp = Nothing
  41.  
  42.  
  43. ans = "Merged OK"
  44.  
  45. Call writeToLogFile(errorLog, "This worked, written to " & fileOut)
  46.  
  47. Catch ex As Exception
  48. ans = "error : exception thrown " & ex.ToString
  49. Call writeToLogFile(errorLog, ans)
  50. End Try
  51.  
  52. Else
  53. ans = "error ; unable to open Date File : " & datafile
  54. If (logErrors) Then
  55. Call writeToLogFile(errorLog, "The specified source csv file does not exist. Unable " & _
  56. "to process it. Filename provided: " & datafile)
  57. End If
  58. End If
  59.  
  60. Return ans
  61.  
  62. End Function
  63.  
  64. wrdDoc = wrdApp.Documents.Add(TemplateFileName)
  65. wrdDoc.Select()
  66. Dim wrdSelection As Word.Selection
  67. Dim wrdMailMerge As Word.MailMerge
  68.  
  69.  
  70. wrdDoc.MailMerge.OpenDataSource(DataFileName)
  71.  
  72. wrdSelection = wrdApp.Selection()
  73. wrdMailMerge = wrdDoc.MailMerge()
  74. With wrdMailMerge
  75. .Execute()
  76. End With
  77.  
  78. ' This is the wrong thing to do. It just re-saves the template file you opened. '
  79. 'wrdDoc.SaveAs(OutputFileName) '
  80.  
  81. ' The resulting merged document is actually stored '
  82. ' in the MailMerge object, so you have to save that '
  83. wrdMailMerge.Application.ActiveDocument.SaveAs(OutputFileName)
  84.  
  85. wrdApp.Quit(False)
  86.  
  87. wrdDoc.MailMerge.OpenDataSource(templateName)
  88.  
  89. data = "C:My Data.xls"
  90. wrdDoc.MailMerge.OpenDataSource(data)
Add Comment
Please, Sign In to add comment