Find next vba word

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Find.Execute method (Word)

vbawd10.chm162529724

vbawd10.chm162529724

word

Word.Find.Execute

3b607955-0e82-aa13-dad1-7a5069a57b9d

06/08/2017

medium

Find.Execute method (Word)

Runs the specified find operation. Returns True if the find operation is successful. Boolean.

Syntax

expression.Execute (FindText, MatchCase, MatchWholeWord, MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward, Wrap, Format, ReplaceWith, Replace, MatchKashida, MatchDiacritics, MatchAlefHamza, MatchControl)

expression Required. A variable that represents a Find object.

Parameters

Name Required/Optional Data type Description
FindText Optional Variant The text to be searched for. Use an empty string («») to search for formatting only. You can search for special characters by specifying appropriate character codes. For example, «^p» corresponds to a paragraph mark and «^t» corresponds to a tab character.
MatchCase Optional Variant True to specify that the find text be case-sensitive. Corresponds to the Match case check box in the Find and Replace dialog box (Edit menu).
MatchWholeWord Optional Variant True to have the find operation locate only entire words, not text that is part of a larger word. Corresponds to the Find whole words only check box in the Find and Replace dialog box.
MatchWildcards Optional Variant True to have the find text be a special search operator. Corresponds to the Use wildcards check box in the Find and Replace dialog box.
MatchSoundsLike Optional Variant True to have the find operation locate words that sound similar to the find text. Corresponds to the Sounds like check box in the Find and Replace dialog box.
MatchAllWordForms Optional Variant True to have the find operation locate all forms of the find text (for example, «sit» locates «sitting» and «sat»). Corresponds to the Find all word forms check box in the Find and Replace dialog box.
Forward Optional Variant True to search forward (toward the end of the document).
Wrap Optional Variant Controls what happens if the search begins at a point other than the beginning of the document and the end of the document is reached (or vice versa if Forward is set to False). This argument also controls what happens if there is a selection or range and the search text is not found in the selection or range. Can be one of the WdFindWrap constants.
Format Optional Variant True to have the find operation locate formatting in addition to, or instead of, the find text.
ReplaceWith Optional Variant The replacement text. To delete the text specified by the Find argument, use an empty string («»). You specify special characters and advanced search criteria just as you do for the Find argument. To specify a graphic object or other nontext item as the replacement, move the item to the Clipboard and specify «^c» for ReplaceWith.
Replace Optional Variant Specifies how many replacements are to be made: one, all, or none. Can be any WdReplace constant.
MatchKashida Optional Variant True if find operations match text with matching kashidas in an Arabic-language document. This argument may not be available to you, depending on the language support (U.S. English, for example) that you have selected or installed.
MatchDiacritics Optional Variant True if find operations match text with matching diacritics in a right-to-left language document. This argument may not be available to you, depending on the language support (U.S. English, for example) that you have selected or installed.
MatchAlefHamza Optional Variant True if find operations match text with matching alef hamzas in an Arabic-language document. This argument may not be available to you, depending on the language support (U.S. English, for example) that you have selected or installed.
MatchControl Optional Variant True if find operations match text with matching bidirectional control characters in a right-to-left language document. This argument may not be available to you, depending on the language support (U.S. English, for example) that you have selected or installed.
MatchPrefix Optional Variant True to match words beginning with the search string. Corresponds to the Match prefix check box in the Find and Replace dialog box.
MatchSuffix Optional Variant True to match words ending with the search string. Corresponds to the Match suffix check box in the Find and Replace dialog box.
MatchPhrase Optional Variant True ignores all white space and control characters between words.
IgnoreSpace Optional Variant True ignores all white space between words. Corresponds to the Ignore white-space characters check box in the Find and Replace dialog box.
IgnorePunct Optional Variant True ignores all punctuation characters between words. Corresponds to the Ignore punctuation check box in the Find and Replace dialog box.

Return value

Boolean

Remarks

If MatchWildcards is True, you can specify wildcard characters and other advanced search criteria for the FindText argument. For example, «*(ing)» finds any word that ends in «ing».

To search for a symbol character, type a caret (^), a zero (0), and then the symbol’s character code. For example, «^0151» corresponds to an em dash (—).

Unless otherwise specified, replacement text inherits the formatting of the text it replaces in the document. For example, if you replace the string «abc» with «xyz», occurrences of «abc» with bold formatting are replaced with the string «xyz» with bold formatting.

Also, if MatchCase is False, occurrences of the search text that are uppercase will be replaced with an uppercase version of the replacement text, regardless of the case of the replacement text. Using the previous example, occurrences of «ABC» are replaced with «XYZ».

Example

This example finds and selects the next occurrence of the word «library».

With Selection.Find 
    .ClearFormatting 
    .MatchWholeWord = True 
    .MatchCase = False 
    .Execute FindText:="library" 
End With

This example finds all occurrences of the word «hi» in the active document and replaces each occurrence with «hello».

Set myRange = ActiveDocument.Content 
myRange.Find.Execute FindText:="hi", _ 
    ReplaceWith:="hello", Replace:=wdReplaceAll

[!includeSupport and feedback]

I am trying to write some code that will search through all the stories including headers, footers, footnotes etc and then stop at each occurrence so the user can make a decision about it (it may or may not change), then click a button again to move to the next occurrence (like Word’s Find Next).

I am aware there is some pretty tricky code for performing a search and replace using the range object and I have that code working for another part of this project, but what I can’t do is make it search and stop at the selected text, then carry on looking in the different stories, it just stops at the end of the main document.

