Global replace in word

Find and replace text

Your browser does not support video. Install Microsoft Silverlight, Adobe Flash Player, or Internet Explorer 9.

  1. Go to Home > Replace.

  2. Enter the word or phrase you want to replace in Find what.

  3. Enter your new text in Replace with.

  4. Choose Replace All to change all occurrences of the word or phrase. Or, select Find Next until you find the one you want to update, and then choose Replace.

  5. To specify only upper or lowercase in your search, select More > Match case. There are several other ways to search in this menu.

Match case

For other options, see Find and replace text

Find and replace basic text

In the upper-right corner of the document, in the search box Enter text to search for in the document, type the word or phrase that you want to find, and Word will highlight all instances of the word or phrase throughout the document.

To replace found text:

  1. Select the magnifying glass, and then select Replace.

    The Replace option is highlighted in the Search box

  2. In the Replace With box, type the replacement text.

  3. Select Replace All or Replace.

    Tips: 

    • You can also open the basic Find and Replace pane with the keyboard shortcut CONTROL + H.

    • When you replace text, it’s a good idea to select Replace instead of Replace All. That way you can review each item before replacing it.

You can find text with special formatting, such as bold or highlight, by using the Format menu.

  1. Select View > Navigation Pane.

    On the View tab, Navigation Pane is checked

  2. In the Navigation Pane, select the magnifying glass.

  3. Select Settings Screenshot of gear, and then select Advanced Find & Replace.

    In the Find and Replace box, Advanced Find and Replace is highlighted

    Notes: 

    • Select the arrow at the bottom of the Find and Replace dialog box to show all options.

    • Shows how to open the Format popup menu

  4. On the Format menu, select the option that you want.

    Shows the Format options

    If a second dialog box opens, select the options that you want, and then select OK.

  5. In the Find and Replace dialog box, select Find Next or Find All.

You can find and replace text with special formatting, such as bold or highlight, by using the Format menu.

  1. Select View > Navigation Pane.

    On the View tab, Navigation Pane is checked

  2. In the Navigation Pane, select the magnifying glass.

  3. Select Settings Screenshot of gear, and then select Advanced Find & Replace.

    In the Find and Replace box, Advanced Find and Replace is highlighted

  4. At the top of the dialog box, select Replace.

    Notes: 

    • Select the arrow at the bottom of the Find and Replace dialog box to show all options.

    • Shows how to open the Format popup menu

  5. On the Find what box, type the text that you want to find.

  6. On the Format menu, select the formatting that you want to find.

    Shows the Format options

    If a second dialog box opens, select the options that you want, and then select OK.

  7. Select in the box next to Replace with.

  8. On the Format menu, select the replacement formatting. If a second dialog box appears, select the formats that you want, and then select OK.

  9. Select Replace, Replace All, or Find Next.

  1. Select View > Navigation Pane.

  2. In the Navigation Pane, select the magnifying glass.

  3. Select Settings Screenshot of gear, and then select Advanced Find & Replace.

    In the Find and Replace box, Advanced Find and Replace is highlighted

    Notes: 

    • Select the arrow at the bottom of the Find and Replace dialog box to show all options.

    • Shows how to open the Format popup menu

  4. On the Special menu, select the special character that you want to find.

    Find special characters

  5. Select Find Next.

  1. Select View > Navigation Pane.

    On the View tab, Navigation Pane is checked

  2. In the Navigation Pane, select the magnifying glass.

  3. Select Settings Screenshot of gear, and then select Advanced Find & Replace.

    In the Find and Replace box, Advanced Find and Replace is highlighted

    Notes: 

    • Select the arrow at the bottom of the Find and Replace dialog box to show all options.

    • Shows how to open the Format popup menu

  4. At the top of the Find and Replace dialog box, select Replace and then select in the Find What box, but don’t type anything there. Later, when you select a special character, Word will automatically put the character code in the box for you.

    Note: Select the arrow at the bottom of the Find and Replace dialog box to show all options.
    Shows how to open the Format popup menu

  5. On the Special menu, select the special character that you want to find.

  6. Select in the Replace with box.

  7. On the Special menu, select the special character that you want to use as a replacement.

  8. Select Replace or Find Next.

  1. Select View > Navigation Pane.

    On the View tab, Navigation Pane is checked

  2. In the Navigation Pane, select the magnifying glass.

  3. Select Settings Screenshot of gear, and then select Advanced Find & Replace.

    In the Find and Replace box, Advanced Find and Replace is highlighted

  4. Select the Use wildcards check box.

    If you don’t see the Use wildcards check box, select Down arrow for more options.

  5. Select the Special menu, select a wildcard character, and then type any additional text in the Find what box.

    Using wildcards in the Find and Replace dialog box

  6. Select Find Next.

    Tips: 

    • To cancel a search in progress, press The Command button.+ PERIOD.

    • You can also enter a wildcard character directly in the Find what box instead of selecting an item from the Special pop-up menu.

    • To search for a character that’s defined as a wildcard character, type a backslash () before the character. For example, type ? to find a question mark.

    • You can use parentheses to group the wildcard characters and text and to indicate the order of evaluation. For example, search for <(pre)*(ed)> to find «presorted» and «prevented.»

    • You can search for an expression and use the n wildcard character to replace the search string with the rearranged expression. For example, type (Newman) (Belinda) in the Find what box and 2 1 in the Replace with box. Word will find «Newman Belinda» and replace it with «Belinda Newman.»

  7. To replace found text:

    1. Select the Replace tab, and then select the Replace with box.

    2. Select Special, select a wildcard character, and then type any additional text in the Replace with box.

    3. Select Replace All, Replace, or Find Next.

      Tip: When you replace text, it’s a good idea to select Replace instead of Replace All. That way you can confirm each replacement to make sure that it’s correct.

