Jordan
Jordan

Reputation: 37

Use VBA to check for text before taking action without selecting text

I want to only take action if the document contains a specific word/phrase. The first part of my macro inserts texts and then I want to check for a word to see if the macro continues. If the document already has the word I want the cursor to be at the end of the inserted text.

I don't want the specific word selected when the macro runs. Below is what I have so far but it selects the word.

Selection.HomeKey Unit:wdStory
With Selection.Find
  .ClearFormatting
  .Text = "Hello"
End With

If Not Selection.Find.Execute Then
    Action
End If

Upvotes: 1

Views: 315

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25663

There's actually a quite elegant and easy way to do this. Instead of using Selection do the Find using a Range. Think of a Range like an invisible selection, but with two major advantages:

  • The selection doesn't change. Code is faster; the screen doesn't flicker
  • Code can use as many Range objects as necessary; there can only ever be one Selection

For example:

Dim rngFind as Word.Range
Dim found as Boolean

Set rngFind = ActiveDocument.Content

With rngFind.Find
  .ClearFormatting
  .Text = "Hello"
  found = .Execute
End With

If Not found Then
    'Actions here
End If

Upvotes: 2

Related Questions