Find and replace in word macro

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

Thanks Harry Spier, even though I had to modify your code a little — finally it works great!

Sub FindReplaceAnywhere()

Dim pOldFontName As String
Dim pNewFontName As String
Dim rngStory As Word.Range
Dim lngJunk As Long
Dim oShp As Shape

pOldFontName = "FontDoe"  'replace with the font you want to replace
pNewFontName = "Font Dolores"  'replace with the font you really need to have in your doc

'Fix the skipped blank Header/Footer problem
lngJunk = ActiveDocument.Sections(1).Headers(1).Range.StoryType
'Iterate through all story types in the current document
For Each rngStory In ActiveDocument.StoryRanges
'Iterate through all linked stories
  Do
  SearchAndReplaceInStory rngStory, pOldFontName, pNewFontName, pFindTxt, pReplaceTxt
  On Error Resume Next
  Select Case rngStory.StoryType
  Case 6, 7, 8, 9, 10, 11
    If rngStory.ShapeRange.Count > 0 Then
      For Each oShp In rngStory.ShapeRange
        If oShp.TextFrame.HasText Then
          SearchAndReplaceInStory oShp.TextFrame.TextRange, pOldFontName, pNewFontName, pFindTxt, pReplaceTxt
        End If
      Next
    End If
  Case Else
    'Do Nothing
  End Select
  On Error GoTo 0
  'Get next linked story (if any)
  Set rngStory = rngStory.NextStoryRange
Loop Until rngStory Is Nothing
Next
End Sub

Sub SearchAndReplaceInStory( _
    ByVal rngStory As Word.Range, _
    ByVal FindFontName As String, _
    ByVal ReplaceFontName As String, _
    ByVal strSearch As String, _
    ByVal strReplace As String)
With rngStory.Find
  .ClearFormatting
  .Replacement.ClearFormatting
  .Forward = True
  .Wrap = wdFindContinue
  .Font.Name = FindFontName
  .Replacement.Font.Name = ReplaceFontName
  .Text = strSearch
  .Replacement.Text = strReplace
  .Execute Replace:=wdReplaceAll
 End With
End Sub

ВикиЧтение

VBA для чайников
Каммингс Стив

Поиск и замена текста с помощью VBA в Word

Хотя это звучит и несколько необычно, но Find — это объект Word VBA. Объекты Find принадлежат диапазонам и выделенным областям. Для обнаружения или форматирования текста с помощью объекта Find вам потребуется выполнить следующие действия.

1. Получите доступ к объекту Find для определенного диапазона или выделенной области. Если вам необходимо просмотреть целый документ, используйте свойство Content объекта Document для получения доступа к соответствующему диапазону, как показано ниже:

ActiveDocument.Content.Find

2. Определить свойства объекта Find в соответствии с тем, что же вы ищете и как именно вы хотите проводить поиск.

3. Вызвать метод Execute объекта Find. Соответствующий пример приведен ниже:

With OpenRange.Find

.Clear Formatting

.Text = «pogosticks»

.Execute

End With

Для свойств, значения которых явно вы задать не можете, объект Find выбирает параметры, использованные последними или те, которые в настоящий момент заданы в диалоговом окне Найти и заменить программы Word. Именно по этой причине вам всегда следует включать метод Clear Formatting перед началом нового поиска- он позволяет убрать все ранее определенные для проведения поиска параметры форматирования.

Работа с найденным текстом

Основная работа метода Execute — обнаружение первого экземпляра искомого текста или форматирования в указанном диапазоне или выделенной области. После выполнения этого метода вам прежде всего следует определить, было ли найдено то, что вы ищете. Для подобной проверки используйте свойство Found объекта Find совместно с инструкцией If…Then, как показано на примере следующей заготовки программного кода:

If .Found = True Then

(выполнение определенных действий с найденным текстом)

Else

(отображение соответствующего сообщения)

End If

Если метол Execute нашел необходимый текст, исходный диапазон или выделенная область переопределяются таким образом, чтобы содержать найденный текст. Это очень важный момент, поскольку это означает, что вы можете работать с найденным текстом посредством свойств и методов исходного объекта. В следующем примере, представляющем собой расширенный вариант первого фрагмента кода из настоящего раздела, инструкция .Parent. Italic = True обращается к родительскому объекту по отношению к объекту Find, т.е. диапазону OpenRange. При выполнении этой инструкции диапазон OpenRange теперь содержит только найденный фрагмент текста, так как только в нем предусмотрено форматирование курсивом:

