Word range find execute

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]

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

1 18.03.2018 13:53:15

  • o5andrey
  • сержант
  • Неактивен
  • Откуда: Братск, Иркутская область
  • Зарегистрирован: 18.03.2018
  • Сообщений: 29

Тема: Как работает .Range.Find.Execute?

Здравствуйте. Интересует следующий вопрос.
Почему

Set p1 = Selection.Paragraphs(2).Range
p1.Find.Text = "110"
p1.Find.Replacement.Text = "!!!"
p1.Find.Execute Replace:=wdReplaceOne

работает, а

Selection.Paragraphs(2).Range.Find.Text = "110"
Selection.Paragraphs(2).Range.Find.Replacement.Text = "!!!"
Selection.Paragraphs(2).Range.Find.Execute Replace:=wdReplaceOne

нет. Спасибо.

2 Ответ от Fck_This 19.03.2018 08:58:27

  • Как работает .Range.Find.Execute?
  • Fck_This
  • генерал-полковник
  • Неактивен
  • Откуда: Минск, Беларусь
  • Зарегистрирован: 13.07.2016
  • Сообщений: 648
  • Поблагодарили: 97

Re: Как работает .Range.Find.Execute?

o5andrey пишет:

Здравствуйте. Интересует следующий вопрос.
Почему

Set p1 = Selection.Paragraphs(2).Range
p1.Find.Text = "110"
p1.Find.Replacement.Text = "!!!"
p1.Find.Execute Replace:=wdReplaceOne

работает, а

Selection.Paragraphs(2).Range.Find.Text = "110"
Selection.Paragraphs(2).Range.Find.Replacement.Text = "!!!"
Selection.Paragraphs(2).Range.Find.Execute Replace:=wdReplaceOne

нет. Спасибо.

Всё работает
Ваш вид проще сделать так

With Selection.Paragraphs(2).Range.Find
    .Text = "110"
    .Replacement.Text = "!!!"
    .Execute Replace:=wdReplaceOne
End With

А ещё компактнее вот так

Selection.Paragraphs(2).Range.Find.Execute FindText:="110", ReplaceWith:="!!!", Replace:=wdReplaceOne

А вот так будет верняк:

If Selection.Range.Paragraphs.Count >= 2 Then
Selection.Paragraphs(2).Range.Find.Execute FindText:="110", ReplaceWith:="!!!", Replace:=wdReplaceOne
End If

Скорее всего у вас там не было двух предложений или текст был заменён.

Спасибо можно перевести на WebMoney-кошелёк R378231864568 или на Яндекс-деньги 410015093172871

3 Ответ от o5andrey 19.03.2018 09:08:39

  • o5andrey
  • сержант
  • Неактивен
  • Откуда: Братск, Иркутская область
  • Зарегистрирован: 18.03.2018
  • Сообщений: 29

Re: Как работает .Range.Find.Execute?

Скорее всего у вас там не было двух предложений или текст был заменён.

А вот и нет, мой второй случай не работает. Вы проверили, у вас идёт?

4 Ответ от o5andrey 19.03.2018 09:47:35

  • o5andrey
  • сержант
  • Неактивен
  • Откуда: Братск, Иркутская область
  • Зарегистрирован: 18.03.2018
  • Сообщений: 29

Re: Как работает .Range.Find.Execute?

Вечером проверю ещё раз.

5 Ответ от Fck_This 19.03.2018 09:48:53

  • Как работает .Range.Find.Execute?
  • Fck_This
  • генерал-полковник
  • Неактивен
  • Откуда: Минск, Беларусь
  • Зарегистрирован: 13.07.2016
  • Сообщений: 648
  • Поблагодарили: 97

Re: Как работает .Range.Find.Execute?

o5andrey пишет:

Вечером проверю ещё раз.

Да, проверил

Спасибо можно перевести на WebMoney-кошелёк R378231864568 или на Яндекс-деньги 410015093172871

6 Ответ от o5andrey 19.03.2018 15:14:52

  • o5andrey
  • сержант
  • Неактивен
  • Откуда: Братск, Иркутская область
  • Зарегистрирован: 18.03.2018
  • Сообщений: 29

Re: Как работает .Range.Find.Execute?

Я проверил на другом ПК

Sub Test2()
Selection.Paragraphs(2).Range.Find.Text = "110"
Selection.Paragraphs(2).Range.Find.Replacement.Text = "!!!"
Selection.Paragraphs(2).Range.Find.Execute Replace:=wdReplaceOne
End Sub

Sub Test3()
Set a = Selection.Paragraphs(2).Range
a.Find.Text = "110"
a.Find.Replacement.Text = "!!!"
a.Find.Execute Replace:=wdReplaceOne
End Sub

Test2 не работает.

Post’s attachments

110.docm 15.4 Кб, файл не был скачан. 

You don’t have the permssions to download the attachments of this post.

7 Ответ от o5andrey 20.03.2018 09:13:05

  • o5andrey
  • сержант
  • Неактивен
  • Откуда: Братск, Иркутская область
  • Зарегистрирован: 18.03.2018
  • Сообщений: 29

