MS Word Replace plaintext with MergeField using vb.net

I have a bunch of letters in RTF format

I made code to convert them to DOTX

The next step is to convert the old plaintext fields into mailmerge fields

This is what i need help with



Here is my current code:
Dim rtfLoc = "c:/test/inputdoc.rtf"
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(rtfLoc)
currentDoc.SaveAs(dotXLoc, Fileformat)
currentDoc.Close()
wordApp.Quit()

Open in new window



Lets say i have an array

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

Open in new window


Here is the code to run through the array for each replace
' 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

Open in new window

the first column is the look for text,
the second column is the replace text, which has to be a Word Merge Field

So plaintext [lastname] will be replaced with MergeField   $Field.LName


How to do this?





Can I do this as i run the migrate from RTF code above, or do i need to save as DOTX first, then open and do..etc.
LVL 15
Ess KayEntrapenuerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

GrahamSkanRetiredCommented:
An open Word document has the same object structure whatever the file type that it was loaded from, so no intermediate conversion is necessary.
Ess KayEntrapenuerAuthor Commented:
please read the question again.  

i have a full Plaintext document

i need to replace some of the text with Microsoft MergeField fields
GrahamSkanRetiredCommented:
Sorry, I took this as your question:

"Can I do this as i run the migrate from RTF code above, or do i need to save as DOTX first, then open and do..etc."

I'll see if I can address any of the detail in your exposition.
Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

GrahamSkanRetiredCommented:
This is VBA code, but it demonstrates the method:
Sub TextToMergeField()
    Dim currentdoc As Word.Document
    Dim rng As Word.Range
    Dim replacements(1, 1) As String
    Dim i As Integer
    
    replacements(0, 0) = "[firstname]"
    replacements(0, 1) = "FName"
    replacements(1, 0) = "[lastname]"
    replacements(1, 1) = "LName"
    
    Set currentdoc = ActiveDocument
    For i = 0 To 1
        Set rng = currentdoc.Range
        With rng.Find
            .Text = replacements(i, 0)
            Do While .Execute(Replace:=wdReplaceOne) 'replace with ""
                currentdoc.Fields.Add rng, wdFieldMergeField, replacements(i, 1)
            Loop
        End With
    Next i
End Sub

Open in new window

Ess KayEntrapenuerAuthor Commented:
i don't know how to convert that to .net
GrahamSkanRetiredCommented:
Here is the core of my code (with the word Set removed) plugged into your code. I have removed the two string declarations as each value is only used once in the loop and setting them would introduce an extra couple of steps.
 
'
 Loop over all elements.
For i As Integer = 0 To bound0
       rng = currentdoc.Range
        With rng.Find
            .Text = replacements(i, 0)
            Do While .Execute(Replace:=wdReplaceOne) 'replace with ""
                currentdoc.Fields.Add rng, wdFieldMergeField, replacements(i, 1)
            Loop
        End With
    Next i

Open in new window

I am downloading Visual Studio 2015 community edition to test it, but it is taking a very long time.
Ess KayEntrapenuerAuthor Commented:
thanks i used your code to do what i need.  will paste code and accept when i get back.  thank you
Ess KayEntrapenuerAuthor Commented:
This is what i used in .net

SUB DOSTUFF()
  Dim Fileformat As Microsoft.Office.Interop.Word.WdSaveFormat = Word.WdSaveFormat.wdFormatXMLTemplate  'SAVE AS DOT
  Dim wordApp As Word.Application = New Microsoft.Office.Interop.Word.Application()
  Dim currentDoc As Microsoft.Office.Interop.Word.Document = wordApp.Documents.Open("c:/test/file.rtf")

  TextToMergeField(currentDoc)

  currentDoc.SaveAs("c:/test/docmake.dotx", Fileformat)
  currentDoc.Close()
  wordApp.Quit()

END SUB

Open in new window


Private Sub TextToMergeField(ByRef currentdoc As Word.Document)
        Dim rng As Word.Range
        Dim replacements(1, 1) As String
        Dim i As Integer

        replacements(0, 0) = "<user.FullName>"
        replacements(0, 1) = "Name.FULLNAME"
        replacements(1, 0) = "<user.AddrName>"
        replacements(1, 1) = "Address.ADDR1"

        currentdoc.Activate()
        For i = 0 To 1
            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 i
    End Sub

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ess KayEntrapenuerAuthor Commented:
Thanks
Albi-LotCommented:
My preference with mail merge scenarios is the one based on template document(s) which are filled with data at runtime. I think you could benefit from this kind of approach too. There are several 3rd party solutions available, I am using Docentric Toolkit.

Data is provided by .NET application as collection classes and can come from anywhere (xml, database, plain text, …). It only takes two lines of code to merge data with the template. Output can be DOCX and PDF.

The benefits I see are:
(1) Templates can be made with MS Word and can contain any formatting
(2) Even end users can change or create templates as long as the data structures are the same
(3) It runs well on servers with multiple users and generates word or pdf documents without MS Office or PDF driver installed.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.