Word find colored text

Я знаю, что это очень устарело в качестве ответа, но, поскольку у большего количества пользователей может быть похожая проблема, это мое частичное решение.

В версиях MS Word, в которых используется лента, щелкните раскрывающееся меню значка «Найти», чтобы выбрать «Расширенный поиск».
В новом окне найдите кнопку «Ещё >>», а внизу есть метка «Найти» с опцией кнопки «Формат». Нажмите на него и выберите «Выделить» (хотя я еще не нашел, как установить цвет за это короткое время, я должен был ответить).


Этот отредактированный ответ является более подходящим обходным решением для чего-то, на что, очевидно, никто пока не мог ответить, поэтому я решил оставить исходный ответ (до строки выше) в качестве ответа на вопрос, который подходит большинству пользователей, попадающих на эту страницу ( нет смысла усложнять то, что не должно быть сложным), и разрабатывать новое.

Принимая во внимание то, что указано в MSDN (https://msdn.microsoft.com/en-us/vba/word-vba/articles/find-object-word), можно получить следующую информацию:

НаходкаМетод Execute не имеет никакого отношения к выделению, так как сам по себе выделение не является форматом, как видно из названия, это просто выделение.

НаходкаСвойство Highlight допускает только обычные логические (True , False) и wdUndefined (игнорируя выделение цветом) и поэтому не позволяет указывать цвет.

НаходкаМетод HitHighLight применяется к объектам Outlook, но может использоваться в Word для поиска и удаления выделения (но опять же не для указания определенного цвета среди нескольких цветов), например,
ActiveDocument.Content.Find.HitHighlight FindText:="text to find"

С предыдущими утверждениями можно действительно найти (или, по крайней мере, для меня) невозможным найти разные цвета без сложного макроса, который сравнивает каждый символ с цветом подсветки по умолчанию (который я уверен, что не собираюсь делать …) или редактирование кода файла (на мой взгляд, это хорошее решение, так что спасибо пользователю, который его опубликовал, но, как пользователь, дал громоздкий ответ большинству пользователей Word). На мой взгляд, есть более подходящий и простой способ использования гораздо более удобного расширенного поиска с опцией « Стиль» .
Для этого вы должны использовать стиль с затенением вместо выделения (или комбинировать оба).

Таким образом, используя мои предыдущие инструкции, помимо опции « Подсветка» , вы также можете использовать опцию « Стиль» для поиска предыдущего добавленного стиля (стилей) с тем же цветом (цветами), которые вы хотите найти, или если вы предпочитаете затенение и выделение цветом. слова для более полного и узкого поиска.

Written by Allen Wyatt (last updated September 13, 2022)
This tip applies to Word 2007, 2010, 2013, 2016, 2019, and Word in Microsoft 365


Amir uses different highlighting colors throughout his documents. When he uses Find and Replace to find highlighted text, it treats all highlighting colors the same. Amir would like, specifically, to use Find and Replace to locate only text highlighted in yellow, having it ignore any other highlighting color used in the document.

Before getting into how to possibly do this, it is important to discuss terms for a moment. When using the term «highlighting color,» some people think that is referring to the color applied to some particular text; it is not. Highlighting doesn’t change the font’s color. Highlighting is accomplished by using the Text Highlight Color tool, which is available in the Font group on the Home tab of the ribbon. (See Figure 1.)

Figure 1. Word allows you to highlight text using different colors.

When you use the Find and Replace dialog box, you can specify that you want to search for text that is highlighted. (Put the insertion point in the Find box, click Format, then click Highlight.) When you click on Find Next, Word selects the next highlighted text, regardless of the color used to highlight that text. In other words, you cannot specify that you only want to find text highlighted in yellow or blue or green or any other color; it is all treated the same.

We haven’t been able to find any reliable way around this. Some information we’ve seen indicates that Word will only find whatever highlight color is specified in the Text Highlight Color tool, but this is not true. Other folks have indicated that if you select some highlighted text (that is highlighted with the color you want to find) before displaying the Find and Replace dialog box, only that highlight color will be found when you click Find Next. This, too, is not true. In all cases, Find Next will find any highlighted text, irrespective of color used for highlighting.

The only way around this is to use a macro to do the finding. VBA allows you to detect the color used to highlight text, which is why this approach will work. The following macro uses Find and Replace to do the finding, but then it checks to see what the HighlightColorIndex property is for what was found. If it is equal to wdYellow (an enumeration for the color yellow), then the text is selected and the macro is exited.

Sub FindNextYellow()
    With Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = ""
        .MatchWildcards = False
        .Forward = True
        .Wrap = wdFindContinue
        .Highlight = True
        Do
            .Execute
        Loop Until Selection.Range.HighlightColorIndex = wdYellow _
          Or Not .Found
        Selection.Range.Select
    End With
End Sub

You can search for different colors simply by changing the wdYellow enumeration to the enumeration for whatever color you want.

If you would like to know how to use the macros described on this page (or on any other page on the WordTips sites), I’ve prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

WordTips is your source for cost-effective Microsoft Word training.
(Microsoft Word is the most popular word processing software in the world.)
This tip (13552) applies to Microsoft Word 2007, 2010, 2013, 2016, 2019, and Word in Microsoft 365.

Author Bio

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. Learn more about Allen…

MORE FROM ALLEN

Out of Memory Errors when Accessing the VBA Editor

It can be frustrating when you get error messages doing something that you previously did with no errors. If you get an …

Discover More

Footnotes within Footnotes

Need to add footnotes to your footnotes? It’s actually allowed by some style guides, but Word doesn’t make it so easy.

Discover More

Zooming With the Keyboard

Excel doesn’t provide a keyboard shortcut that allows you to zoom in or out on your workbook. It is easy, however, to …

Discover More

I know this is far outdated as a reply, but since more users could have a similar problem, this is my partial solution.

In versions of MS Word that use the Ribbon, click on the drop-down menu of the Find icon to choose the Advanced Find.
In the new window locate the «More>>» button and at the bottom, there is a label «Find» with an option button Format. Click on it and chose «Highlight» (though I have yet to find how to set the color in this short time I had to reply).


This edited answer is a more suitable workaround for something that apparently no one could answer so far, so I decided to keep the original answer (before the line above) as a reply to a question that fits most users that end up on this page (no point complicating what doesn’t need to be complicated), and elaborate on a new one.

Taking into account on what is stated in MSDN (https://msdn.microsoft.com/en-us/vba/word-vba/articles/find-object-word) one can retrieve the following information:

The Find.Execute method does not have any regards to highlight, as in itself highlight is not a format, as the name indicates, it’s just a highlight.

The Find.Highlight property only admits the normal Boolean (True, False) and wdUndefined (ignoring highlights), and as such doesn’t allow specifying a color.

The Find.HitHighLight method applies to Outlook objects but can be used in Word to find and remove highlight (but again not to specify a specific color among several colors), for example,
ActiveDocument.Content.Find.HitHighlight FindText:="text to find"

With the previous statements one can indeed find it impossible (or at least to me) to find different colors without a complex macro that compares each character to the default color of highlight (which I’m sure not going to make…) or editing the file code (which is a good solution, in my view, so kudos for the user that posted it, but as the user stated a cumbersome answer to most users of Word). In my opinion, there’s a more suitable and easy workaround using the far easier to use Advanced Find with the Style option.
For that you have to use a Style with Shading instead of the highlight (or combining both).

So using my previous instructions, besides the Highlight option,
you can also use the Style option to search for a previous added style(s) with the same color(s) you want to find, or if you prefer a shading color and a highlight of the word for a more complete and narrowed search.

148 / 116 / 10

Регистрация: 12.09.2011

Сообщений: 785

1

19.07.2014, 18:39. Показов 6762. Ответов 12


Студворк — интернет-сервис помощи студентам

Привет всем!

Подскажите, пожалуйста, каким образом средствами VBA в открытом документе Word найти текст (слово, фразу) окрашенный в определенный цвет, например красный?

Спасибо!



0



Антихакер32

Заблокирован

20.07.2014, 00:17

2

Лучший ответ Сообщение было отмечено Vinemax как решение

Решение

Например ищем по формату

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
Sub Макрос3()
'
' Макрос3 Макрос
' Макрос записан 20.07.2014 (Антихакер32)
'
 
'
    Application.FindFormat.Interior.ColorIndex = 3
    Cells.Find(What:="", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
        xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
        , SearchFormat:=True).Activate
End Sub

Добавлено через 3 минуты
для красного
Application.FindFormat.Interior.ColorIndex = 3
для синего
Application.FindFormat.Interior.ColorIndex = 5
ну и тд

Добавлено через 34 минуты
Вот еще вариант, где указывается шрифт, стиль цвет текста и тд

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Sub Макрос4()
'
' Макрос4 Макрос
' Макрос записан 20.07.2014 (Антихакер32)
'
 
    Application.FindFormat.Clear
 
    With Application.FindFormat.Font
        .Name = "Arial"
        .FontStyle = "обычный"
        .Size = 10
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .Underline = xlUnderlineStyleNone
        .ColorIndex = 3
    End With
    Cells.Find(What:="", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
        xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
        , SearchFormat:=True).Activate
End Sub



1



148 / 116 / 10

Регистрация: 12.09.2011

Сообщений: 785

20.07.2014, 22:43

 [ТС]

3

Антихакер32, спасибо большое!

А вы не в курсе, можно ли как-то еще получать информацию о страницах документа, т.е. сколько их и на странице с каким номером находится найденный текст?



0



Антихакер32

Заблокирован

20.07.2014, 22:53

4

вот как узнать сколько листов в книге

Visual Basic
1
Debug.Print Worksheets.Count

вот имя активного листа

Visual Basic
1
Debug.Print ActiveSheet.Name



1



148 / 116 / 10

Регистрация: 12.09.2011

Сообщений: 785

21.07.2014, 08:56

 [ТС]

5

Антихакер32, это ведь Excel… а мне бы Word



0



Антихакер32

Заблокирован

21.07.2014, 09:19

6

Хорошо, позже выложу отдельный, развернутый пример
для Word, признаюсь в Word я особо не влазию
но там тоже есть все то-же для создания макросов что и в Excel
как освобожусь от своих дел, сделаю



1



148 / 116 / 10

Регистрация: 12.09.2011

Сообщений: 785

21.07.2014, 12:39

 [ТС]

7

Антихакер32, спасибо! буду очень благодарен… просто, задача стоит от заказчика именно со страницами и их номерами, уже весь Гугл облазил, ничего вразумительного



0



Аксима

6076 / 1320 / 195

Регистрация: 12.12.2012

Сообщений: 1,023

21.07.2014, 13:22

8

Лучший ответ Сообщение было отмечено Vinemax как решение

Решение

Пока уважаемый Антихакер32 занят, предложу свой вариант, ведь работать с Word мне приходится часто.

Итак, вариант, который я хочу предложить:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Sub FindFormattedData()
    Dim rng As Range
    Set rng = ActiveDocument.Range
    With rng.Find
        'Î÷èùàåì ðàíåå óñòàíîâëåííûå òðåáîâàíèÿ ê ôîðìàòó òåêñòà, êîòîðûé íàäî íàéòè.
        .ClearFormatting
        'Èùåì òåêñò, âûäåëåííûé êðàñíûì.
        .Font.Color = wdColorRed
        .Format = True
        'Òåêñò - ýòî ëþáîå ñëîâî, íåâàæíî êàêîå, ãëàâíîå, ÷òîáû îíî áûëî âûäåëåíî êðàñíûì.
        .Text = "<*>"
        .MatchWildcards = True
        'Âûïîëíÿåì çàïðîñ íà ïîèñê íóæíîãî òåêñòà.
        .Execute
    End With
    'Âûâîäèì èíôîðìàöèþ î ñòðàíèöå, ãäå íàéäåí òåêñò, è îáùåì êîëè÷åñòâå ñòðàíèö.
    MsgBox "Ïîäõîäÿùèé òåêñò (" & rng.Text & ") íàéäåí íà ñòðàíèöå " & rng.Information(wdActiveEndPageNumber) & " èç " & rng.Information(wdNumberOfPagesInDocument)
End Sub

С уважением,

Aksima



2



148 / 116 / 10

Регистрация: 12.09.2011

Сообщений: 785

21.07.2014, 15:31

 [ТС]

9

Aksima, сейчас буду пробовать… спасибо большое! это что-то… отпишусь, как сделаю

Добавлено через 10 минут
Всё отлично! Ищет и страницы показывает… Господа, скажите, а возможно ли как-то находить вообще цветные слова, т.е. не зная их изначального цвета, — отличающиеся от основного?



0



Аксима

6076 / 1320 / 195

Регистрация: 12.12.2012

Сообщений: 1,023

21.07.2014, 15:56

10

Лучший ответ Сообщение было отмечено Vinemax как решение

Решение

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

а возможно ли как-то находить вообще цветные слова, т.е. не зная их изначального цвета, — отличающиеся от основного

Нет ничего проще:

Visual Basic
1
2
3
4
5
6
7
8
9
10
Sub FindColoredWords()
    Dim d As Document, w As Range, tc As Long
    Set d = ActiveDocument
    'Îïðåäåëÿåì öâåò îñíîâíîãî òåêñòà.
    tc = d.Styles(wdStyleBodyText).Font.TextColor.RGB
    'Íàõîäèì ñëîâà, öâåò êîòîðîãî îòëè÷àåòñÿ îò öâåòà îñíîâíîãî òåêñòà.
    For Each w In ActiveDocument.Words
        If w.Font.TextColor.RGB <> tc And w.Text Like "*[A-Za-zÀ-ßà-ÿ]*" Then MsgBox "Öâåòíîå ñëîâî (" & w.Text & ") íàéäåíî íà ñòðàíèöå " & w.Information(wdActiveEndPageNumber) & " èç " & w.Information(wdNumberOfPagesInDocument)
    Next w
End Sub

С уважением,

Aksima



2



148 / 116 / 10

Регистрация: 12.09.2011

Сообщений: 785

21.07.2014, 16:12

 [ТС]

11

Aksima, бомба! Спасибо огромное! Два дня Гугла ничего не дали… )) Прошу прощения за навязчивость, но не могли бы вы еще подсказать, как программно в документ добавлять слова или фразы, в общем, текст со шрифтом, цветом и т.д.?