With OpenRange.Find

.СlearFormatting

.Text = «pogosticks»

If .Found = True Then

.Parent.Italic = True

Else

MsgBox «No pogosticks found.»

End If

End with

Объект Reolacement принадлежит (а значит, является его свойством) объекту Find. При написании кода для операции поиска и замены вам следует задать свойства и выполнить методы объекта Replacement.

Следующий фрагмент кода заменяет все экземпляры фразы pogosticks словом skateboards. Выделенная область изменяется при выполнении критерия поиска, поскольку доступ к объекту Find осуществляется через объект Selection:

With ActiveDocument.Content.Find

.ClearFormatting

.Text = «pogosticks»

With .Replacement

.ClearFormatting

.Text == «skateboards»

End With

.Execute Replace := wdReplaceAll

End With

Обратите внимание на то, что метод Execute может использовать аргумент Replace, предназначенный для контроля за тем, будут ли заменены все обнаруженные экземпляры обнаруженного фрагмента текста, или только первый.

Читайте также

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

Поиск и замена данных
В программе HtmlPad реализована возможность быстрого поиска данных. Этот механизм полезно использовать при работе с большими программными кодами или с большими объемами данных, поскольку поиск требуемой информации вручную (например, путем просмотра

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

Поиск и замена данных
В программе Extra Hide Studio имеется удобный механизм для быстрого поиска и замены данных. Эта возможность особенно актуальна при работе с большими исходными кодами, поскольку поиск данных путем просмотра всего кода может занять слишком много времени, и к

Глава 2 Подготовка текста в Microsoft Word

Глава 2 Подготовка текста в Microsoft Word
• Общие сведения о Word 2007• Основные правила форматирования• Вставка стандартных блоков в документ• Нумерация страниц и колонтитулы• Проверка правописания, поиск синонимов, перевод слов• Сноски и закладки• Настройка параметров

3.1. Поиск и замена фрагментов

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

Поиск и замена текста

Поиск и замена текста
В текстовом редакторе Adobe InDesign можно воспользоваться полезнейшей функцией поиска и замены фрагментов текста. Причем, раз мы имеем дело с программой верстки, найденные фрагменты можно не только заменить другими, но и оформить каким-то образом –

Поиск и замена форматирования

Поиск и замена форматирования
Для поиска текста с определенным форматированием используйте свойства объекта Find, касающиеся форматирования. Они идентичны свойствам, используемым при работе с форматированием диапазона или выделенной области, как я уже отмечал в разделе

Автоматический поиск и замена данных

Автоматический поиск и замена данных
В процессе работы иногда возникает необходимость быстро найти те или иные данные (слово, текстовый фрагмент и т. д.) либо заменить одни данные на другие. Для решения такой задачи в Publisher 2007 реализован механизм автоматического поиска и

Поиск и замена

Поиск и замена
В новой версии Excel был полностью изменен пользовательский интерфейс и расширены функциональные возможности средства Найти и заменить. Теперь можно с помощью одной операции производить поиск и замену по всем листам книги, повторно выполнять запросы поиска

Поиск и замена символов

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

Глава 2 Подготовка текста в Microsoft Word

Глава 2
Подготовка текста в Microsoft Word
Microsoft Word – пожалуй, самая популярная на сегодняшний день программа, предназначенная для работы с текстами. Продукт компании Microsoft обладает всеми необходимыми возможностями, связанными с набором и правкой текстов любой сложности.

5.7. Поиск и замена

5.7. Поиск и замена
В документе можно производить автоматический поиск текста и замену его другим.Поиск и замена ведется по введенному образцу. Если в качестве образца указано слово «ход», то компьютер найдет и слово «пароход», если предварительно не поставить условие, что

13.3.4. Поиск и замена текста

13.3.4. Поиск и замена текста
Как вы уже догадались, окно Найти и заменить используется не только для перехода на нужную страницу. Вкладка Найти используется для поиска текста. Для быстрого доступа к этой вкладке нажмите Ctrl+F или выберите команду меню Правка, Найти. Нажмите

Поиск и замена

Поиск и замена
Для поиска в тексте документа нужного слова или сочетания символов служит окно поиска и замены (рис. 9.19), которое открывается нажатием Ctrl+F. Если надо, чтобы оно сразу открылось как окно замены, используйте сочетание Ctrl+H.

Рис. 9.19. Окно поиска и замены.Для

Поиск и замена фрагментов фильма

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

Поиск и замена текста

Поиск и замена текста
Поиск определенного слова или фразы в большом документе является довольно непростой задачей, но ее можно значительно упростить, если воспользоваться командой Главная ? Редактирование ? Найти. В появившемся окне (рис. 5.20) введите искомый текст и

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

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

Nowadays, I am working with a lot of Unicode text in MS-Word. In documents that I handle, all pieces of the text invariably need editing. And that’s what I do! But there are some commonly occurring mistakes which I have to repeatedly correcting in various documents.

So, I thought it would be great if I could run several find and replace commands in one go. I often use Find and Replace facility of MS Word. Now the question was how to do multiple find and replace operations on one click.

Well, the answer has to involve a macro! Several tasks can be executed in any MS Word document by the way of macros.

A macro is a set of several commands put together in a particular sequence. All you need is to write a macro and then keep running it on the target documents. For multiple find and replace, you can use a module like given below (I found it on Internet):

Sub MultiReplace()
Dim StrOld As String, StrNew As String
Dim RngFind As Range, RngTxt As Range, i As Long
StrOld = "the,quick,brown,fox"
StrNew = "The,Quick,Brown,Fox"
Set RngTxt = Selection.Range
For i = 0 To UBound(Split(StrOld, ","))
  Set RngFind = RngTxt.Duplicate
  With RngFind.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = Split(StrOld, ",")(i)
    .Replacement.Text = Split(StrNew, ",")(i)
    .Format = False
    .MatchWholeWord = True
    .MatchAllWordForms = False
    .MatchWildcards = False
    .Execute Replace:=wdReplaceAll
  End With
Next
End Sub

In this macro program, the comma separated values in StrOld are the items to be replaced. Each item in this list will be replaced by the corresponding value given in StrNew string. Needless to say, both the strings should have equal number of values and obviously the sequence of the values does matter.

You can write this macro by going in the Visual Basic Editor of Microsoft Word.

I keep on writing articles about time saving MS-Word tips. Do subscribe my blog and keep on receiving great tips that will help you achieve greater productivity at work place.

I hope this was useful for you. Please do let me know if you have any questions on this topic. Thank you for using TechWelkin!

Word Find and Replace

The Microsoft Word Find and Replace feature is very powerful and a great time saver for the more skilled user. You can use Find and Replace to locate exact words, phrases and even patterns matching various scenarios.

Let us start with exploring how to do a regular Find and Replace in Word.

Click the Find or Replace buttons in the Home ribbon Editing section

Find and Replace in Word - Replace Button
If you want to Find a word or sentence in your Word file go to the Home ribbon tab and go to the Editing section.

  • If you want to Find click Find
  • If you want to Find and Replace click Replace
  • This will open the Find and Replace window.

    You can also use the CTRL+F keyboard shortcut to Find and the CTRL+H keyboard shortcut to do a Find and Replace.

    If you click More > > you will see the full set of options below:
    Find and Replace expanded window
    The following options are available:

    • Match case – will only find words/sentences that match the letter case (e.g. A vs a)
    • Find whole words only – will only find whole words (if looking for “ate” will only match ” ate “ and not “late”)
    • Use wildcards – allows you to use wildcards (click the Special button for list of wildcard special characters that can be used
    • Sounds like – matches expressions that sound like provided text
    • Find all word forms – matches all words/sentences that match a word form (e.g. “doyle” will also match “doyl” as it sounds similar)
    • Match prefix – match text matching a prefix of a word
    • Match suffix – match text matching a suffixof a word
    • Ignore punctuation characters – will ignore punctionation
    • Ignore white-space characters – will ignore white-space (” “)

    Provide a word, sentence and/or wildcard special characters

    Provide a word/sentence you want to Find in the Find what text field and the word/sentence you want to replace it with in the Replace with text field.

    Below and explanation of key buttons used to Find or Replace text:
    Find and Replace fields explained
    Although Find and Replace is a basic and very easy to use function it is often underestimated. Especially that many users do not know that you can easily use wildcards to replace more complex text patterns.

    Using Wilcards

    Word Wildcard Special Characters
    You can also you wildcards to replace various complex patterns such as sequences of numbers or specific number of occurances, letter cases, characters use to replace any characters and much more. To use wilcards click More > > and select the Use wilcards checkbox.

    On the right you should see all available wildcard characters.

    For more information on Special Characters that can be used in Wildcard Find and Replace read this

    Let us explore some example common scenarios below:

    Match any word made of A-Z characters, any letter case

    <[A-z]@>

    This matches any single word that contains A-z letters.
    The < character indicate the beginning, while > the end of a word. The [A-z] brackets indicate a series of characters, using the hyphen allows you specify the whole range of A-z letters. Lastly the @ character indicates that the previous expression may repeat 0 to any number of times.

    Match an email from the .com domain

    <[A-z,0-9]@@[A-z,0-9]@.com>

    This matches only emails with A-z letters and 0-9 numbers in their login and domain name. Again the [A-z,0-9] bracket specifies we are listing several ranges of acceptable characters, following this with the @ characters tells that any number of these characters may appear. To use the @ character explicitly we need to escape it with a backslash . We use the similar patter for the domain name. Finally notice again I am using < and > to indicate the beginning or end of a word as emails are not separated by spaces.

    Match a phone number split with hyphens

    [0-9]@-[0-9]@-[0-9]@

    The above matches any 3 series of digits separated by hyphens.

    Using Wildcards to Capture and Replace text

    In some cases you will want to not only capture a pattern but replace it with part of its content. For this you need to use Expressions (). Expressions let you mark a specific group in the “Find what” text field, that you want to reuse in your “Replace with” text field. Below a simple example:

    Example: Switch places of 2 numbers

    In this example we have a pattern of numbers separated by hyphens. Let us assume we want to switch places of these two 3-digit numbers.
    Text:

    Some text 123-456, some other text 789-012.
    Something else 345-678

    Find what:

    ([0-9]{3})-([0-9]{3})

    Replace with:

    -

    The resulting Text:

    Some text 456-123, some other text 012-789.
    Something else 678-345

    Example: Replace Email domain

    Imagine you want to replace an email domain from yahoo to gmail on all emails in your Word document. If you didn’t know Expressions you would use wildcards to find a match an manually replace all such cases. However below an example that will replace this automatically:

    All Expressions () are numbered by the sequence in which they are used. This allows us to reference the first part of the email by using the backslash and number 1.

    VBA Find and Replace

    You can also execute a Find and Replace sequence using a VBA Macro:

    Find a single match

    The below procedure will print out all occurances of “Find Me” phrases.

    ActiveDocument.Content.Select
    With Selection.Find
        .Text = "Find Me"
        .Forward = True
        .Execute
    End With
     
    If Selection.Find.Found Then
          Debug.Print "Found: " & Selection.Range 'Print the found match 
    Else
          Debug.Print "Not Found"
    End If
    

    Find all matches

    Below VBA macro will find all emails in a Word document with their mailto hyperlinks. This is a good example of fixing hyperlinks in Word documents.

    ActiveDocument.Content.Select
    Do
      With Selection.Find
          .Text = "<[A-z,0-9]@@[A-z,0-9]@.com>"
          .MatchWildcards = True
          .Forward = True
          .Execute
      End With
     
      If Selection.Find.Found Then
          ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:="mailto:" & Selection.Range
      Else
          Exit Do 'If not found then end the loop
      End If
    Loop
    

    Conclusions

    Here are my main takeaways from using Find and Replace in Microsoft Word

Понравилась статья? Поделить с друзьями:
  • Find a word or phrase in the article for the definitions
  • Find and replace excel что это
  • Find a word or phrase in the article for the definition
  • Find and replace cells excel
  • Find a word or phrase from the text that has a similar meaning