find text and replace with docvariable

D

Diane

Group,
I am testing code that will find text such as "##" and replace it with a
docvariable.
I can successfully read a directory of over 500 MSWORD documents and find
text and replace text, but I need to find text and replace with a docvariable
field.

I want to add this code for my "replacement" but not having any luck doing
this:

"Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
"DOCVARIABLE abc ", PreserveFormatting:=True
Selection.Font.color = wdColorDarkRed

My code that works with find/replace text :

With oWord.Selection.Find
.ClearFormatting()
.Text = "##"

If oWord.Selection.Find.Found = True Then
Numberoffiles += 1
End If

With .Replacement
.ClearFormatting()
.Text = "**TEST**"
.Font.Color = Word.WdColor.wdColorRed
End With

.Execute(Replace:=Word.WdReplace.wdReplaceAll)


End With

I am coding a VB.NET application with a MSWORD template.doc.
Using MSOFFICE 2003.
Diane
 
G

Greg Maxey

Something like this perhaps:
Sub ScratchMacro()
Dim oRng As Range
Set oRng = ActiveDocument.Range
With oRng.Find
.Text = "##"
While .Execute
oRng.Delete
oRng.Fields.Add oRng, wdFieldDocVariable, """Your Variable Name""",
True
Wend
End With
End Sub
 
D

Diane

Greg,
Many thanks for your example. I finally had a chance to try this and it is
almost working, I'm stuck in a loop, I'm not clear as to how to have it move
on to my next find, it is finding my first text, but then it repeats the
while loop. My end result, it replaces only the first "*" and adds many
docvariables at that same position.


orng = oWord.ActiveDocument.Range

With orng.Find
.ClearFormatting()
.Text = "*"
Loop--> While .Execute
orng.Delete()
orng.Fields.Add(orng,
Word.WdFieldType.wdFieldDocVariable, "abc", True)
End While

End With

Thanks,
Diane
 

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