您需要在OCCURENCES while循环,因为Execute
返回True
如果查找操作是成功的:
Option Explicit
Sub TestFind()
Dim Content As Range
Dim i As Long
Set Content = ActiveDocument.Content
' let's print what we got so far
Debug.Print "All text is:" & vbNewLine & Content.Text
With Content.Find
.ClearFormatting
' our find loop
Debug.Print "Occurences: "
While .Execute(MatchWildcards:=True, Wrap:=wdFindStop, FindText:="[\{\[][a-zA-Z0-9\,\.\:\-;^l^13 ]@[\}\]]")
' count occurences
i = i + 1
' lets bold text just for testing purposes
Content.Bold = True
' and also print each occurence
Debug.Print vbTab & "Occurence #" & i & vbTab & Content.Text
Wend
End With
End Sub
输出:
All text is:
{xxxxx}
asdasd
{ xxxx }
As{asd}
asff
{xxx }
{xxxx, xxxx}
safasf
{ xxxx,xxxx}
{xxxx,xxxx }
{ xxxx, xxxx }
Occurences:
Occurence #1 {xxxxx}
Occurence #2 { xxxx }
Occurence #3 {asd}
Occurence #4 {xxx }
Occurence #5 {xxxx, xxxx}
Occurence #6 { xxxx,xxxx}
Occurence #7 {xxxx,xxxx }
Occurence #8 { xxxx, xxxx }
而且,这不是一个正则表达式都和传统的图案非常粗糙。如果你需要一个真正的正则表达式,看看here。
嗨,谢谢你的帮助......但在文本中,我们有一个字段代码之间所需的字符串......一旦找到字段代码,它不会读取下一个发生。 例如: 所有文本为: {xxxxx} [field code] asdasd {xxxx} As {asd} asff {xxx} {xxxx,xxxx} safasf {xxxx,xxxx} {xxxx,xxxx} {xxxx,xxxx } 在这种情况下,它只会读取第一个事件。我已尝试提供的解决方案,并提供以下输出: 发生: 发生#1 {xxxxx} 发生#2 发生#3 \t。 \t。 \t。 \t。 \t无限 – Rocky
@Rocky,它适用于我的“全部文本”。我[有9次出现](https://i.stack.imgur.com/2XyIO.png)(你的域代码也被捕获了),所以我认为这是你的愿望,不是吗?不幸的是,我不熟悉这些模式。 – CommonSense
@Rocky,我也建议你放弃那些丑陋的模式,并使用RegEx代替!像regex101.com这样的网站很多,您可以在网上粘贴更多的数据和测试模式。我敢肯定,规则模式“抓住所有花括号内的花括号,如果之后有方括号 - 如果我理解你的规则,就可以用同样的方式抓住它们”更容易,更可读。所以试试真实的数据,如果你再次卡住 - 更新你的问题链接到regex101。干杯! – CommonSense