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]

Цитата
Сообщение от Lupus
Посмотреть сообщение

что за объект такой Content и чем он отличается от Range ?

Вообще документ состоит из нескольких частей (я все не могу вспомнить):

  1. колонтитулы,
  2. сноски,
  3. надписи,
  4. собственно документ.

Content — это и есть собственно документ.

Что касается Range, то надо различать:

  1. свойство Range;
  2. метод Range.

Метод Range есть только у объекта Document (Activedocument) и Shapes (про Shapes не знаю, ни разу не использовал). С помощью метода можно задавать определённый диапазон, например:

Visual Basic
1
Activedocument.Range(Start:=0, End:=10)

что означает диапазон документа от начала и до десятого знака включительно. Если ничего не указано:

Visual Basic
1
Activedocument.Range

то означает — весь документ. Т.е. в данном случае Range, то же самое, что Content (хотя может разница и есть в чём-то).

В остальных случаях (когда Range не относится к Documents (Activedocument), Range является свойством и с помощью него узнают

порядковый номер символа

(но там путаница большая, если используются в документе кроме символов другие объекты (например, рисунки)) и

содержимое объекта

(например, абзаца):

Visual Basic
1
2
3
4
Sub P3()
'Определение номера символа, когда начинается абзац.
MsgBox ActiveDocument.Paragraphs(1).Range.Start
End Sub
Visual Basic
1
2
3
4
Sub P4()
'Получаем содержимое абзаца.
MsgBox ActiveDocument.Paragraphs(1).Range
End Sub

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

ВикиЧтение

VBA для чайников
Каммингс Стив

Поиск и замена текста с помощью VBA в Word

Хотя это звучит и несколько необычно, но Find — это объект Word VBA. Объекты Find принадлежат диапазонам и выделенным областям. Для обнаружения или форматирования текста с помощью объекта Find вам потребуется выполнить следующие действия.

1. Получите доступ к объекту Find для определенного диапазона или выделенной области. Если вам необходимо просмотреть целый документ, используйте свойство Content объекта Document для получения доступа к соответствующему диапазону, как показано ниже:

ActiveDocument.Content.Find

2. Определить свойства объекта Find в соответствии с тем, что же вы ищете и как именно вы хотите проводить поиск.

3. Вызвать метод Execute объекта Find. Соответствующий пример приведен ниже:

With OpenRange.Find

.Clear Formatting

.Text = «pogosticks»

.Execute

End With

Для свойств, значения которых явно вы задать не можете, объект Find выбирает параметры, использованные последними или те, которые в настоящий момент заданы в диалоговом окне Найти и заменить программы Word. Именно по этой причине вам всегда следует включать метод Clear Formatting перед началом нового поиска- он позволяет убрать все ранее определенные для проведения поиска параметры форматирования.

Работа с найденным текстом

Основная работа метода Execute — обнаружение первого экземпляра искомого текста или форматирования в указанном диапазоне или выделенной области. После выполнения этого метода вам прежде всего следует определить, было ли найдено то, что вы ищете. Для подобной проверки используйте свойство Found объекта Find совместно с инструкцией If…Then, как показано на примере следующей заготовки программного кода:

If .Found = True Then

(выполнение определенных действий с найденным текстом)

Else

(отображение соответствующего сообщения)

End If

Если метол Execute нашел необходимый текст, исходный диапазон или выделенная область переопределяются таким образом, чтобы содержать найденный текст. Это очень важный момент, поскольку это означает, что вы можете работать с найденным текстом посредством свойств и методов исходного объекта. В следующем примере, представляющем собой расширенный вариант первого фрагмента кода из настоящего раздела, инструкция .Parent. Italic = True обращается к родительскому объекту по отношению к объекту Find, т.е. диапазону OpenRange. При выполнении этой инструкции диапазон OpenRange теперь содержит только найденный фрагмент текста, так как только в нем предусмотрено форматирование курсивом:

With OpenRange.Find

.СlearFormatting

.Text = «pogosticks»

If .Found = True Then

.Parent.Italic = True

Else

MsgBox «No pogosticks found.»

End If

End with

Объект Reolacement принадлежит (а значит, является его свойством) объекту Find. При написании кода для операции поиска и замены вам следует задать свойства и выполнить методы объекта Replacement.

Следующий фрагмент кода заменяет все экземпляры фразы pogosticks словом skateboards. Выделенная область изменяется при выполнении критерия поиска, поскольку доступ к объекту Find осуществляется через объект Selection:

With ActiveDocument.Content.Find

.ClearFormatting

.Text = «pogosticks»

With .Replacement

.ClearFormatting

.Text == «skateboards»

End With

.Execute Replace := wdReplaceAll

End With

Обратите внимание на то, что метод Execute может использовать аргумент Replace, предназначенный для контроля за тем, будут ли заменены все обнаруженные экземпляры обнаруженного фрагмента текста, или только первый.

Читайте также

Поиск и замена данных

Поиск и замена данных
В программе HtmlPad реализована возможность быстрого поиска данных. Этот механизм полезно использовать при работе с большими программными кодами или с большими объемами данных, поскольку поиск требуемой информации вручную (например, путем просмотра

Поиск и замена данных

Поиск и замена данных
В программе Extra Hide Studio имеется удобный механизм для быстрого поиска и замены данных. Эта возможность особенно актуальна при работе с большими исходными кодами, поскольку поиск данных путем просмотра всего кода может занять слишком много времени, и к

Глава 2 Подготовка текста в Microsoft Word

Глава 2 Подготовка текста в Microsoft Word
• Общие сведения о Word 2007• Основные правила форматирования• Вставка стандартных блоков в документ• Нумерация страниц и колонтитулы• Проверка правописания, поиск синонимов, перевод слов• Сноски и закладки• Настройка параметров

3.1. Поиск и замена фрагментов

3.1. Поиск и замена фрагментов
Текстовый редактор успешно справляется с поиском и заменой текста в отдельном файле. Однако, если это же нужно сделать сразу в нескольких файлах, лучше воспользоваться специальными программами, с помощью которых можно заменить фрагменты

Поиск и замена текста

Поиск и замена текста
В текстовом редакторе Adobe InDesign можно воспользоваться полезнейшей функцией поиска и замены фрагментов текста. Причем, раз мы имеем дело с программой верстки, найденные фрагменты можно не только заменить другими, но и оформить каким-то образом –

Поиск и замена форматирования

Поиск и замена форматирования
Для поиска текста с определенным форматированием используйте свойства объекта Find, касающиеся форматирования. Они идентичны свойствам, используемым при работе с форматированием диапазона или выделенной области, как я уже отмечал в разделе

Автоматический поиск и замена данных

Автоматический поиск и замена данных
В процессе работы иногда возникает необходимость быстро найти те или иные данные (слово, текстовый фрагмент и т. д.) либо заменить одни данные на другие. Для решения такой задачи в Publisher 2007 реализован механизм автоматического поиска и

Поиск и замена

Поиск и замена
В новой версии Excel был полностью изменен пользовательский интерфейс и расширены функциональные возможности средства Найти и заменить. Теперь можно с помощью одной операции производить поиск и замену по всем листам книги, повторно выполнять запросы поиска

Поиск и замена символов

Поиск и замена символов
Иногда при подготовке электронных документов возникает задача поиска определенных текстовых фрагментов. Например, вы забыли номер чертежа, но помните, что в его названии или дополнительной информации, размещенной на чертеже, содержится

Глава 2 Подготовка текста в Microsoft Word

Глава 2
Подготовка текста в Microsoft Word
Microsoft Word – пожалуй, самая популярная на сегодняшний день программа, предназначенная для работы с текстами. Продукт компании Microsoft обладает всеми необходимыми возможностями, связанными с набором и правкой текстов любой сложности.

5.7. Поиск и замена

5.7. Поиск и замена
В документе можно производить автоматический поиск текста и замену его другим.Поиск и замена ведется по введенному образцу. Если в качестве образца указано слово «ход», то компьютер найдет и слово «пароход», если предварительно не поставить условие, что

13.3.4. Поиск и замена текста

13.3.4. Поиск и замена текста
Как вы уже догадались, окно Найти и заменить используется не только для перехода на нужную страницу. Вкладка Найти используется для поиска текста. Для быстрого доступа к этой вкладке нажмите Ctrl+F или выберите команду меню Правка, Найти. Нажмите

Поиск и замена

Поиск и замена
Для поиска в тексте документа нужного слова или сочетания символов служит окно поиска и замены (рис. 9.19), которое открывается нажатием Ctrl+F. Если надо, чтобы оно сразу открылось как окно замены, используйте сочетание Ctrl+H.

Рис. 9.19. Окно поиска и замены.Для

Поиск и замена фрагментов фильма

Поиск и замена фрагментов фильма
Очень часто бывает нужно найти в изображении или фильме Flash какой-либо текст и, возможно, заменить его на другой. Специально для этого Flash, как и многие другие программы, работающие с документами, предлагает богатые возможности по поиску и

Поиск и замена текста

Поиск и замена текста
Поиск определенного слова или фразы в большом документе является довольно непростой задачей, но ее можно значительно упростить, если воспользоваться командой Главная ? Редактирование ? Найти. В появившемся окне (рис. 5.20) введите искомый текст и

Поиск и замена данных

Поиск и замена данных
По современным меркам таблица с несколькими тысячами записей считается небольшой, но даже в такой таблице ручной поиск или отбор нужной информации может занять продолжительное время. С помощью средств поиска, сортировки и фильтрации нужные данные

Понравилась статья? Поделить с друзьями:
  • Vba word подстановочные символы
  • Vba word печать документа
  • Vba word переход на новую строку
  • Vba word перенос таблиц в word
  • Vba word переместить курсор