0



Аксима

6076 / 1320 / 195

Регистрация: 12.12.2012

Сообщений: 1,023

21.07.2014, 16:51

12

Vinemax, изучайте методы InsertAfter, InsertBefore, InsertParagraphAfter, InsertParagraphBefore, а также методы объекта Font.

Вот небольшой пример, чтобы вы могли составить себе представление о работе этих методов:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Sub AddWordsToEndOfDocument()
    Dim d As Document, ps As Paragraphs, rng As Range, w As Range, txt As String, tc As Long, tcBody As Long
    Set d = ActiveDocument: Set ps = d.Paragraphs: Set rng = d.Range
    'Узнаем цвет основного текста.
    tc = d.Styles(wdStyleBodyText).Font.TextColor.RGB
    'В цикле добавляем в документ новые слова с указанием их форматирования.
    Do
        txt = InputBox("Введите какой-нибудь текст.", "Ввод слова или фразы")
        If txt <> "" Then
            Do
                tc = Val(InputBox("Укажите номер цвета, в который красится текст:" & vbCr & "0) Не красить" & vbCr & "1) Красный" & vbCr & "2) Зеленый" & vbCr & "3) Синий", "Ввод цвета"))
                If tc < 0 Or tc > 3 Then MsgBox "Вы ошиблись при выборе цвета!"
            Loop While tc < 0 Or tc > 3
            'Добавляем в документ новый параграф и в него - текст txt.
            rng.InsertParagraphAfter
            rng.InsertAfter txt
            'Получаем ссылку на диапазон нового параграфа.
            Set w = ps(ps.Count).Range
            'Если выбран пункт номер 0 (Не красить), то задаем шрифту цвет
            'основного текста, иначе задаем цвет, соответствующий выбранному номеру.
            If tc = 0 Then w.Font.TextColor.RGB = tcBody Else w.Font.TextColor.RGB = 256 ^ (tc - 1) * 255
            'Выделяем созданный текст, чтобы пользователь видел, какое слово было добавлено.
            w.Select
        End If
    Loop While txt <> ""
