View Single Post
 
Old 11-30-2024, 11:50 AM
gmaxey gmaxey is offline Windows 10 Office 2019
Expert
 
Join Date: May 2010
Location: Brasstown, NC
Posts: 1,617
gmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nice
Default

Thanks. I thought I would refine and comment a bit:

Code:
Sub InsertTab_Before_FirstInstance()
Dim oPar As Paragraph
Dim oRng As Word.Range, oFIRng As Range
Dim arrWords
Dim lngIndex As Long, lngListIndex As Long
  'Purpose - to find and prefix the first instance of any word (defined from a list) in each document paragraph define.
  'The number of possible words is variable and defined in an array.
  arrWords = Array("means", "includes", "has", "any")
  'Look in each paragraph
  For Each oPar In ActiveDocument.Range.Paragraphs
    'Define the oFIRng
    Set oFIRng = Nothing 'Note - if oFIRng remains nothing at the end of this looop then none of the possible words where found.
    'Set the search range variable
    Set oRng = oPar.Range
    'Initialize\reset the counter
    lngListIndex = 0
    Do
      'We are entering a Do ... Loop and we stay in this loop until we have looked in the defined range
      'for all the listed words.
      For lngIndex = lngListIndex To UBound(arrWords)
        'Ensure the search range allows starts at the start of the paragraph
        oRng.Start = oPar.Range.Start
        With oRng.Find
          'Note the search range is always from the start of the paragraph to end of the paragraph
          'or end of the last word found.
          .ClearFormatting
          .Replacement.ClearFormatting
          .Text = arrWords(lngIndex)
          .MatchWholeWord = True
          If .Execute Then
            'We have found a first instance word.
            Set oFIRng = oRng.Duplicate
            'Note oRng.End is now defined at then end of the found word.
          End If
          'Found yes, but does one of the other FI words in the list precede it?
          'Index the counter look for next word in the array
          lngListIndex = lngListIndex + 1
          If lngListIndex = UBound(arrWords) + 1 Then
            'We have looked for the last word in the list. Escape the Do ... Loop
            Exit Do
          End If
        End With
      Next lngIndex
    Loop
    'Was a listed word found?
    If Not oFIRng Is Nothing Then
      If oFIRng.Characters.First.Previous = " " Then oFIRng.Characters.First.Previous.Delete
      If Not oFIRng.Characters.First.Previous = Chr(9) Then oFIRng.InsertBefore Chr(9)
    End If
  Next
lbl_Exit:
  Exit Sub
End Sub
__________________
Greg Maxey
Please visit my web site at http://www.gregmaxey.com/
Reply With Quote