0

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

1 回答 1

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
于 2016-08-04T08:31:13.383 回答