Перейти к основному содержанию

Как найти и заменить несколько слов одновременно в документе Word?

Word предоставляет функцию «Найти и заменить», чтобы найти все вхождения слова или фразы и одновременно заменить их новым словом. Но если вы хотите найти и заменить разные слова одновременно, эта встроенная функция не поможет. В этой статье мы говорим о методе VBA для поиска и замены нескольких разных слов одновременно в документе Word.

Найти и заменить несколько слов одновременно в Word с кодом VBA
Легко находите и заменяйте несколько слов одновременно в Word с помощью удивительной функции


Найти и заменить несколько слов одновременно в Word с кодом VBA

Пожалуйста, сделайте следующее, чтобы найти и заменить несколько слов одновременно в документе Word.

1. Откройте документ Word, который хотите найти и заменить несколько слов одновременно, затем нажмите другой + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.

2. в Microsoft Visual Basic для приложений окна, нажмите Вставить > Модуль. Затем скопируйте ниже код VBA в окно модуля.

Код VBA: поиск и замена нескольких слов одновременно в Word

Sub FindAndReplaceMultiItems()
'Update by ExtendOffice 2018/10/25
    Dim xFind As String
    Dim xReplace As String
    Dim xFindArr, xReplaceArr
    Dim I As Long
    Application.ScreenUpdating = False
    xFind = InputBox("Enter items to be found here,seperated by comma: ", "Kutools for Word")
    xReplace = InputBox("Enter new items here, seperated by comma: ", "Kutools for Word")
    xFindArr = Split(xFind, ",")
    xReplaceArr = Split(xReplace, ",")
    If UBound(xFindArr) <> UBound(xReplaceArr) Then
        MsgBox "Find and replace characters must be equal.", vbInformation, "Kutools for Word"
        Exit Sub
    End If
    For I = 0 To UBound(xFindArr)
        Selection.HomeKey Unit:=wdStory
        With Selection.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Text = xFindArr(I)
            .Replacement.Text = xReplaceArr(I)
            .Format = False
            .MatchWholeWord = False
        End With
        Selection.Find.Execute Replace:=wdReplaceAll
    Next
    Application.ScreenUpdating = True
End Sub

3. нажмите F5 ключ для запуска кода.

4. В первом Kutools for Word диалоговом окне введите несколько слов, которые вы найдете и замените, в текстовое поле и разделите их запятыми, затем щелкните OK кнопка. Смотрите скриншот:

5. В секунду Kutools for Word в диалоговом окне введите новые слова, которыми вы замените (эти слова также необходимо разделять запятыми), а затем щелкните OK .

Примечание: В этом случае все «КТЕ» в этом документе будет заменен на «Новый», и «КТО» и «KTW» будет заменено на "Контрольная работа" и "Конец". Пожалуйста, измените их под свои нужды.


Легко находите и заменяйте несколько слов одновременно в Word с помощью удивительной функции

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

Прежде чем применить эту функцию, уделите несколько минут сначала скачайте и установите.

1. Запустите приложение Microsoft Word, нажмите Кутулс Плюс > Пакетный поиск и замена.

2. в Пакетный поиск и замена окна настройте следующим образом.

  • 2.1 щелкните значок кнопка> Добавить файл or Add Folder для добавления одного или нескольких документов, в которых вы найдете и замените несколько слов.
  • 2.2 Щелкните значок Добавить ряд кнопку, чтобы вставить поля поиска и замены. Если вы хотите найти и заменить три разных текста одновременно, создайте три строки.
  • 2.3 В каждой строке введите существующие слова, которые вы замените новым в поле Найдите столбец, а затем введите новые слова в Замените колонка.
  • 2.4 Укажите Тип поиска для каждой строки.
  • 2.5 В Найти в столбец выберите, где применить поиск и замену. Оно включает Основной документ, заголовок и нижний колонтитул в этой секции. Вы можете выбрать один из них, два или все в зависимости от ваших потребностей.
  • 2.6. Нажмите Замените кнопку, чтобы начать операцию. Смотрите скриншот:

Затем в выбранных документах одновременно заменяются конкретные слова.

Наконечник: Вы можете выделить результат цветом фона, указав определенный цвет в Выделите столбец для ряда.

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

Лучшие инструменты для офисной работы

Kutools for Word - Повысьте свой опыт работы со словом с помощью Over 100 Замечательные особенности!

🤖 Kutools AI Помощник: Преобразуйте свое письмо с помощью искусственного интеллекта. Создать контент  /  Переписать текст  /  Обобщение документов  /  Запросить информацию на основе документа, все в Word

📘 Владение документами: Разделить страницы  /  Объединить документы  /  Экспортировать выбранное в различные форматы (PDF/TXT/DOC/HTML...)  /  Пакетное преобразование в PDF  /  Экспортировать страницы как изображения  /  Печать нескольких файлов одновременно...

Редактирование содержания: Пакетный поиск и замена через несколько файлов  /  Изменить размер всех изображений  /  Транспонировать строки и столбцы таблицы  /  Преобразовать таблицу в текст...

🧹 Легкая очистка: Убрать Дополнительные места  /  Разрывы разделов  /  Все заголовки  /  Текстовые поля  /  Гиперссылки  / Чтобы получить дополнительные инструменты для удаления, посетите наш Удалить группу...

