Word VBA 如何查找和替换以“<start>”开头并以“<end>”结尾的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5191176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Word VBA How to find and replace a string starting with "<start>" and ending with "<end>"?
提问by Saul
As per the question, trying to replace a span of text in a Word document that is of the form
根据问题,尝试替换形式为的 Word 文档中的一段文本
"<start>..........<end>"
"<start>..........<end>"
of variable length. It will only occur once in the document.
可变长度。它只会在文档中出现一次。
回答by
You can use Word's built-in find/replace functionality to do this, eg
您可以使用 Word 的内置查找/替换功能来执行此操作,例如
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.
这是通过简单地用 Word 2007 录制宏并查看 VBA 代码发现的。该.Text
属性可以使用通配符,例如*
和[A-Z]
,类似于@Jayantha 的响应中引用的正则表达式。反斜杠包含在.Text
属性中,因为<
和>
也是通配符,反斜杠将它们转义。在 Word 帮助文件中搜索“替换”。
回答by Jayantha Lal Sirisena
Use regular expressions, try this:
使用正则表达式,试试这个:
/start\.*/end\
Replace /
with <
and \
with >
in the above regex.
替换上面的正则表达式中的/
with<
和\
with >
。
回答by Chris H
If you want to use regular expressions, you'll need to go to Tools|References
and add Microsoft VBScript Regular Expressions Libarary
如果要使用正则表达式,则需要转到Tools|References
并添加Microsoft VBScript Regular Expressions Libarary
I think you could use ^<start>.*<end>$
for your regex.
我认为你可以^<start>.*<end>$
用于你的正则表达式。
This should be a comment to @Jayantha's answer probably, but not enough rep here.
这应该是对@Jayantha 的回答的评论,但这里的代表不够。