Word range find text

Цитата
Сообщение от 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

1 18.10.2016 15:31:20

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

Тема: Range.Find VBA

Доброго времени суток, уважаемые форумчане. Новый вопрос из разряда невероятного:
Какая есть возможность совершить поиск в определённой области документа? Лучше всего от одного абзаца до другого. Что-то у меня с абзацами ничего не вышло и я решил попробовать «от символа до символа». Но проблема в том, что есть уйма разнообразных полей. Казалось бы, всё просто — индексы символов нашёл через Len(от начала документа до места курсора(который становится в выделяемый параграф)). От Len1 До Len2 — вот тебе и область, но по итогу область смещается и текст в эту область попадает не совсем тот. Подскажите как с этим бороться?  (при отображении полей выяснять Len тоже пробовал — не помогает — область всё равно остаётся смещённой, хоть и в меньшей степени)

Вот так ищу первый символ

For Each pPara In ActiveDocument.Paragraphs
    If Left(pPara.Range.Text, Len("Мой текст")) = "Мой текст" Then
        pPara.Range.Select
        iStartSymbol = Len(ActiveDocument.Range(1, Selection.Start))
iNumber = ActiveDocument.Range(1, Selection.Start).Paragraphs.Count
        GoTo Line0
    End If

Вот так второй

For iCount = iNumber To ActiveDocument.Paragraphs.Count
        If ActiveDocument.Paragraphs(iCount).Next.Style = ActiveDocument.Styles("Мой стиль") Then
            ActiveDocument.Paragraphs(iCount).Range.Select
            iEndSymbol = Len(ActiveDocument.Range(1, Selection.Start))
            GoTo Line1
        End If
    Next iCount

Но получается ерунда полнейшая.

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

2 Ответ от Fck_This 18.10.2016 16:54:04

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

Re: Range.Find VBA

Извините за беспокойство — уже сам разобрался. Достаточно было внимательно почитать о возможностях объекта Range. Очень полезная возможность — создание собственной области через

.

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

3 Ответ от yshindin 18.10.2016 17:17:52

  • yshindin
  • генерал-полковник
  • Неактивен
  • Откуда: Москва
  • Зарегистрирован: 12.05.2012
  • Сообщений: 447
  • Поблагодарили: 171

Re: Range.Find VBA

Fck_This пишет:

Какая есть возможность совершить поиск в определённой области документа?