The code below looks as though it should work but even if the footnote for example has the text to be searched for, it is ignoring it. I have done a thorough search of this site and others and have found several examples for search and replace, but none for search and stop/select.

Any advice gratefully received — thank you.

Sub TestSelection()

    Dim rngStory As Range
    Dim docDocument As Document

    Set docDocument = ActiveDocument

    With docDocument
        For Each rngStory In .StoryRanges
           Select Case rngStory.StoryType
                Case 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
                    Debug.Print rngStory.StoryType

                    With Selection.Find
                    .ClearFormatting
                        .Text = "XYZ"
                        .Replacement.Text = ""
                        .Forward = True
                        .Wrap = wdFindStop
                        .Format = True
                        .MatchCase = False
                        .MatchWholeWord = False
                        .MatchWildcards = False
                        .MatchSoundsLike = False
                        .MatchAllWordForms = False
                    End With
                    Selection.Find.Execute

                        If Selection.Find.Found = True Then
                            Exit Sub
                        End If

                    End Select

        Next rngStory
    End With
End Sub

If You want to learn how to find a word or phrase in Word file and get its paragraph or word number stay here, You’ve come to the right place!

Find word and get its paragraph number from Word file

Some time ago I wrote about finding phrase in Word or .pdf files, but now we want something more…

Long story short

Recently, I got inspired by topic from StackOverflow, much about finding a word position in the Word file. When I saw this, I wanted to try my skills and create a tool, which finds a word or whole phrase in the Word file and returns its position – number of paragraph or word.

Background

To get things more complicated and be consistent with my website name I wanted to create it in Excel.

Imagine, that in column “A” You store the words, in column “B” locations of Word files You want to search for and in column “C” macro returns words position.

First things first

At the beginning we need to declare variables, which will stand for Word variables: Word application, Word document and Word document ranges.

Dim wd As Word.Application
Dim wdDoc As Word.Document
Dim rng As Word.Range, rng2 As Word.Range, rParagraphs As Word.Range

Get the search info

After all needed declarations let’s get search phrase srcwd and Word file localization wdfile.

Dim txt As String, wdfile As String, srcwd As String
Dim CurPos As Long, GetParNum As Long

wdfile = ThisWorkbook.Sheets(1).Range("B1")
srcwd = ThisWorkbook.Sheets(1).Range("A1")

Create Word objects

To open Word file from Excel, You need to create Word application object and set its document to next variable.

Set wd = CreateObject("Word.Application")
Set wdDoc = wd.Documents.Open(wdfile)

Assign content

Later on set all Word file content range to rng.

Set rng = wdDoc.Content

Text of this document can be taken out from this range variable.

We got opened target Word file and all of its text assigned to variable. Now we can start to seek for chosen phrase and get its paragraph or word number. To do it we will use function .Find

With rng.Find
    .Text = srcwd
    .Forward = True
    .Execute
End With

This will find and select the next occurrence (.Forward = True) of the searched word (srcwd).

Remember about the .Execute, because without it won’t work at all, regardless of parameters number!

Get paragraph number

Finally, we can get the paragraph or word number!

First, we need to set the cursor in the end of the found word. In other case macro will not count the paragraph, which the word is in it!

CurPos = rng.Words(1).End

Next let’s set the range from the beginning of the document to the position of cursor.

Set rParagraphs = wdDoc.Range(Start:=0, End:=CurPos)

Thanks to that we got range containing everything up to searched word and now all we have to do is count the number of paragraphs!

GetParNum = rParagraphs.Paragraphs.Count

If You want to know what is its word number just change Paragraphs to Words.

GetWordsNum = rParagraphs.Words.Count

Whole code

There is one matter left to do in the end of our code. We have to save somewhere the paragraph number. Let’s write it down to the column C, after that close the document with no changes and quit Word application (see end of below code).

Option Explicit

Sub src4Word()

Dim wd As Word.Application
Dim wdDoc As Word.Document
Dim rng As Word.Range, rng2 As Word.Range
Dim rParagraphs As Word.Range
Dim txt As String, wdfile As String, srcwd As String
Dim CurPos As Long, GetParNum As Long

wdfile = ThisWorkbook.Sheets(1).Range("B1")
srcwd = ThisWorkbook.Sheets(1).Range("A1")

Set wd = CreateObject("Word.Application")
Set wdDoc = wd.Documents.Open(wdfile)
Set rng = wdDoc.Content

With rng.Find
    .Text = srcwd
    .Forward = True
    .Execute
End With

CurPos = rng.Words(1).End
Set rParagraphs = wdDoc.Range(Start:=0, End:=CurPos)
GetParNum = rParagraphs.Paragraphs.Count

ThisWorkbook.Sheets(1).Range("C1") = GetParNum
wdDoc.Close 0
wd.Quit

End Sub

Summary

Now You know how to find a word or phrase in Word file and get its paragraph or even its word number! It looks so easy! You can use this code to the other variations, for example to get whole text of the searched word paragraph. The choice is yours!

I’m very advanced in VBA, Excel, also easily linking VBA with other Office applications (e.g. PowerPoint) and external applications (e.g. SAP). I take part also in RPA processes (WebQuery, DataCache, IBM Access Client Solutions) where I can also use my SQL basic skillset. I’m trying now to widen my knowledge into TypeScript/JavaScript direction.
View all posts by Tomasz Płociński

Понравилась статья? Поделить с друзьями:
  • Find new words from one word
  • Find named range in excel
  • Find name of picture in word
  • Find name meaning in one word
  • Find my word mp3