You can refine a search by using any of the following wildcard characters.

To find

Use this

For example

Any single character

?

s?t finds «sat» and «set.»

Any string of characters

*

s*d finds «sad» and «started.»

One of the specified characters

[ ]

w[io]n finds «win» and «won.»

Any single character in this range

[-]

[r-t]ight finds «right» and «sight» and «tight.»

Ranges must be in ascending order.

Any single character except the characters inside the brackets

[!]

m[!a]st finds «mist» and «most» but not «mast.»

Any single character except characters in the range inside the brackets

[!x-z]

t[!a-m]ck finds «tock» and «tuck» but not «tack» or «tick.»

Ranges must be in ascending order.

Exactly n occurrences of a character or expression

{ n}

fe{2}d finds «feed» but not «fed.»

At least n occurrences of a character or expression

{ n,}

fe{1,}d finds «fed» and «feed.»

A range of occurrences of a character or expression

{ n, n}

10{1,3} finds «10,» «100,» and «1000.»

One or more occurrences of a character or expression

@

lo@t finds «lot» and «loot.»

The beginning of a word

<

<(inter) finds «interesting» and «intercept» but not «splintered.»

The end of a word

>

(in)> finds «in» and «within,» but not «interesting.»

Word for the web lets you find and replace basic text. You can match case or fine whole words only. For more varied options, open your document in Word for the desktop.

Need more help?

LarryOfKnollwood


  • #1

I write my talks in Word and then use the Replace Command to bold and
underline specific words to help my eyes move through the text. Is there a
global way of doing this rather than word by word? I tried separating the
words by comma’s, but didn’t work.

Advertisements

macropod


  • #2

Hi LarryOfKnollwood,

In the Find box, insert the word you’re looking for,
In the Replace box, type ‘^&’, then choose More|Format|Font > Bold.

Advertisements

Graham Mayor


  • #3

Put the words (not case sensitive) in a single column table save the table
as a document and put its path/name where shown in the following macro. Then
run the macro on your document.

Sub ReplaceFromTableList()

Dim ChangeDoc As Document, RefDoc As Document
Dim cTable As Table
Dim oldPart As Range
Dim i As Long
Dim sFname As String
‘********************************************
sFname = «D:My DocumentsTestchanges2.doc»
‘********************************************
Set RefDoc = ActiveDocument
Set ChangeDoc = Documents.Open(sFname)
Set cTable = ChangeDoc.Tables(1)
RefDoc.Activate
For i = 1 To cTable.Rows.Count
Set oldPart = cTable.Cell(i, 1).Range
oldPart.End = oldPart.End — 1
With Selection
.HomeKey wdStory
With .Find
.ClearFormatting
.Replacement.ClearFormatting
‘****************************************
.Replacement.Font.Underline = True
.Replacement.Font.Bold = True
‘****************************************
.Execute findText:=oldPart, _
ReplaceWith:=»^&», _
Replace:=wdReplaceAll, _
MatchWildcards:=False, _
Forward:=True, _
Wrap:=wdFindContinue
End With
End With
Next i
ChangeDoc.Close wdDoNotSaveChanges
End Sub


