Replacing empty strings

N

Neil Fraser

Hello,

A scripted search and replace in a Word document works fine when
replacing text with other text. But it doesn't do anything when
replacing text with an empty string.

With WordDoc.Selection.Find
.ClearFormatting
.Replacement.Font.ColorIndex = wdAuto
.Replacement.Font.Bold = False
.Text = "test"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchByte = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.MatchFuzzy = False
.Execute Replace:=wdReplaceAll
End With

Change
.Replacement.Text = ""
to
.Replacement.Text = " "
and it will replace "test" with a space perfectly. But there doesn't
seem to be a way to replace "test" with nothing. Any suggestions on
how to delete text?
 
D

Dave Lett

Hi Neil,

Apparently, Word is getting hung on the fact that you want to format the ""
replacement. The following will remove "test":

With WordDoc.Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "Test"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With


HTH,
Dave
 
N

neil.fraser

Apparently, Word is getting hung on the fact that you want to
format the "" replacement. The following will remove "test":

Thanks! That worked perfectly. I'll selectively apply formatting only
if there is a non-null replacement string.
Wonder if this is another Word bug...
 
K

Klaus Linke

Apparently, Word is getting hung on the fact that you want to
Thanks! That worked perfectly. I'll selectively apply formatting only
if there is a non-null replacement string.
Wonder if this is another Word bug...


It works the same way in the user interface.

If you specify some formatting, you don't need to enter "^&" in "Replace with:".
That is kind of neat if you often apply formatting with "Find/Replace".

Since you can leave "Find what:" empty, too, to search for some specific
formatting, it seems like a sensible convention.
It can bite you though, if you aren't aware of it...

Regards,
Klaus
 

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