replace regular Text with mail New Merge Fields

M

Marcus

Help needed please.

I am in the process of replacing regular Text (e.g. $incident_date$) with
new Merge field using a VB.net program. I have 100’s of documents with 100’s
of variables to replace. Below is my code
Private Sub SearchReplacewithMergeFields(ByVal sFileName As Object, ByVal
strFileName As Object)
Dim WordApp As New Microsoft.Office.Interop.Word.Application
Dim WordDoc As New Microsoft.Office.Interop.Word.Document

WordDoc = WordApp.Documents.Open(sFileName, , False)
WordDoc.Activate()
WordApp.Visible = True
With WordApp.Selection.Range.Find
.Text = "$incident_date$"
.Replacement.Text = ""
.Forward = True

..Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll,
Format:=True, MatchCase:=True, MatchWholeWord:=True)
WordDoc.Fields.Add(Range:=WordApp.Selection.Range,
Type:=Microsoft.Office.Interop.Word.WdFieldType.wdFieldMergeField,
Text:="""AccidentDate""")
End With

WordDoc.SaveAs(strFileName)

Exit_Command1_Click:
If Err.Number <> 0 Then
MsgBox(Err.Number & ", " & Err.Description)
End If
WordDoc.Close(False)
WordDoc = Nothing
WordApp.Quit()
WordApp = Nothing


End Sub
I ran into the following problem. My regular Text gets replaced with space
and the new Merge field is added to the beginning of the document. I need the
Merge field exactly in the same location where the regular Text was.
I am stuck with this, can some expert help me please

Thanks
Marcus
 
G

Graham Mayor

I don't know anything about vb.net but in Word vba perhaps

Dim oDoc As Document
Dim oRng As Range
Set oDoc = ActiveDocument
With Selection
.HomeKey wdStory
With .Find
While .Execute("$incident_date$")
Set oRng = Selection.Range
oRng.Fields.Add oRng, wdFieldMergeField, _
"""AccidentDate""", False
Wend
End With
End With

would help point the way?

--
<>>< ><<> ><<> <>>< ><<> <>>< <>><<>
Graham Mayor - Word MVP


<>>< ><<> ><<> <>>< ><<> <>>< <>><<>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top