<>>< ><<> ><<> <>>< ><<> <>>< <>><<>
Graham Mayor — Word MVP

<>>< ><<> ><<> <>>< ><<> <>>< <>><<>

It’s usually better to go the macro route when finding fields because, as you say, the find algorithm that Word uses doesn’t work the way you might hope with fields.

But if you know exactly what the fields contain, you can specify a search pattern that will probably work (however not in wildcard mode).

For example, if you want to look for figure number field pairs such as

{ STYLEREF 1 s }.{ SEQ Figure * ARABIC s 1 }

(which would typically be the same set of fields everywhere in the document)

If you only really need to look for the following:

{ STYLEREF 1 s }.<any field>

you could ensure that field codes are displayed and search for

^d STYLEREF 1 s ^21.^d

or

^19 STYLEREF 1 s ^21.^19

If you need to be more precise, you can spell out the second field as well.

«^d» only works for finding the field beginning, not the field end.

It’s a shame that ^w wants to find at least 1 whitespace character because otherwise it would be more robust to look for

^19^wSTYLEREF^w1^ws^w^21.^19

Perhaps someone else knows how to work around that without using wildcards?

Many of the applications that you use every day will have a way for you to search through the text that appears on the screen or in the file that is currently open. Often this will be accessible by choosing a “Find” option from a menu or using the Ctrl + F keyboard shortcut.

Sometimes you will make a mistake when you are typing a document, but you won’t realize your mistake until long after it has already happened.

Going back and manually fixing that mistake can be time-consuming if it has happened a lot, and you may inadvertently miss something.

Fortunately, Word 2013 has a function that allows you to automatically replace every occurrence of a word in your document with a different word. So if you incorrectly used a term multiple times throughout a document, it is a simple matter to replace that word with a different one.

  1. Click the Home tab.
  2. Click the Replace button in the Editing section of the ribbon.
  3. Type the word to replace into the Find what field.
  4. Type the replacement word to use into the Replace with field, then click the Replace All button.

Our guide continues below with more information on replacing all occurrences of a word in Microsoft Word, including pictures of these steps.

How to Replace a Word with a Different Word in Word 2013 (Guide with Pictures)

We are going to cover the very basics of this feature first, then we are going to show you how to customize it a little bit to prevent Word from accidentally replacing parts of a Word that match your criteria.

Step 1: Open your document in Word 2013.

Step 2: Click the Home tab at the top of the window.

click the home tab

Step 3: Click the Replace button in the Editing section on the right side of the ribbon.

click the replace button

Step 4: Type the word that you want to replace into the Find what field, then type the word that you want to use to replace it into the Replace with field. Click the Replace All button at the bottom of the window when you are finished.

how to replace word occurrences in word 2013

The problem you may run into with the feature is that it is replacing that text string, not just occurrences of the word. So if you are replacing “xxx” with “yyy”, but you have the word “xxxa” in your document, then it will also be changed to “yyya”. Fortunately, there is a way to prevent this.

How to Use Find and Replace in Word 2013 to Only Replace Whole Words

The steps in this section are going to modify the previous section slightly to prevent Word from replacing text strings that appear within other words.

Step 1: Click the More button at the bottom of the Find and Replace window.

click the mroe button at the bottom of the find and replace window

Step 2: Click the box to the left of Find whole words only.

customize the replace action

You will notice that there are many other options on this menu that you can also use to customize the replace function. For example, using the Match case option would only replace words that were in the same case. This option allows you to replace instances of “John” while ignoring “JOHN”.

This tool becomes even more powerful when you include the Format and Special options at the bottom of the window, which allows you to find and replace information based on the type of formatting that has been applied to it. This is a very powerful, customizable tool that will let you find and replace in almost any way that you might need.

How Can I Get to the Find and Replace Dialog Box in Microsoft Word 2013?

As we have discussed in earlier sections of this document you will find Word’s find and replace feature if you select the Home tab at the top of the window, then click Replace in the Editing group in the window.

But you can also find and replace text by using the Ctrl + H keyboard shortcut to open the Find and Replace box. When you use this shortcut rather than the Ctrl + F option to find a specific word in your document then the window will open with the Replace tab as the active tab.

