Замена символов word vba

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]

ВикиЧтение

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) введите искомый текст и

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

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

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

In the Microsoft Word VBA editor, I’m trying to write a macro that finds and replaces a certain character with another character only within certain strings of text, not the whole document. For instance, I might want to replace decimal commas with decimal points (not all commas with periods), or a space with a hyphen in certain phrases. A big constraint is that the changes must be tracked via Track Changes, so finding and replacing the whole string of text isn’t an option: Some customers think it looks weird and/or sloppy if I replace their numbers with themselves, and they have also worried that some of their data might have gotten changed. (It might also look like I let my computer make edits for me automatically, which I want to avoid.)

I can already do this clunkily by using Selection.Find to find certain strings (or patterns), doing Selection.Collapse, moving the cursor left or right, deleting a comma, and typing a period. I’m hoping there is a faster way to do this, possibly using ranges, but I have had little success finding or replacing anything using Word’s Range object. Since I want to run several macros that total well over a hundred possible find-and-replace actions for each document, I’d like to streamline them all as much as possible.

What I’ve tried so far

For ease of illustration, I’ll take the specific examples in which I want to find commas within statistical p-values written as «0,05», «0,01», or «0,001» and change them to periods, but not make this change anywhere else. I’m aware that in real life, searching for those strings could catch numbers in the thousands, millions, etc., but these are just simplified examples for learning/illustration purposes.

(1) The following works fine, it just strikes me as slow when done for many different Find strings in every document.

With Selection.Find
    .ClearFormatting
    .Text = "0,05"
    .MatchWholeWord = True
    .MatchWildcards = False
    .Forward = True
    .Wrap = wdFindContinue
End With
Do While Selection.Find.Execute
    Selection.Collapse
    Selection.MoveRight unit:=wdCharacter, count:=1
    Selection.Delete unit:=wdCharacter, count:=1
    Selection.TypeText (".")
Loop

(2) The most promising other way was adapted from VBA Word: I would like to find a phrase, select the words before it, and italicise the text:

Sub RangeTest()
Dim Rng As Range
Dim Fnd As Boolean

Set Rng = Selection.Range

    With Rng.Find
        .ClearFormatting
        .Execute findText:="0,05", Forward:=True, _
                 format:=False, Wrap:=wdFindContinue
        Fnd = .found
    End With

If Fnd = True Then
        With Rng
            .Find.Wrap = wdFindContinue
            .Find.Text = ","
            .Find.Replacement.Text = "."
            .Find.Execute Replace:=wdReplaceOne
        End With
    End If
End Sub

but it replaces the comma with a period in only the first «0,05» in the document, not all of them.

When I change wdReplaceOne to wdReplaceAll, then every comma in the document gets replaced with a period.

When I try every possible combination of wdFindContinue/wdFindStop (both times) and wdReplaceAll/wdReplaceOne, either one comma gets changed to a period or every one in the document does.

When I change the «If…Then» statement do a «Do While…Loop» statement, Word hangs:

Dim Rng As Range
Dim Fnd As Boolean

Set Rng = Selection.Range

    With Rng.Find
        .ClearFormatting
        .Execute findText:="0,05", Forward:=True, _
                 format:=False, Wrap:=wdFindStop
        Fnd = .found
    End With

    Do While Fnd = True
        With Rng
            .Find.Text = ","
            .Find.Replacement.Text = "."
            .Find.Execute Replace:=wdReplaceAll
        End With
    Loop

Is there any way to loop the «If…Then» statement or get the «Do While…Loop» method to work without hanging?

(3) I tried to adapt the code from this page https://www.techrepublic.com/article/macro-trick-how-to-highlight-multiple-search-strings-in-a-word-document/

Sub WordCollectionTest()

Dim Word As Word.Range
Dim WordCollection(2) As String 
Dim Words As Variant

WordCollection(0) = "0,05"
WordCollection(1) = "0,01"
WordCollection(2) = "0,001"

'This macro behaves weirdly if insertions and deletions aren't hidden (more than one period gets inserted).
With ActiveWindow.view
    .ShowInsertionsAndDeletions = False

For Each Word In ActiveDocument.Words
    For Each Words In WordCollection
        With Selection.Find
        .ClearFormatting
        .Text = Words
        .Forward = True
        .Wrap = wdFindContinue
        .MatchWildcards = False
        .MatchWholeWord = True
    End With
    Do While Selection.Find.Execute
        Selection.Find.Text = ","
        Selection.Find.Replacement.Text = "."
        Selection.Find.Execute Replace:=wdReplaceAll
    Loop
Next
Next

End With
End Sub

but this replaces every comma in the document with a period. (It’s also kind of slow.)

(4) I tried putting the Find terms in an array rather than a word collection:

Sub ArrayTest()

Dim vDecimalCommas As Variant
Dim i As Long

vDecimalCommas = Array("0,05", "0,01", "0,001")

'This macro behaves weirdly if insertions and deletions aren't hidden:
With ActiveWindow.view
    .ShowInsertionsAndDeletions = False

For i = LBound(vDecimalCommas) To UBound(vDecimalCommas)
    With Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = vDecimalCommas(i)
        .Forward = True
        .Wrap = wdFindContinue
        .matchcase = False
        .MatchWholeWord = False
        .MatchWildcards = True
    End With
    Do While Selection.Find.Execute
        Selection.Find.Text = ","
        Selection.Find.Replacement.Text = "."
        Selection.Find.Execute Replace:=wdReplaceAll
    Loop
Next

End With
End Sub

but this only replaces the comma with a period in the second of those numbers that it comes across, oddly enough.

I tried a variant of the Array method:

Sub ArrayTest()
For i = LBound(vDecimalCommas) To UBound(vDecimalCommas)
    With Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = ","
        .Replacement.Text = "."
        .Forward = True
        .Wrap = wdFindContinue
        .matchcase = False
        .MatchWholeWord = False
        .MatchWildcards = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
Next

End Sub

But this replaces every comma in the document with a period (which isn’t surprising, since I don’t think the For i statement has any bearing on the Find and Replace commands in this version).

I’ve tried lots of other variants that I haven’t mentioned here. I’ve tried combining the Array method with the Range/Boolean method. I’ve tried every variant I know of of the Find, Selection, For i, For Each, If Then, and Do While commands. And every time, only one comma gets replaced with a period or every one does.

Is there some way to define a range that consists of a certain string of text so that word will find and replace commas with periods within that range, every time, and nowhere else? Is there a way to define many such strings in one array or some other kind of list? Or any other way to find and replace commas with periods only within certain strings? I’m far from an expert, so a tiny variation of one of the above methods might work.

Доброе утро.
Нужен макрос, который заменил бы 1 на 2 в выделенном фрагменте текста.
Макрорекордер записал:

Код
Sub Макрос1()
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "1"
        .Replacement.Text = "2"
        .Forward = True
        .Wrap = wdFindAsk
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

Но этот код меняет НЕ ТОЛЬКО в выделенном тексте, но и дальше.

Подскажите пожалуйста, как исправить код?

Понравилась статья? Поделить с друзьями:
  • Замена символа на символ в excel
  • Замена символа на перенос строки excel
  • Замена символа в тексте excel
  • Замена символа в строке word
  • Замена символа в excel в столбце