Word vba string find

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 need to find a string in word document and replace it, with it’s sub string using vba code.

Deduplicator's user avatar

Deduplicator

44.3k7 gold badges65 silver badges115 bronze badges

asked Oct 23, 2015 at 2:11

Yari's user avatar

1

Use Mid method for the sub string purpose

Sub WordReplace()
    Dim sSample, rResult As String
    sSample = "hello world is my program"

    ' Sub String (replacing word)
    rResult = Mid(sSample, 1, 5)

    Set rRange = ActiveDocument.Content
    rRange.Find.Execute FindText:=sSample, ReplaceWith:=rResult, Replace:=wdReplaceAll
End Sub

Deduplicator's user avatar

Deduplicator

44.3k7 gold badges65 silver badges115 bronze badges

answered Oct 23, 2015 at 2:31

PASUMPON V N's user avatar

PASUMPON V NPASUMPON V N

1,1782 gold badges10 silver badges17 bronze badges

You can do something like this:

Sub Macro1()

    Dim TextToFind as String
    TextToFind = "test"

    Dim TextToReplace as String
    TextToReplace = "testing"

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = TextToFind
        .Replacement.Text = TextToReplace
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

This is directly pulled from Record Macro functionality within Word.

answered Oct 23, 2015 at 2:26

zedfoxus's user avatar

zedfoxuszedfoxus

34.2k5 gold badges62 silver badges61 bronze badges

RRS feed

  • Remove From My Forums
  • General discussion

  • Hi,

    I am new to VBA. My requirement is that VBA code should find the path in the word document., some of the paths are present in the word document.

    search criteria should start with \\ and end with .doc. Could anyone please help me out on how to provide the search criteria and is there any predefined methods present.

    Thanks in advance.

    Thanks,.