This can be a little faster as it cuts out the part of the process where you need to choose Replace if you had selected the Advanced Find option from the menu.

More Information on How to Replace All Occurrences of a Word in Word 2013

The steps in the article above provide you with the means to quickly find and replace a word that appears multiple times within your Microsoft Word document. That assumes that the word is spelled the same way each time, otherwise, Word is going to miss those misspellings.

You may wish to use the spell checker before you do this so that Word can catch spelling mistakes so it doesn’t overlook a misspelled version of the word.

All of the advanced find and replace options that appear on the Find and Replace window after you click More are:

  • Match case
  • Find whole words only
  • Use wildcards
  • Sounds like (English)
  • Find all word forms (English)
  • Match prefix
  • Match suffix
  • Ignore punctuation characters
  • Ignore white-space characters

As you can see, this tool has a lot of different variables that you can apply which will enable you to find and replace almost any string of text or word that you might want to change within your document.

MS Word has been updating both the find and replace option for years to the point where it has become an incredibly powerful and useful way to find text or find words and quickly search through your document content. In newer versions of Word when you click the Find button or press Ctrl + F on your keyboard it will open a Navigation pane at the left side of the window. If you just need to find individual instances of a word or phrase ion long documents then this can be a life saver.

You always have the open to press Ctrl + H to open the Find and Replace window in newer versions of Word, however, if you prefer the replace or find box over the new Navigation pane.

Did you know that there is a freehand drawing tool in Word 2013? Find out how to draw in Word 2013 if you need to add a shape to a drawing that you can’t replicate with one of the other options.

Additional Sources

Matthew Burleigh has been writing tech tutorials since 2008. His writing has appeared on dozens of different websites and been read over 50 million times.

After receiving his Bachelor’s and Master’s degrees in Computer Science he spent several years working in IT management for small businesses. However, he now works full time writing content online and creating websites.

His main writing topics include iPhones, Microsoft Office, Google Apps, Android, and Photoshop, but he has also written about many other tech topics as well.

Read his full bio here.

01

Все кто когда-либо сталкивался с подстановочными символами (Wildcards) знают, что это достаточно убогая попытка реализовать в VBA механизм подобный регулярным выражениям в других более развитых языках. Помимо более скудных возможностей (я уже не говорю о невозможности указания количества «ноль-или-один») данный механизм также ограничен и в сложности выстраиваемых выражений, и те кто пытался решить более-менее сложные задачи не раз сталкивался с ошибкой Поле «Найти» содержит слишком сложное выражение с использованием подстановочных символов. Отсюда и возникла необходимость воспользоваться более могущественным инструментом — регулярными выражениями.

02 VBA

1
2
3
4
5
6
7
8
9
10
11

Dim objRegExp, matches, match

Set objRegExp = CreateObject(«VBScript.RegExp»)

With objRegExp
.Global = True
.IgnoreCase = False
.pattern = «pattern»
End With

03

Здесь, конечно, каждый кодер обрадуется — вызываем Replace и все ок!

04 VBA

1

Set matches = objRegExp.Replace(ActiveDocument.Content, «replacementstring»)

05

Но при запуске, конечно же, будет выдана ошибка. Это связано с тем, что метод Replace объекта VBScript.RegExp принимает на вход первым параметром строковую переменную, а не объект (в нашем случае ActiveDocument.Content), и возвращает этот метод также измененную строку, а не вносит изменение во входящую, отсюда и танцы с бубнами:

06 VBA

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

Set matches = objRegExp.Execute(ActiveDocument.Content)

For Each match In matches
Set matchRange = ActiveDocument.Content
With matchRange.Find
.Text = match.Value
.Replacement.Text = «replacementstring»
.MatchWholeWord = True
.MatchCase = True
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
.Execute Replace:=wdReplaceOne
End With
Next

07

Ну хорошо, скажете вы, ну а если нам нужно переформатировать данные по аналогии с выражениями типа $1-$3-$2 (т. н. «обратные ссылки» в регулярных выражениях), т. е. как к примеру из 926-5562214 получить +7 (926) 556-22-14. Это тоже достаточно просто, здесь они тоже есть — единственное отличие — нумерация найденных групп начинается не с нуля, а единицы — $1. Давайте пока отвлечемся от нашего документа и посмотрим как это можно сделать с обычной строковой переменной:

