Word VBA Find/Replace Issue

心已入冬 提交于 2019-12-25 08:00:39

问题


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:


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.



来源:https://stackoverflow.com/questions/22187909/word-vba-find-replace-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!