将风格应用于特定单词

时间:2016-08-04 06:52:10

标签: vba word-vba word-style

我正在使用RegEx搜索,找出我的MS-Word文档中的特定单词,并将搜索结果存储到变量中。我的问题是我只想为搜索结果应用自定义样式

输入: 世界范围内[1,2]。在[1,3,4] [1,2,4,5] [1,2,6,7,8] [1,2] [1,2]之前,期间或之后

我正在使用以下代码

Sub RegexReplaces()
    Set matches = New regExp
    Dim Sure As Integer
    Dim rng As Range
    matches.Pattern = "([\[\(][0-9, -]*[\)\]])"
    matches.Global = True
    Dim mat As MatchCollection
    Set mat = matches.Execute(ActiveDocument.Range)
    For Each m In mat
        Sure = MsgBox("Are you sure?" + m, vbOKCancel)
        If Sure = 1 Then
            m.Style = ActiveDocument.Styles("Heading 1")    'this is the error line
        Else
            MsgBox "not1111"
        End If
    Next m
End Sub

1 个答案:

答案 0 :(得分:1)

For Each m In mat循环遍历mat集合中的每个项目。 M不是范围。您需要设置一个范围,从m.FirstIndex开始,到m.FirstIndex + m.Length结束。然后,您需要选择范围并使用Selection.Style来设置范围的样式。

Sub RegexReplaces()
    Set matches = New regExp
    Dim Sure As Integer
    Dim rng As Range
    matches.Pattern = "([\[\(][0-9, -]*[\)\]])"
    matches.Global = True
    Dim mat As MatchCollection
    Set mat = matches.Execute(ActiveDocument.Range)
    For Each m In mat
        Sure = MsgBox("Are you sure?" + m, vbOKCancel)
        If Sure = 1 Then

            Set rng = ActiveDocument.Range(Start:=m.FirstIndex, End:=m.Length + m.FirstIndex)
            rng.Select
            Selection.Style = ActiveDocument.Styles("Heading 1")
        Else
            MsgBox "not1111"
        End If
    Next m
End Sub