Search code examples
c#.netvb.netms-wordmergefield

.NET & Word - How to Convert PlainText to MergeField in Document


i am using Visual Studio .NET (VB) So if you have a solution in C#, just go here first (http://converter.telerik.com/)

I have a document with text, and an array of words to replace: I need to replace the plaintext and substitute with actual mergefield

Dim replacements(,) As String =
        New String(,) {{"[firstname]", "$Field.FName"},
               {"[lastname]", "$Field.LName"},
               {"[addr]", "$Field.Addr.St"},
               {"[city]", "$Field.City"}}

Dim dotXLoc "c:/test/result.dotx"

Dim Fileformat As Microsoft.Office.Interop.Word.WdSaveFormat = Word.WdSaveFormat.wdFormatXMLTemplate  'SAVE AS DOT
Dim wordApp As Object = New Microsoft.Office.Interop.Word.Application()
Dim currentDoc As Microsoft.Office.Interop.Word.Document = wordApp.Documents.Open(dotXLoc)

' Get bounds of the array.
Dim bound0 As Integer = replacements.GetUpperBound(0)

' Loop over all elements.
For i As Integer = 0 To bound0
    ' Get element.
    Dim FieldFind As String = replacements(i, 0)
    Dim FieldReplace As String = replacements(i, 1)

        '<<< CODE HERE TO REPLACE TEXT WITH MERGEFIELD >>>
Next

currentDoc.SaveAs(dotXLoc & " v2.dotx", Fileformat)
currentDoc.Close()
wordApp.Quit()

Solution

  • Here is the end result

     Public sub main()
    
                Dim rtfLoc = "c:/temp.rtf"
                Dim dotXLoc = "c:/temp.dotx"
                Dim Fileformat As Microsoft.Office.Interop.Word.WdSaveFormat = Word.WdSaveFormat.wdFormatXMLTemplate
                Dim wordApp As Word.Application = New Microsoft.Office.Interop.Word.Application()
                Dim currentDoc As Microsoft.Office.Interop.Word.Document = wordApp.Documents.Open(rtfLoc)
    
    
                TextToMergeField(currentDoc)
    
                currentDoc.SaveAs(dotXLoc, Fileformat)
                currentDoc.Close()
                wordApp.Quit()
     End Sub
    

    we call TextToMergeField(currentDoc) from the main function this way we can loop through multiple documents and replace all instances

     Private Sub TextToMergeField(ByRef currentdoc As Word.Document)
        Dim rng As Word.Range
        Dim replacements(,) As String =
        New String(,) {{"[firstname]", "$Field.FName"},
               {"[lastname]", "$Field.LName"},
               {"[addr]", "$Field.Addr.St"},
               {"[city]", "$Field.City"}}
        Dim bound0 As Integer = replacements.GetUpperBound(0)
        currentdoc.Activate()
        For i As Integer = 0 To bound0
            rng = currentdoc.Range
            With rng.Find
                .Text = replacements(i, 0)
                Do While .Execute(Replace:=WdReplace.wdReplaceOne)
                    currentdoc.Fields.Add(rng, WdFieldType.wdFieldMergeField, replacements(i, 1))
                Loop
            End With
        Next 
    End Sub
    

    Hope this helps someone