We help IT Professionals succeed at work.

VBA Word Find & Replace fails to work

Medium Priority
496 Views
Last Modified: 2012-05-12
I have a sub that is supposed to search through my word document performing a find and replace.  For some reason, it completely fails to do its job.  The original text is still in the document and nothing gets replaced.  The code is as follows:

 'Show hidden text
    ActiveWindow.View.ShowHiddenText = True
       
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .ClearFormatting
        .Text = "Text To Find"
        .Replacement.Text = "Text To Replace"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .Execute Replace:=wdReplaceAll
    End With

It's driving me nuts as I simply cannot understand why it doesn't work.  I recorded a macro which found and replaced the text and then used said macro, but nothing gets replaced!!!

Can anyone give me a clue as to why this might be please
   
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2011
Commented:
HAve you selected the document text on which it should work?  Try adding:
activedocument.range.select before selection.find

Chris
CERTIFIED EXPERT

Commented:
I cut and pasted it into the attached and it works fine

reg

102-gb.doc
CERTIFIED EXPERT
Top Expert 2011

Commented:
Forgot to paste!

Chris
ActiveWindow.View.ShowHiddenText = True
        
    activedocument.Range.Select
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .ClearFormatting
        .Text = "Text To Find"
        .Replacement.Text = "Text To Replace"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .Execute Replace:=wdReplaceAll
    End With

Open in new window

GrahamSkanRetired
CERTIFIED EXPERT
Top Expert 2012

Commented:
You can shrink your code to this:

With ActiveDocument.Range.Find
        .Text = "Text To Find"
        .Replacement.Text = "Text To Replace"
        .Execute Replace:=wdReplaceAll
    End With

Open in new window


However, we may need to see the document. Remove as much as possible while it still demonstrates the problem, especially anything confidential, and post it, and the actual code that you are using.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.