将样式应用于特定单词

Applying style to particular words

我正在使用 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

For Each m In mat 循环遍历 mat 集合中的每个项目。 M 不是范围。您需要设置从 m.FirstIndex 开始到 m.FirstIndex + m.Length 结束的范围。然后,您需要 select 范围并使用 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