End Sub

С уважением,

Aksima



2



148 / 116 / 10

Регистрация: 12.09.2011

Сообщений: 785

21.07.2014, 17:00

 [ТС]

13

Aksima, благодарю!



0



  • Remove From My Forums
  • Question

  • i’m struggling with what i have read on the internet and here on the forums. i need some clarity on how to find a match on a string in a 2003 Word document and using Visual Studio C# 2010 to change the string in a different font.

    it would need to scan each line and change the font for the matching string.

    can anyone help explain what is being the fog?

    • Moved by

      Saturday, September 3, 2011 10:31 PM
      Office related (From:Visual C# General)

Answers

  • Hi,

    Thanks for telling me that…It’s my mistake, we need to change Find.Format property to true in ReplaceFont method:

            public bool ReplaceFont(Word.Range rng, string findWhat)
            {
                bool hasFound = false;
                rng.Find.ClearFormatting();
                rng.Find.Replacement.ClearFormatting();
                rng.Find.Replacement.Font.ColorIndex = Word.WdColorIndex.wdBlue;
                rng.Find.Text = findWhat;
                rng.Find.Replacement.Text = findWhat;
                rng.Find.Forward = true;
                rng.Find.Wrap = Word.WdFindWrap.wdFindStop;
    
                //change this property to true as we want to replace format
                rng.Find.Format = true;
    
                hasFound = rng.Find.Execute(Replace: Word.WdReplace.wdReplaceAll);
                return hasFound;
            }
    

    Good day :-)


    Best Regards, Calvin Gao [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by
      hauld
      Tuesday, September 13, 2011 5:45 PM

Понравилась статья? Поделить с друзьями:
  • Word find capitalized words
  • Word find board games
  • Word find back to school
  • Word find any character
  • Word find and sound