08 VBA

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

19

Dim objRegExp, matches, match

Set objRegExp = CreateObject(«VBScript.RegExp»)

Dim strSearch As String
Dim strResult As String
strSearch = «Пусть у нас есть несколько телефонов 8495-3584512, 8800-4852620 и, к примеру, 8950-5628585»

With objRegExp
.Global = True
.IgnoreCase = False

.pattern = «8(d{3})-(d{3})(d{2})(d{2})»

End With

strResult = objRegExp.Replace(strSearch, «+7 ($1) $2-$3-$4»)

Debug.Print strResult

09 На заметку:

12 строка выделена для того чтобы подчеркнуть каким образом было разделено указание на подгруппы ($2, $3 и $4), ведь выражение (d{3})(d{2})(d{2}) эквивалентно (d{7}). Но во втором случае, рекурсивный запрос содержал бы все 7 цифр.

Изучайте регулярные выражения!

10

Но поскольку, как уже говорилось выше, вместо входной строки у нас объект ActiveDocument.Content, такой метод не подойдет для работы. Придется пойти на хитрость — объединить два предыдущих кода:

11 VBA

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
27
28
29
30
31
32

Set objRegExp = CreateObject(«VBScript.RegExp»)

With objRegExp
.Global = True
.IgnoreCase = False
.pattern = «8(d{3})-(d{3})(d{2})(d{2})»
End With

Set matches = objRegExp.Execute(ActiveDocument.Content)

Dim strReplacement As String

For Each match In matches
Set matchRange = ActiveDocument.Content

strReplacement = objRegExp.Replace(match.Value, «+7 ($1) $2-$3-$4»)

With matchRange.Find
.Text = match.Value
.Replacement.Text = strReplacement
.MatchWholeWord = True
.MatchCase = True
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
.Execute Replace:=wdReplaceOne
End With
Next

12

Оборачиваем в оболочку-функцию и, вуаля:

13 VBA

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
27
28
29
30
31
32
33
34
35
36
37
38

Sub ВыполнитьГруппуПреобразований_RegExp()
Call Выполнить_RegExp(«8(d{3})-(d{3})(d{2})(d{2})», «+7 ($1) $2-$3-$4»)

End Sub

Sub ВыполнитьГруппуПреобразований_RegExp() …

Private Sub Выполнить_RegExp(pattern As String, patternExpr As String)
Set objRegExp = CreateObject(«VBScript.RegExp»)

With objRegExp
.Global = True
.IgnoreCase = False
.pattern = pattern
End With

Set matches = objRegExp.Execute(ActiveDocument.Content)

Dim strReplacement As String

For Each match In matches
Set matchRange = ActiveDocument.Content

strReplacement = objRegExp.Replace(match.Value, patternExpr)

With matchRange.Find
.Text = match.Value
.Replacement.Text = strReplacement
.MatchWholeWord = True
.MatchCase = True
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
.Execute Replace:=wdReplaceOne
End With
Next
End Sub

Private Sub Выполнить_RegExp(pattern As String, patternExpr As String) …

14

Нельзя умолчать о существовании, к сожалению, некоторых ограничений в синтаксисе регулярных выражений при использовании объекта VBScript.RegExp в VBA. Эти ограничения провоцируют ошибку Run-time error ‘5017’ Application-defined or object-defined error. Вот некоторые из них:

15
  • отсутствуют указатели на начало и конец текста A и Z — вместо этих указателей можно использовать указатель конца текста $;
  • отсутствуют назад- (?<=…) и впередсмотрящие (?=…) указатели (утверждения, lookbehind assertions), равно как и их отрицательные реализации — (?!=…) и (?!…);
  • отсутствует ряд модификаторов.
17

Похожие запросы:

  • Регулярные выражения в MS-Word
  • VBA regular expression, replacing groups
  • Поиск и замена текста с помощью объекта VBScript.RegExp
  • Замена текста в документе при помощи регулярных выражений
  • Regex Capture Groups and Back-References
  • Разработка регулярного выражения для разбора строки с помощью обратных ссылок

Like this post? Please share to your friends:
  • Give the missing part of the word 5 класс
  • Give the meaning of word processing
  • Give the meaning of the word stress
  • Give the meaning get the word
  • Give the english for the following word combinations трогательная история