View Single Post
 
Old 08-11-2020, 10:56 PM
Guessed's Avatar
Guessed Guessed is offline Windows 10 Office 2016
Expert
 
Join Date: Mar 2010
Location: Canberra/Melbourne Australia
Posts: 4,176
Guessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant future
Default

Greg, that looks like a better approach. I had a go at minimising the code and avoiding the RegEx which I don't think adds any value to this particular problem.

Code:
Sub HilitePartNumsHyph()
  Dim rngWord As Range, aRng As Range, sWord As String
  Dim oRng As Range, oNum As Range, rngFrag As Range, sPref As String
  
  Set oRng = ActiveDocument.Range
  With oRng.Find
    Do While .Execute(findText:="[0-9]{1,}", MatchWildcards:=True)
      Set oNum = oRng.Words(1)
      sWord = UCase(Trim(oNum.Text))
      If sWord Like "*[A-Z]*" Then                  'If there is a letter included it is a part num
        sPref = Ucase(oNum.Characters.First.Previous)
        Do While SwitchHitter(sPref)     'Look back
          oNum.MoveStart Unit:=wdWord, Count:=-1
        Loop
        If oNum.Text = Trim(oNum.Text) Then   'not ending with a space
          Do While SwitchHitter(UCase(oNum.Characters.Last.Next))   'Look forward
            oNum.MoveEnd Unit:=wdWord, Count:=1
          Loop
        End If
        oNum.HighlightColorIndex = wdYellow
        Debug.Print oNum                            'This is the output list
      End If
      oRng.Start = oNum.End
    Loop
  End With
End Sub

Function SwitchHitter(aChar As String, Optional str As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-") As Boolean
  'Returns true if the character appears in provided string
  SwitchHitter = InStr(str, aChar) > 0
End Function
__________________
Andrew Lockton
Chrysalis Design, Melbourne Australia
Reply With Quote