All replies

  • You’re doing a wildcard search for \\*.doc. In VBA, this is done as follows:

    Sub FindIt()
        Selection.HomeKey Unit:=wdStory
        With Selection.Find
            .ClearFormatting
            .Text = "\\*.doc"
            .Forward = True
            .Wrap = wdFindStop
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchAllWordForms = False
            .MatchSoundsLike = False
            .MatchWildcards = True
            .Execute
        End With
    End Sub

    or if you want to find all occurrences:

    Sub FindIt()
        Selection.HomeKey Unit:=wdStory
        With Selection.Find
            .ClearFormatting
            .Text = "\\*.doc"
            .Forward = True
            .Wrap = wdFindStop
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchAllWordForms = False
            .MatchSoundsLike = False
            .MatchWildcards = True
            Do While .Execute
                ' Do something here
            Loop
        End With
    End Sub


    Regards, Hans Vogelaar (http://www.eileenslounge.com)

  • Hi,

    Thanks for the reply.

    I getting the error when i use the code. please find below the changes i made

      doc.ActiveDocument.Application.Selection.HomeKey Unit:=wdStory

     
    With Selection.Find
            .ClearFormatting
            .Text = «\\*.doc»
            .Forward = True
            .Wrap = wdFindStop
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchAllWordForms = False
            .MatchSoundsLike = False
            .MatchWildcards = True
            .Execute
        End With

    Error :

    Wrong number of arguments or invalid property

    Thanks in advance.

  • Hi,

    my requirement is from excel VBA i will open the document and will search in that document  so only i have used

      doc.ActiveDocument.Application.Selection.HomeKey Unit:=wdStory

    Thanks

  • It might have helped had you said you were woking from Excel — it isn’t clear from the forum :(

    In this case you could use the following which will list the paths in column A of the activesheet. You can change that in the code where marked in bold

    Sub FindIt()
    Dim wdApp As Object
    Dim wdDoc As Object
    Dim oRng As Object
    Dim bStarted As Boolean
    Dim i As Integer
        On Error Resume Next
        Set wdApp = GetObject(, «Word.Application»)
        If Err Then
            Set wdApp = CreateObject(«Word.Application»)
            bStarted = True
        End If
        On Error GoTo 0
        ActiveWorkbook.Save
        ‘Note that opening the document in Word if it is already open does not cause an error. It just sets the value to that open document.
        Set wdDoc = wdApp.Documents.Open(«C:PathDocumentName.docx«)
        Set oRng = wdDoc.Range
        With oRng.Find
            i = 1
            Do While .Execute(FindText:=.Text = «\\*.doc», MatchWildCards:=True)
                Range(«A» & i) = oRng.Text
                oRng.collapse 0
                i = i + 1
            Loop
        End With
        wdDoc.Close 0
        If bStarted Then wdApp.Quit
        Set oRng = Nothing
        Set wdDoc = Nothing
        Set wdApp = Nothing
    End Sub


    Graham Mayor — Word MVP
    www.gmayor.com

    • Edited by

      Tuesday, December 30, 2014 7:25 AM

  • Hi,

    many Thanks for the reply

    oRng.Text is always returning 0.

    but i need the path to be written in the excel.

    Thanks.

  • Hi,

    My requirement is

    I have 100 + word documents.

    In that i have some paths hard coded in header,footer and in the content.

    I need to take all those paths and need to write in excel sheet.

    I know only the starting and the end letters of the document. starting is \\ and the end is .doc.

    I need the complete paht between these.

    Many thanks in advance.

    Thanks

  • Apologies, the line

    Do While .Execute(FindText:=.Text = «\\*.doc», MatchWildCards:=True)

    should read

    Do While .Execute(FindText:=»\\*.doc», MatchWildCards:=True)

    It will however only work for the document body. If the string is in a different story range you will have to loop through those story ranges e.g.

    Sub FindIt()
    Dim wdApp As Object
    Dim wdDoc As Object
    Dim oRng As Object
    Dim bStarted As Boolean
    Dim i As Integer
        On Error Resume Next
        Set wdApp = GetObject(, «Word.Application»)
        If Err Then
            Set wdApp = CreateObject(«Word.Application»)
            bStarted = True
        End If
        On Error GoTo 0
        ActiveWorkbook.Save
        Set wdDoc = wdApp.Documents.Open(«C:PathDocumentName.docx»)
        i = 1
        For Each oRng In wdDoc.StoryRanges
            With oRng.Find
                .MatchWildcards = True
                Do While .Execute(FindText:=»\\*.doc»)
                    Range(«A» & i) = oRng.Text
                    oRng.Collapse 0
                    i = i + 1
                Loop
            End With
            If oRng.StoryType <> wdMainTextStory Then
                While Not (oRng.NextStoryRange Is Nothing)
                    Set oRng = oRng.NextStoryRange
                    With oRng.Find
                        .MatchWildcards = True
                        Do While .Execute(FindText:=»\\*.doc»)
                            Range(«A» & i) = oRng.Text
                            oRng.Collapse 0
                            i = i + 1
                        Loop
                    End With
                Wend
            End If
        Next oRng
        wdDoc.Close 0
        If bStarted Then wdApp.Quit
        Set oRng = Nothing
        Set wdDoc = Nothing
        Set wdApp = Nothing
    End Sub


    Graham Mayor — Word MVP
    www.gmayor.com

    • Edited by
      Graham MayorMVP
      Tuesday, December 30, 2014 10:51 AM

  • Hi,

    Many Thanks for the reply. This helped me a lot. I have an another issue. When i try to convert my .dot files to .dotm the macros are not getting converted.  Any Idea please.

    Thanks

  • Hi,

    Thanks for the help.

    I there any way to find/search for the text in notepad through VBA.

    Thanks

  • You can open a text file in Word, edit it and then save it.


    Regards, Hans Vogelaar (http://www.eileenslounge.com)

  • Hi,

    I have a footer document which is kept seperately in the some other folder.

    I have thousands of files which refer to that footer document. I am planning to write an ini file to automate the usage.

    IS there any way to read the data from the another file to one file using Ini.

    Thanks.

Word VBA Find

This example is a simple word macro find the text “a”:

Sub SimpleFind()

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

Find and Replace

This simple macro will search for the word “their” and replace it with “there”:

Sub SimpleReplace()

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "their"
        .Replacement.Text = "there"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

Find and Replace Only in Selection

This VBA macro will find and replace text in a selection. It will also italicize the replaced text.

Sub ReplaceInSelection()
'replaces text JUST in selection . in adittion it makes replaced text italic
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "their"

        With .Replacement
            .Font.Italic = True
            .Text = "there"
        End With

        .Forward = True
        .Wrap = wdFindStop    'this prevents Word from continuing to the end of doc
        .Format = True 'we want to replace formatting of text as well
        .MatchCase = False
        .MatchWholeWord = True
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

This line of code prevents VBA from continuing to the end of the Word document:

.Wrap = wdFindStop    'this prevents Word from continuing to the end of doc

This line of code indicates to replace the formatting of the text as well:

.Format = True 'we want to replace formatting of text as well

Find and Replace Only In Range

Instead of replacing text throughout the entire document, or in a selection, we can tell VBA to find and replace only in range.  In this example we defined the range as the first paragraph:

Dim oRange As Range
Set oRange = ActiveDocument.Paragraphs(1).Range
Sub ReplaceInRange()
'replaces text JUST in range [in this example just in the first paragraph]
Dim oRange As Range
Set oRange = ActiveDocument.Paragraphs(1).Range
 oRange.Find.ClearFormatting
    oRange.Find.Replacement.ClearFormatting
    With oRange.Find
        .Text = "their"
        .Replacement.Text = "there"
        .Forward = True
        .Wrap = wdFindStop 'this prevent Word to continue to the end of doc
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    oRange.Find.Execute Replace:=wdReplaceAll
End Sub

Multiple objectsFind
Multiple objects

Represents the criteria for a find operation. The properties and methods of the Find object correspond to the options in the Find and Replace dialog box.

Using the Find Object

Use the Find property to return a Find object. The following example finds and selects the next occurrence of the word «hi.»

With Selection.Find
    .ClearFormatting
    .Text = "hi"
    .Execute Forward:=True
End With
		

The following example finds all occurrences of the word «hi» in the active document and replaces the word with «hello.»

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

Remarks

If you’ve gotten to the Find object from the Selection object, the selection is changed when text matching the find criteria is found. The following example selects the next occurrence of the word «blue.»

Selection.Find.Execute FindText:="blue", Forward:=True
		

If you’ve gotten to the Find object from the Range object, the selection isn’t changed when text matching the find criteria is found, but the Range object is redefined. The following example locates the first occurrence of the word «blue» in the active document. If «blue» is found in the document, myRange is redefined and bold formatting is applied to «blue.»

Set myRange = ActiveDocument.Content
myRange.Find.Execute FindText:="blue", Forward:=True
If myRange.Find.Found = True Then myRange.Bold = True
		

Like this post? Please share to your friends:
  • Word vba selection words
  • Word vba selection expand
  • Word vba selection end
  • Word vba selection copy
  • Word vba selection all