Thread: [Solved] Find Challenge
View Single Post
 
Old 01-06-2025, 04:21 PM
gmaxey gmaxey is offline Windows 10 Office 2019
Expert
 
Join Date: May 2010
Location: Brasstown, NC
Posts: 1,601
gmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nice
Default

Batman1,


No denying that your RegEx code and pattern is simple compared to the Find method. Both your Test() and my ScratchMacroC() return the same results. But, how do you then process the Match object? Let's say that we not only want to Debug.Print the Match.Value, we want to highlight it in the text as well:

Code:
Sub ScratchMacroC()
Dim oRng As Range, oRngProcess As Range
Set oRng = ActiveDocument.Range
Dim lngIndex As Long
  With oRng.Find
    .Text = "[0-9]{1,}"
    .MatchWildcards = True
    While .Execute
      lngIndex = 1
      Set oRngProcess = Nothing
      If InStr(Left(oRng.Text, 4), "2") > 0 Then
        Set oRngProcess = oRng.Duplicate
        Select Case Len(oRng.Text)
          Case Is > 4
            Debug.Print Left(oRng.Text, 5)
            oRngProcess.End = oRngProcess.Start + 5
            lngIndex = 5
          Case Is = 4
            Debug.Print oRng.Text
            oRngProcess.End = oRngProcess.Start + 4
            lngIndex = 4
        End Select
      End If
      oRng.End = oRng.Start + lngIndex
      If Not oRngProcess Is Nothing Then oRngProcess.HighlightColorIndex = wdBrightGreen
    Wend
  End With
lbl_Exit:
  Exit Sub
End Sub

EDIT: Well, I won't say this is the best way, but I think I may have answered my own question:


Code:
Sub RegExMethod()
Dim RegEx As Object, Matches As Object, Match As Object
Dim oRng As Range
    Set RegEx = CreateObject("VBScript.RegExp")
    With RegEx
        .Global = True
        .Pattern = "(?=(\d){0,3}2)\d{4,5}"
    End With
    Set Matches = RegEx.Execute(ActiveDocument.Range.Text)
    For Each Match In Matches
      Set oRng = ActiveDocument.Range
      With oRng.Find
        .Text = Match.Value
        If .Execute Then
          oRng.HighlightColorIndex = wdYellow
        End If
      End With
    Next
lbl_Exit:
  Exit Sub
End Sub

Now, would you mind breaking down your pattern and explaining how it is constructed?
__________________
Greg Maxey
Please visit my web site at http://www.gregmaxey.com/
Reply With Quote