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
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
Массовый поиск и замена в документах MS Office (Word и Excel)
Имеется большое количество документов Word или Excel и в каждом документе нужно
изменить несколько фраз. В каждом документе через замену (Найти и заменить ) это слишком долго.
Решение:
- Вариант с использованием макроса
- В виде приложения
a) для Microsoft Excel:
Скопировать макрос в папку с файлами, запустить макрос, задать условия замены, заключая их в кавычки.
выбрать любой файл из папки.
Программа пройдётся по всем листам всех книг (*.xls;*.xlsx) в этой папке,
и поменяет текст в заданной графе. Недостатком способа очевиден –
замена производится только в указанной графе.
Скачать макрос можно по ссылке
б) для Microsoft Word:
Создать новый документ Word, открыть редактор Microsoft VBA, добавить
новый модуль, скопировать текст процедуры ниже. О том как создать макрос более подробно написано
здесь.
При выполнении макроса нужно выбрать файлы, данные в которых подлежат замене:
Что изменить и на что изменить прописывается в теле макроса:
что_заменить = «123»
чем_заменить = «1234»
Сам макрос:
Для документов Word подойдет @Text Replacer — бecплaтнaя пpoгpaммa для быcтpoгo пoиcкa и зaмeны
тeкcтa в фaйлax из выбpaннoй пaпки и влoжeнныx пoдпaпoк.
Работает с дoкумeнтaми тeкcтoвoгo peдaктopa Word: *.doc, *.docx, *.rtf, фaйлaми тeкcтoвoгo фopмaтa:
*.txt, *.ini, *.html, *.php и дp., paбoтa c кoтopыми вoзмoжнa чepeз cтaндapтный Блoкнoт Windows.
Вce фaйлы дpугиx типoв oбpaбaтывaютcя пpoгpaммoй кaк тeкcтoвыe.
Пpoгpaммoй пoддepживaeтcя пoиcк и зaмeнa мнoгocтpoчныx фpaгмeнтoв тeкcтa c учeтoм peгиcтpa и
игнopиpуeмыx cимвoлoв — тaкиx кaк пpoбeлы и пepeвoды cтpoки (windows / *nix).
Программа бесплатная, скачать можно по
ссылке
с официального сайта программы
Не пробуйте @Text Replacer для документов Excel – программа их портит!
Для документов Excel попробуйте FireBall.exe – небольшую программу, не требующую установки.
Файлы Excel необходимо скопировать в папку с FireBall.exe.
В ходе работы программа создает новые файлы, добавляя к названию приставку new.
Скачать программу можно по
ссылке
На просторах интернета нашел вот такой макрос
Visual Basic | ||
|
Данный макрос делает замену текста во всем документе и даже в колонтитулах, что для меня очень удобно. Но в маем случае нужен вариант когда нужно ввести текст на который необходимо заменить.
Я вставлял в .Replacement.Text = «ооо» вот так .Replacement.Text = InputBox(«введите № «), и окно выскакивал постоянно, сколько замен он бы не делал, и в каждом я набирал текст замены.
Можно ли сделать так, что бы я ввел один раз и он далее подставлял везде это.
Заранее спасибо.
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]