Креативные вставки: Вставлять Разделители тысяч  /  Флажки  /  радио кнопки  /  QR код  /  Штрих-код  /  Таблица диагональных линий  /  Заголовок уравнения  /  Заголовок изображения  /  Заголовок таблицы  /  Несколько изображений  / Узнайте больше в Вставить группу...

???? Точный выбор: Точно определить конкретные страницы  /  Эта таблица  /  формы  /  заголовки абзацев  / Улучшите навигацию с помощью БОЛЕЕ Выберите функции...

Звездные улучшения: Быстро перемещайтесь в любое место  /  автоматическая вставка повторяющегося текста  /  плавно переключаться между окнами документов  /  11 инструментов преобразования...

👉 Хотите попробовать эти функции? Kutools for Word предлагает 60-дневная бесплатная пробная версия, без ограничений! 🚀
 
Comments (23)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
The VBA script you provide here seems to work only for Latin characters; is there some workaround to get special characters to work.
I work with Sanskrit, which used the Devanagari script, similar to Hindi. (1) The VBA does not accept the Devanagai font nor does it find the Latin characters with diacriticals. For example: It fails miserably if I search for mūlādhāra (मूलाधार). It doesn't seem to recognize the ū or ā, for example, and the Devanagari is a complete loss.

Moreover, does the script recognize spaces between words? If not, how do I get them in there?

Thank you!
This comment was minimized by the moderator on the site
Chào bạn, có cách nào thay thế RẤT NHIỀU cụm từ bằng RẤT NHIỀU cụm từ khác (nhập từng cụm từ rất mất thời gian) bằng cách m lập một file trong đó có 2 cột, 1 cột là cụm từ nguồn và cột 2 là cụm từ đích được không? rất cám ơn bạn.
This comment was minimized by the moderator on the site
Hi Nguyễn Phúc Lâm,
I recommand you apply the Batch Find and Replace feature of Kutools for Word (the second method in this post) to solve this problem.
In the Find and Replace dialog box, after creating the two columns you need, you can save the current settings as a scenaria for future use.
https://www.extendoffice.com/images/stories/comments/comment-picture-zxm/find_and_replace.png
This comment was minimized by the moderator on the site
Cám ơn Crystal, cách này có thể áp dụng với một số lượng nhỏ các cụm từ, nếu với số lượng các cụm từ lớn (hơn 1000, hơn 10000.. cụm từ) thì rất khó để có thể nhập thủ công. Vậy có cách nào khác không bạn? Cám ơn bạn đã trả lời
This comment was minimized by the moderator on the site
Hi Nguyễn Phúc Lâm,
Temporarily unable to deal with this problem with VBA code as it is a bit complex. This feature will be considered for upgrade in the next release. Sorry for the inconvenience.
This comment was minimized by the moderator on the site
Thanks for the project, Could you make it the way we can also replace letters in words. For example if i want to change Dollar as DoLLar it does not function.
This comment was minimized by the moderator on the site
In the first instruction (Find And Replace Multiple Words At The Same Time In Word With VBA Code), it does not find instances where the word to be replaced falls in the middle of a word (For example, .com following a website name). Can this be modified to do so?
This comment was minimized by the moderator on the site
What if I'm trying to replace commas?
This comment was minimized by the moderator on the site
The VBA code can't help to replace commas. You can apply Kutools to achieve.
This comment was minimized by the moderator on the site
After hitting Replace it just goes to Preview and doesn't do anything further.
This comment was minimized by the moderator on the site
Hi Ajs,All required words have been successfully replaced at once after hitting the Replace button. It goes to the Preview tab to help you know how many words have been successfully replaced. After that, close the dialog box.
This comment was minimized by the moderator on the site
Hi! First, congratulations for your work: this macro is very useful and interesting! I would like, neverthless, you help me with one thing. I am a proofreader and would like the replacements would highlithed in green or red color. How can I do this? Is there a code line I could use?
This comment was minimized by the moderator on the site
Hi, The Batch Find and Replace feature of Kutools for Word can perfectly solve your problem, you can have a try.
This comment was minimized by the moderator on the site
Hi how can this macro be revised to take more key words? I have about 170 words that I wold like to find and replace
This comment was minimized by the moderator on the site
Hi JM,
After running the code, a Kutools for Excel dialog box will pop up, please enter the keywords you will find and separate them with commas.
This comment was minimized by the moderator on the site
How to find and select multiple words at the same time
This comment was minimized by the moderator on the site
Hi,
After running the code, a Kutools for Excel dialog box will pop up, please enter the keywords you will find and separate them with commas.
This comment was minimized by the moderator on the site
Hi, This works well with English Words. Now I am doing a document where I translate English to Gujarati. So, when I apply this, (Find English Words) and (Replace with Gujarati words), it does change but it appears like "???". Doesn't show the Gujarati word but just question marks? Any further help? Please.
This comment was minimized by the moderator on the site
I'm have a similar problem with Sanskrit, not only the Devanagari script but also the English/Latin diacriticals on the special characters like ā, ū, ṛ, ṁ, ṃ, etc. Any suggestions for a workable fix?
This comment was minimized by the moderator on the site
Hello Shailesh, facing the same issue. Did you find a solution to it. Am also trying to figure out how to change from Chinese to English.
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations