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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 11:12:33  来源:igfitidea点击:

Word VBA How to find and replace a string starting with "<start>" and ending with "<end>"?

vbams-word

提问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 .Textproperty 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 .Textproperty 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|Referencesand 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 的回答的评论,但这里的代表不够。