0
votes

I am using RegEx search, for find out the particular word in my MS-Word document, and the search result is stored into a variable. My problem is I want to apply a custom style only for the search result

Input: worldwide[1,2]. Before, during or after the [1,3,4][1,2,4,5] [1,2,6,7,8] [1,2] [1,2]

I am using the following code

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

1 Answers

1
votes

The For Each m In mat loop iterates over each item in the mat collection. M is not a range. You need to set a range starting at m.FirstIndex and ending at m.FirstIndex + m.Length. Then you'll need to select the range and use Selection.Style to style the range.

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