Вы можете выполнять поиск по диапазону с помощью как раз метода Range.Find. В примере привожу поиск по стилю (стартовая программа — SearchByStyleInRange, она в процессе цикла поиска вызывает подпрограмму RangeStartEndOfStyleInRange. Подпрограмма возвращает границы диапазона найденного текста (или -1, если текст не найден).  Закладка на найденном тексте создается на случай необходимости чтения или изменения найденного текста — тогда его можно найти по диапазону этой закладки.

Sub SearchByStyleInRange()
Dim sr As range
Dim ok_to_search As Boolean
Dim search_style_name As String
Dim search_style As Style
Dim ss_start As Long
Dim ss_end As Long
Dim text_found As String
Dim search_found_bookmark_name As String
Set sr = ActiveDocument.range
search_style_name = "DFN" 'find text in this style
ok_to_search = True
On Error Resume Next
Set search_style = ActiveDocument.Styles(search_style_name)
On Error GoTo 0
search_found_bookmark_name = "SearchFoundBookmark" 'bookmark for the text found
If Not (search_style Is Nothing) Then
    While ok_to_search
        'Search by style
        RangeStartEndOfStyleInRange sr, search_style, ss_start, ss_end
        If ss_start = -1 Then 'text not found = stop the search
            ok_to_search = False
        Else 'text is found
            'set bookmark
            If ActiveDocument.Bookmarks.Exists(search_found_bookmark_name) Then
                ActiveDocument.Bookmarks(search_found_bookmark_name).Delete
            End If
            ActiveDocument.Bookmarks.add range:=sr, name:=search_found_bookmark_name
            'process the found text
            text_found = ActiveDocument.Bookmarks(search_found_bookmark_name).range.Text
            ' . . . .
        End If
    Wend
End If
End Sub

Sub RangeStartEndOfStyleInRange(ByRef rgf As range, ByRef st As Style, ByRef fst_start As Long, ByRef fst_end As Long)
'find text with style 'st' in the 'rgf' range.
'the found text boundaries are determined (for not found the -1;-1 values are returned).
fst_start = -1
fst_end = -1
With rgf.Find
    .ClearFormatting
    .Style = st
    .Forward = True
    .Format = True
    .Text = ""
    .Execute
End With
If rgf.Find.found = True Then
    fst_start = rgf.Start
    fst_end = rgf.End
End If
End Sub

4 Ответ от Fck_This 20.10.2016 11:53:53

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

Re: Range.Find VBA

yshindin пишет:

Fck_This пишет:

Какая есть возможность совершить поиск в определённой области документа?

Вы можете выполнять поиск по диапазону с помощью как раз метода Range.Find. В примере привожу поиск по стилю (стартовая программа — SearchByStyleInRange, она в процессе цикла поиска вызывает подпрограмму RangeStartEndOfStyleInRange. Подпрограмма возвращает границы диапазона найденного текста (или -1, если текст не найден).  Закладка на найденном тексте создается на случай необходимости чтения или изменения найденного текста — тогда его можно найти по диапазону этой закладки.

Sub SearchByStyleInRange()
Dim sr As range
Dim ok_to_search As Boolean
Dim search_style_name As String
Dim search_style As Style
Dim ss_start As Long
Dim ss_end As Long
Dim text_found As String
Dim search_found_bookmark_name As String
Set sr = ActiveDocument.range
search_style_name = "DFN" 'find text in this style
ok_to_search = True
On Error Resume Next
Set search_style = ActiveDocument.Styles(search_style_name)
On Error GoTo 0
search_found_bookmark_name = "SearchFoundBookmark" 'bookmark for the text found
If Not (search_style Is Nothing) Then
    While ok_to_search
        'Search by style
        RangeStartEndOfStyleInRange sr, search_style, ss_start, ss_end
        If ss_start = -1 Then 'text not found = stop the search
            ok_to_search = False
        Else 'text is found
            'set bookmark
            If ActiveDocument.Bookmarks.Exists(search_found_bookmark_name) Then
                ActiveDocument.Bookmarks(search_found_bookmark_name).Delete
            End If
            ActiveDocument.Bookmarks.add range:=sr, name:=search_found_bookmark_name
            'process the found text
            text_found = ActiveDocument.Bookmarks(search_found_bookmark_name).range.Text
            ' . . . .
        End If
    Wend
End If
End Sub

Sub RangeStartEndOfStyleInRange(ByRef rgf As range, ByRef st As Style, ByRef fst_start As Long, ByRef fst_end As Long)
'find text with style 'st' in the 'rgf' range.
'the found text boundaries are determined (for not found the -1;-1 values are returned).
fst_start = -1
fst_end = -1
With rgf.Find
    .ClearFormatting
    .Style = st
    .Forward = True
    .Format = True
    .Text = ""
    .Execute
End With
If rgf.Find.found = True Then
    fst_start = rgf.Start
    fst_end = rgf.End
End If
End Sub

Уважаемы, скажите, а это будет работать, если мне нужно найти все вхождения текста в области? Я делал поиск по области

с маской поиска

OurRange.Find.Text "anytext"

через цикл

Do while OurRange.Find.Execute = True

. И дело в том, что у меня несколько масок поиска, а макрос, когда обрабатывает первое выражение, OurRange делает равным маске поиска и это всё сбивает.

Вот полный кусок кода

    Set OurRange = ActiveDocument.Paragraphs(iNumberOne).Range
        OurRange.SetRange Start:=OurRange.Start, End:=ActiveDocument.Paragraphs(iNumberTwo).Range.End
'Устанавливаем свою область
    For i = 1 To 10
        x = 0
        With OurRange.Find
            .Text = FindArray(i)
            .Forward = True
            .Wrap = wdFindStop
            .MatchWildcards = True
                TextOne = OurRange
                TextTwo = Peremennaya
                MsgBox TextOne & TextTwo
'ПОиЗА будет выполняться, пока будут попадаться вхождения
                Do While Selection.Find.Execute = True
                Peremennaya = OurRange.Find.Parent
'Отсейка
'На данном этапе происходит очистка найденной переменной от (по порядку): Замена неразрывного дефиса Chr(30) на обычный Chr(150)
'Выпил точки с запятой "Chr(59)" _ запятой "Chr(44)" _ Открывающей скобки "Chr(40)" _ Знака абзаца "Chr(13)" _
'Неразрывный пробел Chr(160) будет изменён на обычный Chr(32) _ Справа будут удалены пробелы RTrim и точка Chr(46), если есть
                    If InStr(Peremennaya, Chr(30)) >= 1 Then
                        Peremennaya = Replace(Peremennaya, Chr(30), Chr(150))
                        End If
                    If InStr(Peremennaya, Chr(59)) >= 1 Then
                        Peremennaya = Replace(Peremennaya, Chr(59), ReplaceText)
                        End If
                    If InStr(Peremennaya, Chr(44)) >= 1 Then
                        Peremennaya = Replace(Peremennaya, Chr(44), ReplaceText)
                        End If
                    If InStr(Peremennaya, Chr(40)) >= 1 Then
                        Peremennaya = Replace(Peremennaya, Chr(40), ReplaceText)
                        End If
                    If InStr(Peremennaya, Chr(13)) >= 1 Then
                        Peremennaya = Replace(Peremennaya, Chr(13), ReplaceText)
                        End If
                    If InStr(Peremennaya, Chr(160)) >= 1 Then
                        Peremennaya = Replace(Peremennaya, Chr(160), Chr(32))
                        End If
                    If InStr(Peremennaya, Chr(42)) >= 1 Then
                        Peremennaya = Replace(Peremennaya, Chr(42), ReplaceText)
                        End If
                    Peremennaya = RTrim(Peremennaya)
                    If Right(Peremennaya, 1) = Chr(46) Then
                        PeremEdit = Len(Peremennaya) - 1
                        Peremennaya = Left(Peremennaya, PeremEdit)
                        End If
                    If Len(Peremennaya) <= 5 Then
                        x = x
                        GoTo Line00
                    End If
'Условия для сравнения переменной со значениями из массива. Если значения равны - повторяет цикл. Если в значении Переменной
'содержится значение массива - значение массива будет изменено. Если в значении массива содержится значение переменной, то
'цикл повторится. Значение переменной в первом и третьем случае не будет занесено в массив.
'Пометка 1
                        If Not FirstStorageArray(1) = Empty Then
                            For FromLowerToUpper = LBound(FirstStorageArray) To UBound(FirstStorageArray)
                            If Peremennaya Like FirstStorageArray(FromLowerToUpper) Then
                                GoTo Line00
                            ElseIf InStr(Peremennaya, FirstStorageArray(FromLowerToUpper)) >= 1 Then
                                FirstStorageArray(FromLowerToUpper) = Peremennaya
                                GoTo Line00
                            ElseIf InStr(FirstStorageArray(FromLowerToUpper), Peremennaya) >= 1 Then
                                GoTo Line00
                            End If
                            Next FromLowerToUpper
                        End If
                    x = x + 1
                    ReDim Preserve FirstStorageArray(x)
                    FirstStorageArray(x) = Peremennaya
Line00:
        Set OurRange = ActiveDocument.Paragraphs(iNumberOne).Range
        OurRange.SetRange Start:=OurRange.Start, End:=ActiveDocument.Paragraphs(iNumberTwo).Range.End
                Loop
                End With

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

5 Ответ от yshindin 20.10.2016 12:09:36

  • yshindin
  • генерал-полковник
  • Неактивен
  • Откуда: Москва
  • Зарегистрирован: 12.05.2012
  • Сообщений: 447
  • Поблагодарили: 171
  • За сообщение: 1

Re: Range.Find VBA

Fck_This пишет:

Уважаемы, скажите, а это будет работать, если мне нужно найти все вхождения текста в области?

Если вы сразу хотите находить одно из нескольких возможных значений, то попробуйте обратиться к аппарату регулярных выражений (в Word реализованы wildcards — см., напр., внешняя ссылка. А проще — если не критично по времени, то переберите в цикле все абзацы, а в них — выполните поиск различных символов и соответствующие замены.

6 Ответ от Fck_This 20.10.2016 12:17:35

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

Re: Range.Find VBA

yshindin пишет:

Fck_This пишет:

Уважаемы, скажите, а это будет работать, если мне нужно найти все вхождения текста в области?

Если вы сразу хотите находить одно из нескольких возможных значений, то попробуйте обратиться к аппарату регулярных выражений (в Word реализованы wildcards — см., напр., внешняя ссылка. А проще — если не критично по времени, то переберите в цикле все абзацы, а в них — выполните поиск различных символов и соответствующие замены.

Спасибо за совет. Изначально была мысль просто перебрать все абзацы области. Но я же не ищу лёгких путей, как говорится. Думал открыть что-то новое.

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

7 Ответ от Fck_This 20.10.2016 12:20:03

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

Re: Range.Find VBA

yshindin пишет:

Fck_This пишет:

Уважаемы, скажите, а это будет работать, если мне нужно найти все вхождения текста в области?

Если вы сразу хотите находить одно из нескольких возможных значений, то попробуйте обратиться к аппарату регулярных выражений (в Word реализованы wildcards — см., напр., внешняя ссылка. А проще — если не критично по времени, то переберите в цикле все абзацы, а в них — выполните поиск различных символов и соответствующие замены.

ссылка не работает

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

8 Ответ от Fck_This 20.10.2016 12:30:11

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

Re: Range.Find VBA

yshindin пишет:

Fck_This пишет:

Уважаемы, скажите, а это будет работать, если мне нужно найти все вхождения текста в области?

Если вы сразу хотите находить одно из нескольких возможных значений, то попробуйте обратиться к аппарату регулярных выражений (в Word реализованы wildcards — см., напр., внешняя ссылка. А проще — если не критично по времени, то переберите в цикле все абзацы, а в них — выполните поиск различных символов и соответствующие замены.

Про регулярные выражения я знаю, но дело в том, что подобрать одно для всех невозможно, а через цикл Do while MyRange.Find.Execute = True MyRange становится равной FindText. Макрос ищет по первой регулярке, а затем делает её областью и вторую уже не ищет.

 First = "СТБ[!A-Za-zА-яЁё]ГОСТ[!A-Za-zА-яЁё]Р[!A-Za-zА-яЁё[]{1;}"
Second = "СТБ[!A-Za-zА-яЁё]ЕН[!A-Za-zА-яЁё[]{1;}"
Third = "СТБ[!A-Za-zА-яЁё]ISO[!A-Za-zА-яЁё[]{1;}"
Fourth = "СТБ[!A-Za-zА-яЁё[]{1;}"
Fifth = "ГОСТ[!A-Za-zА-яЁё]ИСО[!A-Za-zА-яЁё[]{1;}"
Sixth = "ГОСТ[!A-Za-zА-яЁё]Р[!A-Za-zА-яЁё[]{1;}"
Seventh = "ГОСТ[!A-Za-zА-яЁё]ISO[!A-Za-zА-яЁё[]{1;}"
Eighth = "ГОСТ[!A-Za-zА-яЁё[]{1;}"
Ninth = "ТР[!A-Za-zА-яЁё[]ТС[!A-Za-zА-яЁё[]{1;}"
Tenth = "ИСО[!A-Za-zА-яЁё[]{1;}"

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

9 Ответ от yshindin 20.10.2016 12:31:13

  • yshindin
  • генерал-полковник
  • Неактивен
  • Откуда: Москва
  • Зарегистрирован: 12.05.2012
  • Сообщений: 447
  • Поблагодарили: 171

Re: Range.Find VBA

Fck_This пишет:

ссылка не работает

Еще раз: внешняя ссылка

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
  • Remove From My Forums
  • Question

  • Hi,

    I can find text with the code:

    dc.Activate();
    dc.Content.Find.ClearFormatting();
    dc.Content.Find.Wrap = WdFindWrap.wdFindContinue;
    dc.Content.Find.Format = false;
    dc.Content.Find.MatchCase = false;
    dc.Content.Find.MatchWholeWord = false;
    dc.Content.Find.MatchWildcards = false;
    dc.Content.Find.MatchSoundsLike = false;
    dc.Content.Find.MatchAllWordForms = false;
    dc.Content.Find.Forward = true;
    object missing = System.Reflection.Missing.Value;
    object repl = WdReplace.wdReplaceNone;
    object Wrap = WdFindWrap.wdFindContinue;
    result = dc.Content.Find.Execute(findItem, missing, missing, missing, missing, missing, missing, Wrap, missing, "", repl, missing, missing, missing, missing);

    This tells me if the text is found or not . But I need the range of the found text-piece, because i would like to know what content
    control contain the word. I also need to implement a sort of MS Word «find next», when i find an occurrence 
    of
    the word, check what «parentContentControl» contains the word, and continue searching until the end of the document.

    I really don’t know how to get it. Would be nice if you could help me out.

    Thanks

    Matteo

    • Moved by

      Tuesday, November 4, 2014 3:31 AM
      move to appropriate forum

Answers

  • Hi M4TT3,

    First, to get the find text range, you could use Range.Select() method.

    Word.Document dc = this.Application.ActiveDocument;
    
                Word.Range rng = dc.Content;
    
                dc.Activate();
    
                rng.Find.ClearFormatting();
    
                rng.Find.Wrap = Word.WdFindWrap.wdFindContinue;
    
                rng.Find.Format = false;
    
                rng.Find.MatchCase = false;
    
                rng.Find.MatchWholeWord = false;
    
                rng.Find.MatchWildcards = false;
    
                rng.Find.MatchSoundsLike = false;
    
                rng.Find.MatchAllWordForms = false;
    
                rng.Find.Forward = true;
    
                object missing = System.Reflection.Missing.Value;
    
                object repl = Word.WdReplace.wdReplaceNone;
    
                object Wrap = Word.WdFindWrap.wdFindContinue;
    
                if (rng.Find.Execute(findItem, missing, missing, missing, missing, missing, missing, Wrap, missing, "", repl, missing, missing, missing, missing))
    
                {
    
                    MessageBox.Show("Text found.");
    
                }
    
                else
    
                {
    
                    MessageBox.Show("Text not found.");
    
                }
    
               
    
                rng.Select();

    Secondly, to continue to find the next, you need to change the content instead of using the whole document content everytime (Get remaining content range). You may use
    Selection.Find directly.

    Application.Selection.Find.Execute

    To get the word of parent’s content control, you could get the selected range’s
    ParentContentControl.

    rng.Select();
    Word.ContentControl c = rng.ParentContentControl;
    MessageBox.Show(c.Range.Text);

    There is a link about search text in documents that can help you:

    # Programmatically Search for and Replace Text in Documents

    http://msdn.microsoft.com/en-us/library/f1f367bx.aspx

    Best Regards

    Starain


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.

    Click
    HERE to participate the survey.

    • Edited by
      Starian chenMicrosoft contingent staff
      Wednesday, November 5, 2014 9:45 AM
    • Proposed as answer by
      Starian chenMicrosoft contingent staff
      Friday, November 21, 2014 9:32 AM
    • Marked as answer by
      George Hua
      Tuesday, November 25, 2014 10:04 AM

title ms.prod ms.assetid ms.date ms.localizationpriority

Finding and Replacing Text or Formatting

word

9ab9f4a7-9833-5a78-56b0-56a161480f18

06/08/2019

medium

Finding and replacing is exposed by the Find and Replacement objects. The Find object is available from the Selection object and the Range object. The find action differs slightly depending upon whether you access the Find object from the Selection object or the Range object.

Finding text and selecting it

If the Find object is accessed from the Selection object, the selection is changed when the find criteria is found. The following example selects the next occurrence of the word «Hello.» If the end of the document is reached before the word «Hello» is found, the search is stopped.

With Selection.Find 
 .Forward = True 
 .Wrap = wdFindStop 
 .Text = "Hello" 
 .Execute 
End With

The Find object includes properties that relate to the options in the Find and Replace dialog box. You can set the individual properties of the Find object or use arguments with the Execute method, as shown in the following example.

Selection.Find.Execute FindText:="Hello", _ 
 Forward:=True, Wrap:=wdFindStop

Finding text without changing the selection

If the Find object is accessed from a Range object, the selection is not changed but the Range is redefined when the find criteria is found. The following example locates the first occurrence of the word «blue» in the active document. If the find operation is successful, the range is redefined and bold formatting is applied to the word «blue.»

With ActiveDocument.Content.Find 
 .Text = "blue" 
 .Forward = True 
 .Execute 
 If .Found = True Then .Parent.Bold = True 
End With

The following example performs the same result as the previous example, using arguments of the Execute method.

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

Using the Replacement object

The Replacement object represents the replace criteria for a find and replace operation. The properties and methods of the Replacement object correspond to the options in the Find and Replace dialog box (Edit menu).

The Replacement object is available from the Find object. The following example replaces all occurrences of the word «hi» with «hello». The selection changes when the find criteria is found because the Find object is accessed from the Selection object.

With Selection.Find 
 .ClearFormatting 
 .Text = "hi" 
 .Replacement.ClearFormatting 
 .Replacement.Text = "hello" 
 .Execute Replace:=wdReplaceAll, Forward:=True, _ 
 Wrap:=wdFindContinue 
End With

The following example removes bold formatting in the active document. The Bold property is True for the Find object and False for the Replacement object. To find and replace formatting, set the find and replace text to empty strings («») and set the Format argument of the Execute method to True. The selection remains unchanged because the Find object is accessed from a Range object (the Content property returns a Range object).

With ActiveDocument.Content.Find 
 .ClearFormatting 
 .Font.Bold = True 
 With .Replacement 
 .ClearFormatting 
 .Font.Bold = False 
 End With 
 .Execute FindText:="", ReplaceWith:="", _ 
 Format:=True, Replace:=wdReplaceAll 
End With

[!includeSupport and feedback]

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