Re: Как работает .Range.Find.Execute?

С «With — End With» тоже работает, а вот без всяких свёрток не работает. В общем, я объяснил это себе как глюк объекта и метода Find.Execute; как глюк Word.

8 Ответ от Вождь 20.03.2018 09:23:34

  • Как работает .Range.Find.Execute?
  • Вождь
  • Модератор
  • Неактивен
  • Зарегистрирован: 07.01.2010
  • Сообщений: 745
  • Поблагодарили: 181
  • За сообщение: 1

Re: Как работает .Range.Find.Execute?

Блин, ребята, вы синтаксис VBA то сначала выучите smile
Целая дискуссия из-за элментарной ошибки!

Каждый раз, когда вы пишите:

Selection.Paragraphs(2).Range

Создается новая переменная, по типу With.
Которая убивается, после выполнения команды smile

Макросы под заказ и готовый пакет — mtdmacro.ru

9 Ответ от Fck_This 20.03.2018 09:33:37

  • Как работает .Range.Find.Execute?
  • Fck_This
  • генерал-полковник
  • Неактивен
  • Откуда: Минск, Беларусь
  • Зарегистрирован: 13.07.2016
  • Сообщений: 648
  • Поблагодарили: 97

Re: Как работает .Range.Find.Execute?

Вождь пишет:

Блин, ребята, вы синтаксис VBA то сначала выучите smile
Целая дискуссия из-за элментарной ошибки!

Каждый раз, когда вы пишите:

Selection.Paragraphs(2).Range

Создается новая переменная, по типу With.
Которая убивается, после выполнения команды smile

Спасибо. На счёт повторного использования Selection.paragraph(2).Range не видел или не обратил внимания на подобное. Разумеется, следует пользоваться оригинальными конструкциями.

Спасибо можно перевести на WebMoney-кошелёк R378231864568 или на Яндекс-деньги 410015093172871

10 Ответ от o5andrey 20.03.2018 16:17:41

  • o5andrey
  • сержант
  • Неактивен
  • Откуда: Братск, Иркутская область
  • Зарегистрирован: 18.03.2018
  • Сообщений: 29

Re: Как работает .Range.Find.Execute?

Рад что вам всё ясно. Но будьте любезны, поясните мне.

Создается новая переменная, по типу With.

Это как?

11 Ответ от Вождь 21.03.2018 09:26:14

  • Как работает .Range.Find.Execute?
  • Вождь
  • Модератор
  • Неактивен
  • Зарегистрирован: 07.01.2010
  • Сообщений: 745
  • Поблагодарили: 181

Re: Как работает .Range.Find.Execute?

Поясню, так как это вопрос почему-то оказался не очевидным форумчанам smile

Определение Range то читали? Range – представляет какую-то непрерывную область документа. То бишь, главное запомнить, что Range всегда относится к документу. Не к Selection, Paragraph или чему другому, а именно к документу. Так же, Range – это объект (читаем что это такое и как с ними работать).

Здесь свойство Range вернуло вам область документа, соответствующую второму выбранному абзацу:

Selection.Paragraphs(2).Range

Не ссылку на объект, а именно объект. Если бы вы запомнили этот объект Range, то работали бы с ним и дальше. Например:

Set R = Selection.Paragraphs(2).Range

Вы не сделали этого, и объект был удален сразу, после выполнения строки кода:

Selection.Paragraphs(2).Range.Find.Text = "110"

Следующий вызов вернул еще один новый объект Range. И так далее.

Если ничего не поняли, значит изучение даже основ VBA вы посчитали лишним, а сразу решили попробовать smile Почитайте какую книжку с примерами, можно и справку глянуть. Главное — читать с начала и подряд. Изучая основы (чего бы то ни было) бессистемным образом (на форумах) люди гробят свое и чужое время. Как говорится: У семи нянек дитя без глазу smile

Макросы под заказ и готовый пакет — mtdmacro.ru

12 Ответ от Fck_This 21.03.2018 09:50:59

  • Как работает .Range.Find.Execute?
  • Fck_This
  • генерал-полковник
  • Неактивен
  • Откуда: Минск, Беларусь
  • Зарегистрирован: 13.07.2016
  • Сообщений: 648
  • Поблагодарили: 97

Re: Как работает .Range.Find.Execute?

Вождь пишет:

Если ничего не поняли, значит изучение даже основ VBA вы посчитали лишним, а сразу решили попробовать smile Почитайте какую книжку с примерами, можно и справку глянуть. Главное — читать с начала и подряд. Изучая основы (чего бы то ни было) бессистемным образом (на форумах) люди гробят свое и чужое время. Как говорится: У семи нянек дитя без глазу smile

Фе, какой вы сноб. Читать сначала и подряд — ужасно скучно. Считаю, что для VBA достаточно читать справку при составлении кода, но читать стоит внимательно.

Спасибо можно перевести на WebMoney-кошелёк R378231864568 или на Яндекс-деньги 410015093172871

