Word VBA Find/Replace Issue

2019-08-30 05:01发布

Using the VBA Find and Replace in Word i have the issue that if i am trying to replace all instances of "John(space)Smith" for example, with "John(non-breaking space)Smith", the Find Replace function replaces all "John(space)Smith" as well as all "John(non-breaking space)Smith" with "John(non-breaking space)Smith". Before i am using this and leaving track changes i don't really want it to replace it with itself. I have tried using Chr(32) to only select the space but still to no avail. (I will just point out here that i am not literally writing (space) and (non-breaking space) but it is just symbolizing where the spaces and non-breaking spaces are)

It seems that the Find/Replace doesn't differentiate between a space and a non-breaking space when it does a find. I tried it in the opposite direction and it works fine however (non-breaking space to space find and replace). So my theory is that for a Find/Replace, a non-breaking space is regarded as a space but a space is not regarded as a non-breaking space. Knowing this, can anyone offer a solution to get past this? Can i somehow loop through a document and find instances of "John(space)Smith" and replace accordingly? A loop method should avoid this issue but i am not sure how to implement it.

ActiveDocument.Range.Select

strFind = "John" & Chr(32) & "Smith"
strReplace = "John" & Chr(202) & "Smith" 'note the chr(202) is because i am working on a mac. 160 on pc i believe

Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
 .Text = strFind
 .Replacement.Text = strReplace
 .Forward = True
 .Wrap = wdFindAsk
 .Format = True
 .MatchCase = False
 .MatchWholeWord = False
 .MatchWildcards = False
 .MatchSoundsLike = False
 .MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll

Thanks,

Cameron

1条回答
女痞
2楼-- · 2019-08-30 05:52

You need to use wildcards to do so. Therefore change appropriate lines into the following ones:

strFind = "(John)( )(Smith)"
strReplace = "\1^s\3"      'for Win, and for Mac try: "\1" & chr(202) & "\3"

and set this line into true:

.MatchWildcards = True

For more information please see THIS LINK.

查看更多
登录 后发表回答