Home > front end >  Combine two separate Find and Format Macros into one
Combine two separate Find and Format Macros into one

Time:01-14

At the moment, I'm using two separate Macros to find a specific text in Word document and execute certain formatting commands (different for each search). For convenience, I want to somehow combine the two into one.

This is the first one:

With Selection.Find
.Text = "potatoes"
.Forward = True
.Wrap = wdFindContinue
.MatchWildcards = True
End With
'
Selection.Find.Execute
Selection.MoveRight Unit:=wdCharacter, Count:=3
Selection.InsertParagraphAfter
Repeat (3)
           

And the second one:

With Selection.Find
.Text = "tomatoes"
.Forward = True
.Wrap = wdFindContinue
.MatchWildcards = True
End With
'
Selection.Find.Execute
Selection.InsertParagraphAfter
Repeat (2)

In my case, only one of the searches will be true and will return a result.

So the idea is something like this ...

  • If you find "potatoes" do the first case formatting and don't search for "tomatoes".
  • If you find "tomatoes" do the second case formatting and don't search for "potatoes".
    • Or ... If you don't find "potatoes", search for "tomatoes" and do the second case formatting.

CodePudding user response:

Use:

Dim fnd As Boolean
fnd = False
Selection.HomeKey wdStory
Selection.Find.ClearFormatting
With Selection.Find
    Do While .Execute(FindText:="potatoes", Forward:=True, _
        MatchWildcards:=False, Wrap:=wdFindStop, MatchCase:=True) = True
        fnd = True
        Selection.MoveRight Unit:=wdCharacter, Count:=3
        Selection.InsertAfter vbCr
        Selection.Collapse wdCollapseEnd
    Loop
End With
If fnd = False Then
    Selection.HomeKey wdStory
    Selection.Find.ClearFormatting
    With Selection.Find
        Do While .Execute(FindText:="tomatoes", Forward:=True, _
        MatchWildcards:=False, Wrap:=wdFindStop, MatchCase:=True) = True
            Selection.InsertAfter vbCr
            Selection.Collapse wdCollapseEnd
        Loop
    End With
End If
  •  Tags:  
  • Related