13 Ответ от Вождь 21.03.2018 10:22:25

  • Как работает .Range.Find.Execute?
  • Вождь
  • Модератор
  • Неактивен
  • Зарегистрирован: 07.01.2010
  • Сообщений: 745
  • Поблагодарили: 181

Re: Как работает .Range.Find.Execute?

Fck_This пишет:

…вы сноб…

Да, зануда еще тот smile Программеров других не бывает, все строго по алгоритму smile

Макросы под заказ и готовый пакет — mtdmacro.ru

14 Ответ от o5andrey 01.04.2018 09:33:42

  • o5andrey
  • сержант
  • Неактивен
  • Откуда: Братск, Иркутская область
  • Зарегистрирован: 18.03.2018
  • Сообщений: 29

Re: Как работает .Range.Find.Execute?

Здравствуйте. Подскажите пожалуйста как расширить диапазон на одно слово.
Set r1 = Selection.Paragraphs(1).Range

r1.Find.Text = ChrW(34)
r1.Find.Execute 
If r1.Find.Found = True Then
    r1.Expand Unit:=wdWord
    MsgBox (r1)
End If

В окошке только одна кавычка.

15 Ответ от Вождь 01.04.2018 09:51:53

  • Как работает .Range.Find.Execute?
  • Вождь
  • Модератор
  • Неактивен
  • Зарегистрирован: 07.01.2010
  • Сообщений: 745
  • Поблагодарили: 181

Re: Как работает .Range.Find.Execute?

o5andrey пишет:

…расширить диапазон на одно слово…

Например так:

R1.Find.Text = ChrW(34)
R1.Find.Execute
If R1.Find.Found = True Then
    R1.Expand Unit:=wdWord
    R1.MoveStart wdWord, wdBackward
    R1.MoveEnd wdWord, wdForward
    MsgBox (R1)
End If

Макросы под заказ и готовый пакет — mtdmacro.ru

16 Ответ от o5andrey 01.04.2018 11:46:56

  • o5andrey
  • сержант
  • Неактивен
  • Откуда: Братск, Иркутская область
  • Зарегистрирован: 18.03.2018
  • Сообщений: 29

Re: Как работает .Range.Find.Execute?

Не выходит. Так берётся весь текст: от кавычки до начала и до конца. Мне нужно чтобы в окошке появилось слово, которое в кавычках.

17 Ответ от o5andrey 01.04.2018 11:51:50

  • o5andrey
  • сержант
  • Неактивен
  • Откуда: Братск, Иркутская область
  • Зарегистрирован: 18.03.2018
  • Сообщений: 29

Re: Как работает .Range.Find.Execute?

В справке есть примеры:

Set myRange = ActiveDocument.Words(1)
myRange.Expand Unit:=wdParagraph
Set Range1 = ActiveDocument.Paragraphs(1).Range
With Range1
    .Collapse Direction:=wdCollapseStart
    .Move Unit:=wdParagraph, Count:=3
    .Select
End With

Но почему-то у меня приведённое аналогичное не проходит…

18 Ответ от o5andrey 01.04.2018 12:20:55

  • o5andrey
  • сержант
  • Неактивен
  • Откуда: Братск, Иркутская область
  • Зарегистрирован: 18.03.2018
  • Сообщений: 29

Re: Как работает .Range.Find.Execute?

Вот с этой строчкой получилось:

r1.MoveEnd Unit:=wdWord, Count:=1

19 Ответ от o5andrey 01.04.2018 12:53:01

  • o5andrey
  • сержант
  • Неактивен
  • Откуда: Братск, Иркутская область
  • Зарегистрирован: 18.03.2018
  • Сообщений: 29

Re: Как работает .Range.Find.Execute?

With Selection.Paragraphs(1).Range
    .Find.Text = ChrW(34)
    .Find.Execute
    If .Find.Found = True Then
        .MoveEnd Unit:=wdWord, Count:=1
        MsgBox (.Text)
    End If
End With

20 Ответ от o5andrey 01.04.2018 16:56:47

  • o5andrey
  • сержант
  • Неактивен
  • Откуда: Братск, Иркутская область
  • Зарегистрирован: 18.03.2018
  • Сообщений: 29

Re: Как работает .Range.Find.Execute?

Как сделать чтобы при этом поиске находилась именно кавычка заданного кода UTF-8? А то не делается различий между кавычками в виде двух верхних чёрточек и

21 Ответ от o5andrey 01.04.2018 16:58:01

  • o5andrey
  • сержант
  • Неактивен
  • Откуда: Братск, Иркутская область
  • Зарегистрирован: 18.03.2018
  • Сообщений: 29

Re: Как работает .Range.Find.Execute?

Как сделать чтобы при этом поиске находилась именно кавычка заданного кода UTF-8? А то не делается различий между кавычками в виде двух верхних чёрточек и «кавычками-ёлочками»: находятся и те и другие (этот поиск работает этим по двум видам кавычек).

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

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
		

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

Понравилась статья? Поделить с друзьями:
  • Word ran in a sentence
  • Word quizzes with answers
  • Word quizzes for english
  • Word quizzes and answers
  • Word quiz questions and answers