Visual basic word 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]

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
		

ВикиЧтение

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) введите искомый текст и

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

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

Понравилась статья? Поделить с друзьями:
  • Visual basic userform excel
  • Visual basic excel комментарии
  • Visual basic use in excel
  • Visual basic excel если не открыт файл то открыть
  • Visual basic excel диапазон