Word VBA How to find and replace a string starting with "<start>" and ending with "<end>"?
As per the question, trying to repl开发者_如何学JAVAace a span of text in a Word document that is of the form
"<start>..........<end>"
of variable length. It will only occur once in the document.
You can use Word's built-in find/replace functionality to do this, eg
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "\<start\>*\<end\>"
.Replacement.Text = ""
.Forward = True
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = True
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceAll
This was found from simply recording a macro with Word 2007 and viewing the VBA code. The .Text
property can use wildcards, such as *
and [A-Z]
, similar to regular expressions referred to in @Jayantha's response. The back-slashes are included in the .Text
property because <
and >
are wildcard characters too, and the back-slash escapes them. Search for "replace" in the Word help files.
Use regular expressions, try this:
/start\\.*/end\
Replace /
with <
and \
with >
in the above regex.
If you want to use regular expressions, you'll need to go to Tools|References
and add Microsoft VBScript Regular Expressions Libarary
I think you could use ^<start>.*<end>$
for your regex.
This should be a comment to @Jayantha's answer probably, but not enough rep here.
精彩评论