View Single Post
 
Old 07-30-2025, 04:33 PM
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

Vivka,


Question and comment about your code below.


1. I notice that you (and others I have observed) use the Find.Found method. E.g. If rng.find.found ...


Why? find.found returns True but so does


If .Execute.


2. Your code will error if the one of the find returns is at the end of the document.


Consider:


Code:
Sub Find_N_Embolden()
'Revised GKM
Dim oRng As Range
  Application.ScreenUpdating = False
  Set oRng = Selection.Range
  With oRng.Find
    .Text = "\@[A-Z]{1,}"
    .MatchWildcards = True
    .Forward = True
    .Wrap = wdFindStop
    Do While .Execute
      If oRng.InRange(Selection.Range) Then
        Select Case True
          Case oRng.End = ActiveDocument.Range.End - 1
            oRng.Font.Bold = True
          Case oRng.Characters.Last.Next <> "_"
            oRng.Font.Bold = True
          Case oRng.End <= ActiveDocument.Range.End - 4
            oRng.MoveEnd unit:=wdCharacter, Count:=3
            If Right(oRng.Text, 3) Like "_[0-9][0-9]" Then oRng.Font.Bold = True
        End Select
      End If
      oRng.Collapse wdCollapseEnd
    Loop
  End With
  Application.ScreenUpdating = True
  Set oRng = Nothing
End Sub

Quote:
Originally Posted by vivka View Post
Hi! Unfortunately, you can't use a one-line regex to do this. Try the following, which will work on the selecton, not on the entire doc (it's my personal preference):
Code:
Sub Find_N_Embolden()

Dim rng As range
Dim FindTxt As String
 
    Application.ScreenUpdating = False
    Set rng = Selection.range
    
    FindTxt = "\@[A-Z]{1,}"
    Do
        With rng.Find
            .text = FindTxt
            .MatchWildcards = True
            .Forward = True
            .Wrap = wdFindStop
            .Execute
        End With
        If rng.Find.found And rng.InRange(Selection.range) Then
            If rng.Characters.Last.Next = "_" And _
                rng.Characters.Last.Next.Next Like "[0-9]" And _
                rng.Characters.Last.Next.Next.Next Like "[0-9]" And _
                Not rng.Characters.Last.Next.Next.Next.Next Like "[A-Za-z0-9]" Then
                rng.MoveEnd unit:=wdCharacter, count:=3
                rng.Font.Bold = True: GoTo lbl_Next
            ElseIf rng.Characters.Last.Next <> "_" Then
                rng.Font.Bold = True
            Else: GoTo lbl_Next
            End If
        Else
            Exit Do
        End If
lbl_Next:
        rng.Collapse wdCollapseEnd
     Loop
Application.ScreenUpdating = True
Set rng = Nothing
End Sub
__________________
Greg Maxey
Please visit my web site at http://www.gregmaxey.com/
Reply With Quote