我有这个正则表达式代码,它工作正常,但是我试图在foreach中操纵文本,但对文档不起作用。 我想更改选择的样式并剪掉标记。
Sub Substituir()
Set documento = ActiveDocument.Range
Dim texto As String
Set oRegExp = New RegExp
oRegExp.Pattern = "<h1>[\s\S]*?</h1>"
oRegExp.Global = True
oRegExp.MultiLine = True
Dim resultado As MatchCollection
Set resultado = oRegExp.Execute(documento)
For Each r In resultado
r.Find.Execute FindText:="<h1>", ReplaceWith:="", Replace:=wdReplaceAll
r.Find.Execute FindText:="</h1>", ReplaceWith:="", Replace:=wdReplaceAll
Next
End Sub
我想要的结果是替换
<h1>bla bla</h1>
与
bla bla
然后将样式更改为单词中的标题1。
答案 0 :(得分:1)
仅当无法使用通配符内置的内置Words实现我想要的功能时,我才会求助于正则表达式。
Option Explicit
Sub Substituir(Optional ByVal this_tag As String = "h1", Optional ByVal this_replacement_style As String = "Heading 1")
With ActiveDocument.Content
With .Find
.ClearFormatting
.Text = "(\<" & this_tag & "\>)(*)(\</" & this_tag & "\>)" ' Default is "(<h1>)(*)(</h1>)"
.Replacement.Text = "\2"
.Format = True
.Replacement.Style = this_replacement_style
.Wrap = wdFindContinue
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With
End With
End Sub