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]

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

Добрый день, готов с вами пообщаться по скайпу, когда вам будет удобно.
И высылаю тестовый пример, где все уже отражено.
Итак — есть вордовский документ, в котором в определенные места необходимо вставить текст, это чаще всего ФИО.
Или клише подписи, содержащее ФИО. Поэтому необходимо уметь вставить и текст и графический файл.
Я вставил в текст документа метки “!|” – это метка для вставки текста. (ФИО)
“(|” – это метка для вставки графического файла и это может быть клише содержащее ФИО.
Эти метки могут быть вставлены как просто в тексте документа, так и в поля таблиц, которые есть в документе.
Документ может содержать одну и более страниц. На каждой странице, кроме

последне

й нужно заполнять Нижний колонтитул. Ну для этого скорее всего можно просто сделать раздел и отдельно колонтитул для последней страницы, ну или реализовать кодом.
В тестовом примере показаны варианты Нижнего колонтитула: в Нижний колонтитул нужно уметь вставлять ТЕКСТ и графический файл (клише).
Кроме того, в нижним колонтитуле может быть таблица, поэтому нужно уметь вставлять ТЕКС и графический файл(клише) в
Поля этой таблицы. В высылаемом примере – это все визуализировано.

В сам документ вставлены таблицы, а в ячейки таблиц ПОЛЯ. Кроме того поля могут быть вставлены просто в текст документа.
Если документ закрыть паролем, то есть возможность вносить данные только в эти ПОЛЯ. Таблицы и поля заполняются вручную. Это номер документа и дата и еще какие-то могут быть данные. Это скорее пишу просто для информации, так как не нужно автоматизировать заполнение полей данными из других источников-файлов.
Я представляю сам процесс следующим образом – сделать вордовский файл, в нем вывести форму и несколько кнопок управления и запуска кода, который сейчас вырысовывается. И с этой формы запускать код для обработки файлов-документов, который будут лежать в определенной папке. С этим никаких трудностей нет. Сейчас нужно добиться прогресса с нижним колонтитулом.

В документах не нашел разрывы на разделы.

Все это в рамках борьбы с трудностями с наличием бумаги A4

I have an MS Word document including a table. I am trying to find and replace text via VBA using the following code:

If TextBox1.Text <> "" Then
    Options.DefaultHighlightColorIndex = wdNoHighlight
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    Selection.Find.Replacement.Highlight = True
    With Selection.Find
        .Text = "<Customer_Name>"
        .Replacement.Text = TextBox1.Text
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With

Selection.Find.ClearFormatting
    With Selection.Find.Font
    .Italic = True
    End With
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find.Replacement.Font
    .Italic = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    End If

This works fine for replacing all my content which is outside of the table. But it will not replace any of the content within the table.

kvantour's user avatar

kvantour

24.7k4 gold badges49 silver badges69 bronze badges

asked Sep 4, 2013 at 9:21

122user321's user avatar

If your goal is to perform replacements in the whole documents (it looks so from the code, but it is not explicit), I would suggest you use Document.Range instead of the Selection object. Using Document.Range will make sure everything is replaced, even inside tables.

Also, it is more transparent to the user, as the cursor (or selection) is not moved by the macro.

Sub Test()
  If TextBox1.Text <> "" Then
    Options.DefaultHighlightColorIndex = wdNoHighlight
    With ActiveDocument.Range.Find
      .Text = "<Customer_Name>"
      .Replacement.Text = TextBox1.Text
      .Replacement.ClearFormatting
      .Replacement.Font.Italic = False
      .Forward = True
      .Wrap = wdFindContinue
      .Format = False
      .MatchCase = False
      .MatchWholeWord = False
      .MatchWildcards = False
      .MatchSoundsLike = False
      .MatchAllWordForms = False
      .Execute Replace:=wdReplaceAll
    End With
  End If
End Sub

answered Sep 4, 2013 at 10:47

d-stroyer's user avatar

d-stroyerd-stroyer

2,6282 gold badges18 silver badges31 bronze badges

0

I have used the following code and it works like charm….. for all the occurances that are found in the document.

  stringReplaced = stringReplaced + "string to be searched"
For Each myStoryRange In ActiveDocument.StoryRanges
    With myStoryRange.Find
        .Text = "string to be searched"
        .Replacement.Text = "string to be replaced"
        .Wrap = wdFindContinue
        .ClearFormatting
        .Replacement.ClearFormatting
        .Replacement.Highlight = False
        .Execute Replace:=wdReplaceAll
    End With
Next myStoryRange  

Christopher Oezbek's user avatar

answered Jan 30, 2014 at 6:59

122user321's user avatar

122user321122user321

2211 gold badge4 silver badges13 bronze badges

Like this post? Please share to your friends:
  • Vba word поиск в строке
  • Vba word поиск в документе
  • Vba word подстановочные символы
  • Vba word печать документа
  • Vba word переход на новую строку