In Word How Do You Capture Found/Not Found in IF Statement in Visual Basic?

In Word's Visual Basic macro, I want to do a Find for a unique text and then highlight.  I'm a novice and could not find how to show in an IF statement, IF the text is found, progress with the statements that highlight the text and if nothing is found, don't.  Thanks.
LVL 2
rvfowler2Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

GrahamSkanRetiredCommented:
The .Execute method returns True if the .Find is successful.

But your requirement is a little confusing. You can Highlight each instance of the text without stopping

Sub HighLightFoundText(doc As Document, strText As String)
    Dim rng As Range
    
    Set rng = doc.Range
    rng.HighlightColorIndex = wdYellow
    With rng.Find
        .Text = strText
        .Replacement.Highlight = True
        .Execute Replace:=wdReplaceAll
    End With
End Sub

Open in new window

0
rvfowler2Author Commented:
Yes, sorry, I wasn't clear.  After I find the text, I need to select the paragraph before highlighting it (paragraph text is slightly variable).  Thus, so far I have:

    CommandBars("Navigation").Visible = False
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "XX.^tREA"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
    Selection.MoveLeft Unit:=wdCharacter, Count:=1
    Selection.MoveDown Unit:=wdParagraph, Count:=1, Extend:=wdExtend
    Options.DefaultHighlightColorIndex = wdYellow
    Selection.Range.HighlightColorIndex = wdYellow
0
rvfowler2Author Commented:
Used wildcards and special characters to capture paragraph, but now I get an error when using your steps.  I got an error in the Dim as I'd already dimmed rng, so changed it to rng2, but now I'm getting on error on the Set step of Run-time error 424, Object required.

    Dim rng2 As Range
   
    Set rng2 = doc.Range
    rng.HighlightColorIndex = wdYellow
    With rng2.Find
        .Text = "XX.^tREA*emergency."
        .Replacement.Highlight = True
        .Execute Replace:=wdReplaceAll
    End With
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

GrahamSkanRetiredCommented:
Your latest problem seems to be caused by using two different variables for the Range object.

It will help you to make sure that you have  Option Explicit at the top of the module. That can be set automatically with any new modules after ticking 'Require Variable Declaration' in Tools>Options
0
rvfowler2Author Commented:
The one I showed you above had a typo, but fixed it and still didn't work.  Then I went back to the original way you suggested as follows are obtained the error, "duplicate declaration in current scope."  Then I try to comment out the dim and obtained "object not defined."  Tried every possible combo and still not working.

    Dim rng As Range
   
    Set rng = doc.Range
    rng.HighlightColorIndex = wdYellow
    With rng.Find
        .Text = "XX.^tREA*emergency."
        .Replacement.Highlight = True
        .Execute Replace:=wdReplaceAll
    End With
0
rvfowler2Author Commented:
Marked Option explicit as you said and still receive "duplicate declaration in current scope."
0
GrahamSkanRetiredCommented:
Option Explicit make sure that you haven't missed a Dim for a variable and that you haven't misspelt one in use.

A duplicate Duplicate Declaration error is usually a matter of having something like "Dim rng As Range" twice in the same procedure
0
rvfowler2Author Commented:
By procedure, if you mean the entire sub, I tried to take care of it by commenting it out.  However, I get one error when I include it and another when I comment it out.  Doesn't make any sense.  Below is the latest.  Will keep playing with it.  

    Dim rng As Range
   
    Set rng = doc.Range
    rng.HighlightColorIndex = wdYellow
    With rng.Find
        .Text = "XX.^tREA*emergency."
        .Replacement.Highlight = True
        .Execute Replace:=wdReplaceAll
    End With
0
GrahamSkanRetiredCommented:
It doen't make sense to me either. It might be worth closing word and re=opening it - perhaps re-booting the system at the same time
0
rvfowler2Author Commented:
Tried running your code on its own as a separate Word macro.  Something is not matching between your code and my Word macro, which I thought was in Visual Basic.  The only change I made below was to add in the text I'm looking for.  However, it doesn't show in the initial macro viewer and thus doesn't seem to even recognize this as a macro and won't run.  Yet, I have a Sub macro2() that shows up and runs fine.  Note that I have Microsoft Office Professional Plus 2016.

Sub HighLightFoundText (doc As Document, strText As String)
    Dim rng As Range
   
    Set rng = doc.Range
    rng.HighlightColorIndex = wdYellow
    With rng.Find
        .Text = "XX.^tREA*emergency."
        .Replacement.Highlight = True
        .Execute Replace:=wdReplaceAll
    End With

End Sub
0
GrahamSkanRetiredCommented:
I guess you are talking about the 'Macros' button in the Developer tab. I had forgotten about that. It only shows code that will run as it stands (i.e. doesn't need to be called with arguments). I never use it while developing, because it is likely that the VBA IDE is open. Just put the cursor somewhere in the procedure that you want to run and press F5 or click the Run button.

If you have a problem to report, we need to know the details.
0
rvfowler2Author Commented:
Already ran it all day yesterday with various iterations without the Sub and end Sub notations as follows and obtained the error, "duplicate declaration in current scope."  Then I try to comment out the dim and obtained "object not defined."  Tried every possible combo and still not working.

    Dim rng As Range
   
    Set rng = doc.Range
    rng.HighlightColorIndex = wdYellow
    With rng.Find
        .Text = "XX.^tREA*emergency."
        .Replacement.Highlight = True
        .Execute Replace:=wdReplaceAll
    End With
0
rvfowler2Author Commented:
Finally, figured out a way that works (see below).  For some reason, it seems your Set rng = doc.Range doesn't work.

Sub HighlightFoundText2()

    With ActiveDocument.Range.Find
        .Text = "XX.^tREA*emergency."
        .Replacement.Highlight = True
        .MatchWildcards = True
        .Execute Replace:=wdReplaceAll
    End With

End Sub
0
rvfowler2Author Commented:
See above.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
GrahamSkanRetiredCommented:
My original code which was used for illustration purposes required calling from some other code which would supply the arguments (for 'doc' and 'strText'). I couldn't see what you were actually doing which is why I said that we need to know the details.
0
rvfowler2Author Commented:
Thanks, Graham.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.