Совет. Другие языки - Google-Translated. Вы можете посетить English версия этой ссылки.
Войти
x
or
x
x
Регистрация
x

or

Как искать и заменять несколько файлов словом?

Если у вас несколько десятков файлов слов, содержащих один и тот же контент (например, верхний колонтитул, нижний колонтитул, некоторые специальные слова или номер), вам необходимо заменить один и тот же контент на эти документы в Word. Как вам будет легче сделать это быстро? Конечно, вы можете открывать эти файлы один за другим, чтобы заменить один и тот же контент, но это будет отнимать много времени и хлопотно. Этот учебник покажет вам сложный способ заменить один и тот же контент в нескольких документах Word одновременно.

Поиск и замена текстов в нескольких текстовых документах одновременно с кодом VBA


Объединение / объединение нескольких документов в один легко:

Объединить документы полезности Kutools for Word может помочь вам объединить несколько документов в один быстро. Вам просто нужно:

  • Выберите документы, которые вы объедините в один;
  • Укажите разрыв между каждым объединенным документом;
  • Начните слияние. Смотрите скриншот:

Kutools for Word: с более чем 100 удобными надстройками Word, бесплатно попробовать без ограничений в 30-дни. Скачать и бесплатно пробную версию!

Поиск и замена текстов в нескольких текстовых документах одновременно с кодом VBA

1. Нажмите другой + F11 для открытия Microsoft Visual Basic для приложений окна.

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

Код VBA: поиск и замена одного и того же содержимого на нескольких документах одновременно

Sub CommandButton1_Click()
'Updated by Extendoffice 20180625
Dim xFileDialog As FileDialog, GetStr(1 To 100) As String '100 files is the maximum applying this code
Dim xFindStr As String
Dim xReplaceStr As String
Dim xDoc As Document
On Error Resume Next
Set xFileDialog = Application.FileDialog(msoFileDialogFilePicker)
With xFileDialog
    .Filters.Clear
    .Filters.Add "All WORD File ", "*.docx", 1
    .AllowMultiSelect = True
    i = 1
    If .Show = -1 Then
        For Each stiSelectedItem In .SelectedItems
            GetStr(i) = stiSelectedItem
            i = i + 1
        Next
        i = i - 1
    End If
    Application.ScreenUpdating = False
    xFindStr = InputBox("Find what:", "Kutools for Word", xFindStr)
    xReplaceStr = InputBox("Replace with:", "Kutools for Word", xReplaceStr)
    For j = 1 To i Step 1
        Set xDoc = Documents.Open(FileName:=GetStr(j), Visible:=True)
        Windows(GetStr(j)).Activate
        Selection.Find.ClearFormatting
        Selection.Find.Replacement.ClearFormatting
        With Selection.Find
            .Text = xFindStr  'Find What
            .Replacement.Text = xReplaceStr  'Replace With
            .Forward = True
            .Wrap = wdFindAsk
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchByte = True
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        Selection.Find.Execute Replace:=wdReplaceAll
        Application.Run macroname:="NEWMACROS"
        ActiveDocument.Save
        ActiveWindow.Close
    Next
    Application.ScreenUpdating = True
End With
MsgBox "Operation end, please view", vbInformation
End Sub

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

4. В открытии просмотреть , найдите и выберите документы, которые вы найдете, и замените текст внутри, а затем нажмите OK кнопка. Смотрите скриншот:

5. Во-первых Kutools for Word диалогового окна, введите текст, который вы найдете в документах, в Найти то, что и нажмите OK Кнопка.

6. В секунду Kutools for Word в диалоговом окне введите текст, который вы замените, и нажмите OK Кнопка.

8. Нажмите OK в следующем Microsoft Word чтобы завершить поиск и заменить.

В этом случае все слова «Word» в выбранных документах одновременно заменяются «Excel».


Office Tab - Вкладка Просмотр, редактирование и управление несколькими документами в Word:

Вкладка «Office» предоставляет интерфейс с вкладками в виде веб-браузеров, таких как Google Chrome, новые версии Internet Explorer и Firefox для Microsoft Word. Это будем быть инструментом экономии времени и незаменимым в вашей работе. См. Ниже демо:

Нажмите для бесплатной пробной версии Office Tab!




Рекомендуемые инструменты для повышения производительности Word

Kutools для Word - больше, чем расширенные функции 100 для Word, сэкономьте время 50%

  • Сложные и повторяющиеся операции могут быть выполнены одноразовой обработкой за считанные секунды.
  • Вставьте несколько изображений из папок в документ Word одновременно.
  • Объединяйте и объединяйте несколько файлов Word в разных папках в нужном вам порядке.
  • Разделите текущий документ на отдельные документы в соответствии с заголовком, разрывом раздела или другими критериями.
  • Конвертируйте файлы между Doc и Docx, Docx и PDF, коллекцией инструментов для общих преобразований и выбора и так далее ...
Say something here...
symbols left.
You are guest ( Sign Up? )
or post as a guest, but your post won't be published automatically.
Loading comment... The comment will be refreshed after 00:00.
  • To post as a guest, your comment is unpublished.
    Tiago · 7 months ago
    Is it possible to replace in the headers of the word doc?
    • To post as a guest, your comment is unpublished.
      crystal · 7 months ago
      Hi Tiago,
      Please apply the below VBA code to include the content of headers and footers when finding and replacing texts in multiple documents at once.

      Sub CommandButton1_Click()
      'Updated by Extendoffice 20180625
      Dim xFileDialog As FileDialog, GetStr(1 To 100) As String '100 files is the maximum applying this code
      Dim xFindStr As String
      Dim xReplaceStr As String
      Dim xDoc As Document
      On Error Resume Next
      Set xFileDialog = Application.FileDialog(msoFileDialogFilePicker)
      With xFileDialog
      .Filters.Clear
      .Filters.Add "All WORD File ", "*.docx", 1
      .AllowMultiSelect = True
      i = 1
      If .Show = -1 Then
      For Each stiSelectedItem In .SelectedItems
      GetStr(i) = stiSelectedItem
      i = i + 1
      Next
      i = i - 1
      End If
      Application.ScreenUpdating = False
      xFindStr = InputBox("Find what:", "Kutools for Word", xFindStr)
      xReplaceStr = InputBox("Replace with:", "Kutools for Word", xReplaceStr)
      For j = 1 To i Step 1
      Set xDoc = Documents.Open(FileName:=GetStr(j), Visible:=True)
      Windows(GetStr(j)).Activate
      Selection.Find.ClearFormatting
      Selection.Find.Replacement.ClearFormatting
      With Selection.Find
      .Text = xFindStr 'Find What
      .Replacement.Text = xReplaceStr 'Replace With
      .Forward = True
      .Wrap = wdFindAsk
      .Format = False
      .MatchCase = False
      .MatchWholeWord = False
      .MatchByte = True
      .MatchWildcards = False
      .MatchSoundsLike = False
      .MatchAllWordForms = False
      End With
      Selection.Find.Execute Replace:=wdReplaceAll
      Application.Run macroname:="NEWMACROS"
      If MsgBox("Do you want to replace texts in headers and footers too? ", vbYesNo, "Kutools for Word") = vbYes Then
      ActiveWindow.View.SplitSpecial = wdPanePrimaryFooter
      Selection.Find.Execute Replace:=wdReplaceAll
      Application.Run macroname:="NEWMACROS"
      ActiveWindow.View.SplitSpecial = wdPanePrimaryHeader
      Selection.Find.Execute Replace:=wdReplaceAll
      Application.Run macroname:="NEWMACROS"
      End If
      ActiveDocument.Save
      ActiveWindow.Close
      Next
      Application.ScreenUpdating = True
      End With
      MsgBox "Operation end, please view", vbInformation
      End Sub
  • To post as a guest, your comment is unpublished.
    dsadasd · 7 months ago
    Is that possible to replace in the header of the word doc?
  • To post as a guest, your comment is unpublished.
    martinadam · 10 months ago
    Thanks for sharing this information with us.
    Word search and replace tool
  • To post as a guest, your comment is unpublished.
    nathalie · 1 years ago
    Works perfectly but is there a similar macro to change text in the header! because this does not work with this version!
    thanks
    • To post as a guest, your comment is unpublished.
      crystal · 7 months ago
      Hi,
      Please apply the below VBA code to include the content of headers and footers when finding and replacing texts in multiple documents at once.

      Sub CommandButton1_Click()
      'Updated by Extendoffice 20180625
      Dim xFileDialog As FileDialog, GetStr(1 To 100) As String '100 files is the maximum applying this code
      Dim xFindStr As String
      Dim xReplaceStr As String
      Dim xDoc As Document
      On Error Resume Next
      Set xFileDialog = Application.FileDialog(msoFileDialogFilePicker)
      With xFileDialog
      .Filters.Clear
      .Filters.Add "All WORD File ", "*.docx", 1
      .AllowMultiSelect = True
      i = 1
      If .Show = -1 Then
      For Each stiSelectedItem In .SelectedItems
      GetStr(i) = stiSelectedItem
      i = i + 1
      Next
      i = i - 1
      End If
      Application.ScreenUpdating = False
      xFindStr = InputBox("Find what:", "Kutools for Word", xFindStr)
      xReplaceStr = InputBox("Replace with:", "Kutools for Word", xReplaceStr)
      For j = 1 To i Step 1
      Set xDoc = Documents.Open(FileName:=GetStr(j), Visible:=True)
      Windows(GetStr(j)).Activate
      Selection.Find.ClearFormatting
      Selection.Find.Replacement.ClearFormatting
      With Selection.Find
      .Text = xFindStr 'Find What
      .Replacement.Text = xReplaceStr 'Replace With
      .Forward = True
      .Wrap = wdFindAsk
      .Format = False
      .MatchCase = False
      .MatchWholeWord = False
      .MatchByte = True
      .MatchWildcards = False
      .MatchSoundsLike = False
      .MatchAllWordForms = False
      End With
      Selection.Find.Execute Replace:=wdReplaceAll
      Application.Run macroname:="NEWMACROS"
      If MsgBox("Do you want to replace texts in headers and footers too? ", vbYesNo, "Kutools for Word") = vbYes Then
      ActiveWindow.View.SplitSpecial = wdPanePrimaryFooter
      Selection.Find.Execute Replace:=wdReplaceAll
      Application.Run macroname:="NEWMACROS"
      ActiveWindow.View.SplitSpecial = wdPanePrimaryHeader
      Selection.Find.Execute Replace:=wdReplaceAll
      Application.Run macroname:="NEWMACROS"
      End If
      ActiveDocument.Save
      ActiveWindow.Close
      Next
      Application.ScreenUpdating = True
      End With
      MsgBox "Operation end, please view", vbInformation
      End Sub
  • To post as a guest, your comment is unpublished.
    blds · 1 years ago
    Doesn't work for me on footers. e.g find FFSOSxxxx and replace with GGSOSxxxx, i can see this code is great for others pls help. :(
  • To post as a guest, your comment is unpublished.
    Kath · 1 years ago
    Hi there, is there a code for replacing with text that is multiple sentences, with bullet points and quotation marks in MS word using this code - which is fantastic !
  • To post as a guest, your comment is unpublished.
    Rouzbeh · 1 years ago
    hi, i want to replace a number but i guess the problem that it's not working is that the number is not written in english it's in Persian. I would be so thankfull if someone can help me with it.
    • To post as a guest, your comment is unpublished.
      Rouzbeh · 1 years ago
      sorry, i was wrong. the problem is that the number is in the header and it seems that the trick is not working in header. if i open one of the files and activate the header then run the module it works but just in that specific file ,even if i select all the files. thanks again.
  • To post as a guest, your comment is unpublished.
    Rav · 1 years ago
    Hi, I new to VBA. I am able to get the data updated for only single file. How to select multiple files when the VBA script opens up ? The question might be simple to few, but it will help. Since i need to update a string in 175+ plus word files. Appreciate your quick response. Thanks ...
    • To post as a guest, your comment is unpublished.
      Asi · 1 years ago
      Put your files in one folder and select them all with a shift key. Hope this works.
  • To post as a guest, your comment is unpublished.
    darshan Jain · 1 years ago
    Hi
    this code is only editing 7 documents at a time... why?
  • To post as a guest, your comment is unpublished.
    Bryce · 2 years ago
    I really appreciated this post. Thank you. It allowed me to spend 10 minutes implementing something that saved several hours of work.
  • To post as a guest, your comment is unpublished.
    Tomuko Suryadi · 2 years ago
    What if I want to find and replace multiple sentences in multiple documents?
  • To post as a guest, your comment is unpublished.
    3Cees · 2 years ago
    Thank you so much. You win the internet!

    This has saved me amending 360 documents.

    You're my favourite :)
  • To post as a guest, your comment is unpublished.
    WAK · 2 years ago
    worked like a charm for me. Thanks a billion!
  • To post as a guest, your comment is unpublished.
    CC · 2 years ago
    Merlin 4099, I am having trouble with the following portion of your code. I am new to VBA.:

    ' --------------- --------------- --------------- ----------
    ' Beginning Header Updates
    ' --------------- --------------- --------------- ----------
    Windows(GetStr(j)).Activate
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.Cle arFormatting

    If ActiveWindow.View.SplitSpecialwdPane None Then
    ActiveWindow.Panes(2).Close
    End If

    If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
    ActivePane.View .Type = wdOutlineView Then

    Can anyone help me? I think I fixed most
    • To post as a guest, your comment is unpublished.
      blue_crayon · 2 years ago
      Was figuring out this issue myself, today.

      First, make sure you fix the line:

      Selection.Find.Replacement.Cle arFormatting

      To be:

      Selection.Find.Replacement.ClearFormatting

      Then, change the following line:

      If ActiveWindow.View.SplitSpecialwdPane None Then

      To look like this:

      If ActiveWindow.View.SplitSpecial <> wdPaneNone Then


      The code should look like this in the end:

      Windows(GetStr(j)).Activate
      Selection.Find.ClearFormatting
      Selection.Find.Replacement.ClearFormatting

      If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
      ActiveWindow.Panes(2).Close
      End If

      If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
      ActivePane.View.Type = wdOutlineView Then
      ActiveWindow.ActivePane.View.Type = wdPrintView
      End If
  • To post as a guest, your comment is unpublished.
    CC · 2 years ago
    Merlin4099, I am having trouble with the following portion of your code:

    ' --------------- --------------- --------------- ----------
    ' Beginning Header Updates
    ' --------------- --------------- --------------- ----------
    Windows(GetStr(j)).Activate
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.Cle arFormatting

    If ActiveWindow.View.SplitSpecialwdPane None Then
    ActiveWindow.Panes(2).Close
    End If

    If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
    ActivePane.View .Type = wdOutlineView Then

    Can you or anyone else help me?

    Thanks!
  • To post as a guest, your comment is unpublished.
    DaveW · 2 years ago
    Thanks so much for posting this, absolute lifesaver!

    I notice that there is a line "MatchWildcards = False", which implies that it's possible to use wildcards in the search text - is that possible and, if so, what's the protocol?

    Thanks again!
  • To post as a guest, your comment is unpublished.
    Paul Oz · 2 years ago
    Hi all,
    I am new to the whole VBA thing and I Love love love this code!
    I have 5000+ docs to review and if this works it will save heaps of time!
    I have the code above running however i can see that it does not cater for replacing text in footers, Only headers and the body of the doc.
    Can anyone assist in extending this to the entire document.
    P.S. not sure if this is relevant but the list of words that i need to replace is the same for headers, footers and the body...
    Any help would really be appreciated!
    • To post as a guest, your comment is unpublished.
      blue_crayon · 2 years ago
      You can edit the footer by using almost identical code that the header uses. Copy everything from "Begin Header Updates" to "End Header Updates" and paste it directly after.

      Then, in this pasted section, find the word "wdSeekCurrentPageHeader" and change it to "wdSeekCurrentPageFooter".
  • To post as a guest, your comment is unpublished.
    Terence · 2 years ago
    Out of interest what does the line: Application.Run macroname:="NEW MACROS" do?
    The rest of the code makes sense to me (used to VBA in Excel) but I can't figure out why you need to execute another piece of code here.
    Thanks for the great tool though.
  • To post as a guest, your comment is unpublished.
    Mike · 3 years ago
    This macro was amazing..is there any code to update multiple excel files,spss files.also is there is any macro to update the header and footer on multiple word documents .

    Any help is appreciated .thanks !
  • To post as a guest, your comment is unpublished.
    Tracy · 3 years ago
    Just brilliant, saved me lots of time, thank you
  • To post as a guest, your comment is unpublished.
    Exis · 3 years ago
    You can always try a 3rd party tool to do this which makes it very easy: www.officefindreplace.com
  • To post as a guest, your comment is unpublished.
    Nick · 3 years ago
    I am trying to add an entire section to a document that has three lines, bolding, and bullet points. Is there a way to keep that formatting when running the macro?
  • To post as a guest, your comment is unpublished.
    Tali1953 · 3 years ago
    To Merlin4099
    You have just saved my life (... time...) with you code !
    THANK YOU !!!
  • To post as a guest, your comment is unpublished.
    Jelena · 3 years ago
    Is it possible to change code and search and replace photo in multiply files?
  • To post as a guest, your comment is unpublished.
    fatma · 3 years ago
    this was sooo helpful, thank you very much! I have just changed the contents in 90 word files. This is amazing! Just one more tip: at the beginning close all open word documents but one of your file to be change.
  • To post as a guest, your comment is unpublished.
    Exis,LLC · 3 years ago
    You can use a program such as [url]www.officefindreplace.com[/url] to perform the same operation on multiple documents, or multiple operations on the same document. [url]www.officefindreplace.com[/url]
  • To post as a guest, your comment is unpublished.
    Merlin4099 · 4 years ago
    ' --- Beging body text replacemnt 3 ---
    With Selection.Find
    .Text = "leadership" ' Find What
    .Replacement.Text = "supervision" ' Replace With
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchByte = True
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    ' --- End body text replacemnt 3 ---

    Application.Run macroname:="NEWMACROS"
    ActiveDocument.Save
    ActiveWindow.Close
    ' -------------------------------------------------------
    ' End of Body Updates
    ' -------------------------------------------------------
    Next

    Application.ScreenUpdating = True

    End With

    MsgBox "operation end, please view", vbInformation

    End Sub
    • To post as a guest, your comment is unpublished.
      Ravini · 2 years ago
      To Merlin4099
      Wonderful code - thank you!! worked perfectly in executing what I needed.
  • To post as a guest, your comment is unpublished.
    Merlin409 · 4 years ago
    ' --- Beging body text replacemnt 1 ---
    With Selection.Find
    .Text = "Body text 1" ' Find What
    .Replacement.Text = "BT1" ' Replace With
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchByte = True
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    ' --- Beging body text replacemnt 1 ---

    ' --- Beging body text replacemnt 2 ---
    With Selection.Find
    .Text = "membership" ' Find What
    .Replacement.Text = "team members" ' Replace With
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchByte = True
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    ' --- End body text replacemnt 2 ---
  • To post as a guest, your comment is unpublished.
    Merlin409 · 4 years ago
    ' --- Beging header text replacemnt 2 ---
    With Selection.Find
    .Text = "Header String 2" ' Find What
    .Replacement.Text = "HReplacement 2" ' Replace With
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchByte = True
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False

    If .Found = True Then
    ChangeMade = True
    End If

    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    ' --- Beging header text replacemnt 2 ---

    ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
    ' ------------------------------------------------------
    ' End of Header Updates
    ' ------------------------------------------------------


    ' -------------------------------------------------------
    ' Beginning of Body Updates
    ' -------------------------------------------------------
    Windows(GetStr(j)).Activate
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting

    ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ' Delete additional body replacement blocks if
    ' not needed or copy/paste additional blocks if
    ‘ required.
    ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  • To post as a guest, your comment is unpublished.
    Merlin409 · 4 years ago
    ' --- Beging header text replacemnt 1 ---
    With Selection.Find
    .Text = "Header String 1" ' Find What
    .Replacement.Text = "HReplacement 1" ' Replace With
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchByte = True
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False

    If .Found = True Then
    ChangeMade = True
    End If

    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    ' --- End header text replacemnt 1 ---
  • To post as a guest, your comment is unpublished.
    Merlin409 · 4 years ago
    Sub Search_and_Replace()

    ' 500 files is the maximum applying this code
    Dim MyDialog As FileDialog, GetStr(1 To 500) As String

    On Error Resume Next

    Set MyDialog = Application.FileDialog(msoFileDialogFilePicker)

    ' ---------------------------------------------------------------
    ' *.doc? allows processing of *.doc and *.docx files.
    ' ---------------------------------------------------------------
    With MyDialog
    .Filters.Clear
    .Filters.Add "All WORD File ", "*.doc?", 1
    .AllowMultiSelect = True

    i = 1
    If .Show = -1 Then
    For Each stiSelectedItem In .SelectedItems
    GetStr(i) = stiSelectedItem
    i = i + 1
    Next

    i = i - 1
    End If

    Application.ScreenUpdating = False

    For j = 1 To i Step 1
    Set Doc = Documents.Open(FileName:=GetStr(j), Visible:=True)

    ' -------------------------------------------------------
    ' Beginning Header Updates
    ' -------------------------------------------------------
    Windows(GetStr(j)).Activate
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting

    If ActiveWindow.View.SplitSpecial wdPaneNone Then
    ActiveWindow.Panes(2).Close
    End If

    If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
    ActivePane.View.Type = wdOutlineView Then
    ActiveWindow.ActivePane.View.Type = wdPrintView
    End If

    ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
  • To post as a guest, your comment is unpublished.
    Merlin409 · 4 years ago
    I ran across this code while searching with DuckDuckGo. I modified it to suit my needs which were to other requests such as handling multiple search/replace in the header and multiple search/replace in the body. I also modified it handle the older .DOC format and the new .DOCX format. The modified code is pasted below. Feel free to use and improve!

    It is being sent in multiple parts because comments to this site can only be 2000 characters or less.
    ------------------------------------------------------------
  • To post as a guest, your comment is unpublished.
    Milo · 4 years ago
    This code has saved so much time for me... so, thanks!

    One thing though - is there any way to increase the number of words that the macro finds/replaces? I need to find/replace multiple paragraphs at once and the macro seems to have a limit of approximately 200 characters.
  • To post as a guest, your comment is unpublished.
    Mario · 4 years ago
    Is it possible to tweak this macro to perform multiple 'find and replace' stances at once? There are several words and phareses I need to replace and as of now I need to reinsert the VBA code for every instance.

    I'm a noob regarding those things
  • To post as a guest, your comment is unpublished.
    Moh · 4 years ago
    I've been testing it for the last few minutes and it's really a wonder, thank you!

    I need to perform several 'find and replace' routines for several files. Dozens of routines for dozens of files.

    Is there a way to 'save' the module so I don't need to paste it again on the VBA screen every time I need to perform a new routine?
  • To post as a guest, your comment is unpublished.
    Pia · 4 years ago
    I am sorry but I have no idea re the headers or the format. It was not something I needed to include in my code. I had never used this before myself and the code I posted was taken from the original code above and then tweeked using code found in other searches until it worked. I am sorry I cant be of more help.
  • To post as a guest, your comment is unpublished.
    sathena99 · 4 years ago
    Thanks for posting this! I've run a couple tests and gotten it to work for me; however, it's not working on text in headers and footers for some reason. Is there a fix for this?
  • To post as a guest, your comment is unpublished.
    WORDZ · 4 years ago
    Big THX 4 the code... but also have that prblm with the headers... no change

    Thanks in advance
  • To post as a guest, your comment is unpublished.
    Nilesh · 5 years ago
    I want to change the format of the replaces text. i.e. "Pizza" has to be replaced with "[i]Burger[/i]".
    How can it be achieved?
  • To post as a guest, your comment is unpublished.
    Judy · 5 years ago
    Hello,
    This worked great for the word in the body of the document but did not replace the same word in the header. Any ideas.

    Thanks
  • To post as a guest, your comment is unpublished.
    Dani · 5 years ago
    This worked perfectly and saved me so much time. Thank you!
  • To post as a guest, your comment is unpublished.
    Pia · 5 years ago
    It only runs across selected files and files must be in one folder only. This is run as a macro in a word doc. It is run from clicking a button. It only updates word doc's Hope this helps.


    Private Sub CommandButton1_Click()
    Dim MyDialog As FileDialog, GetStr(1 To 100) As String '100 files is the maximum applying this code
    On Error Resume Next
    Set MyDialog = Application.FileDialog(msoFileDialogFilePicker)
    With MyDialog
    .Filters.Clear
    '~~> Change this file extention to the relevant doc type.
    .Filters.Add "All WORD File ", "*.doc", 1
    .AllowMultiSelect = True
    i = 1
    If .Show = -1 Then
    For Each stiSelectedItem In .SelectedItems
    GetStr(i) = stiSelectedItem
    i = i + 1
    Next
    i = i - 1
    End If
    Application.ScreenUpdating = False
    For j = 1 To i Step 1
    Set doc = Documents.Open(FileName:=GetStr(j), Visible:=True)
    Windows(GetStr(j)).Activate
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting

    For i = 1 To doc.Hyperlinks.Count
    'If the hyperlink matches.
    If LCase(doc.Hyperlinks(i).Address) = "http://www.yahoo.co.uk/" Then
    'Change the links address.
    doc.Hyperlinks(i).Address = "https://www.google.co.uk"
    'Change the links display text if desired.
    doc.Hyperlinks(i).TextToDisplay = "www.google.co.uk"
    End If
    Next
    Application.Run macroname:="NEWMACROS"
    ActiveDocument.Save
    ActiveDocument.Close
    Next
    Application.ScreenUpdating = True
    End With
    MsgBox "operation end, please view", vbInformation
    End Sub
  • To post as a guest, your comment is unpublished.
    Pia Wilson · 5 years ago
    You then add one of the following two sections depending on if it is test or hyperlink to be replaced

    '~~> This section if uncommented will replace text - ONLY ONE OF TWO SECTIONS CAN BE UNCOMMENTED AT ONCE


    With Selection.Find
    .Text = "www.google.co.uk" 'Find What
    .Replacement.Text = "www.google.com" 'Replace With
    .Forward = True
    .Wrap = wdFindAsk
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchByte = True
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
    Application.Run macroname:="NEWMACROS"
    ActiveDocument.Save
    ActiveDocument.Close
    Next
    Application.ScreenUpdating = True
    End With
    MsgBox "operation end, please view", vbInformation


    '~~> This section if uncommented will replace hyperlinks
    'For i = 1 To doc.Hyperlinks.Count
    ' 'If the hyperlink matches.
    ' If LCase(doc.Hyperlinks(i).Address) = "http://www.google.co.uk/" Then
    ' 'Change the links address.
    ' doc.Hyperlinks(i).Address = "https://www.google.com"
    ' 'Change the links display text if desired.
    ' doc.Hyperlinks(i).TextToDisplay = "www.google.com"
    ' End If
    ' Next
    'Application.Run macroname:="NEWMACROS"
    'ActiveDocument.Save
    'ActiveDocument.Close
    'Next
    'Application.ScreenUpdating = True
    'End With
    'MsgBox "operation end, please view", vbInformation



    End Sub
    • To post as a guest, your comment is unpublished.
      segarn · 5 years ago
      Hi Pia,
      I am trying to run your script for replacing hyperlinks but am getting errors. Any chance you can post the script for replacing hyperlinks all in 1 piece? I must be messing something up when trying to patch your code together.
  • To post as a guest, your comment is unpublished.
    Pia Wilson · 5 years ago
    This is what finally worked for me. I hope it helps. I added this macro to a word file. It will run the replace any documents selected (you can select as many as you like) when the file dialoge is open. It wont work on sub folders so I did each folder in the file structure individually but it worked.It may not be the best fix but it works at least.


    Private Sub CommandButton1_Click()
    Dim MyDialog As FileDialog, GetStr(1 To 100) As String '100 files is the maximum applying this code
    On Error Resume Next
    Set MyDialog = Application.FileDialog(msoFileDialogFilePicker)
    With MyDialog
    .Filters.Clear
    '~~> Change this file extention to the relevant doc type.
    .Filters.Add "All WORD File ", "*.doc", 1
    .AllowMultiSelect = True
    i = 1
    If .Show = -1 Then
    For Each stiSelectedItem In .SelectedItems
    GetStr(i) = stiSelectedItem
    i = i + 1
    Next
    i = i - 1
    End If
    Application.ScreenUpdating = False
    For j = 1 To i Step 1
    Set doc = Documents.Open(FileName:=GetStr(j), Visible:=True)
    Windows(GetStr(j)).Activate
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    'Section then either one or the other of sections of code to follow.
  • To post as a guest, your comment is unpublished.
    Greg Simonis · 5 years ago
    I still cannot get this to work on my PC running Windows 7.
    When I run it, I get an error msg at the line:
    -Windows(GetStr(j)).Activate
    The error msg. is:
    -Compile error:
    -Sub or Function not defined
    Any idea why? And how to fix it?
  • To post as a guest, your comment is unpublished.
    Muralisk · 5 years ago
    Worked like a charm and it did save a lot of time and effort for me. Thanks.
  • To post as a guest, your comment is unpublished.
    Greg Simonis · 5 years ago
    When I run it, it gets hung up and stops at:
    Application.Run macroname:="NEWMACROS"
    and when I step into it, it tells me I have a Compile error: Named argument not found.
    Now what?
  • To post as a guest, your comment is unpublished.
    Jebidiah Springfield · 5 years ago
    Wow you are a saint for putting this macro together! I am listening to 'Epic Battle Music' on Songza because I am such an amatuer Macro-smith and it's the only way I can make it through the pain and agony of crafting programming spells.

    Anyway, my point I am going to make is a spent a lot of time on Friday troubleshooting the part where you actually put in the text you want to find and putting in the text you want to replace - I did not quite understand this part in terms of where I put my "find" word text and "replace" word text:

    [quote]Note:you can change the Text = "search”, Replacement.Text = "find” to specify the content to be searched and the content to be applied for replacement.
    [/quote]

    I read over this again today and I wish to respectfully clarify for other programming non-initiates - in the section of VBA where you have copied and pasted the original programming language, make sure you put an end ' after the [i]what [/i] and a ' after the [i]with[/i] (see example below) - in my example, I am looking for multiple documents to replace Pizza with Stromboli:

    .Text = "Pizza" 'Find What'
    .Replacement.Text = "Stromboli" 'Replace With'
  • To post as a guest, your comment is unpublished.
    James R · 5 years ago
    Could this VBA technique be adapted to work for Publisher files? For example by changing *.docx to *.pub ?
  • To post as a guest, your comment is unpublished.
    Patrick · 5 years ago
    When you run the macro, the "Open" window will open. Navigate to the folder that contains the files you need to make the change to, then click once on the first one, then, while holding down the "Ctrl" key, click on the other files also requiring the find/replace. If all files in the folder need the action, just press the "Ctrl" and "A" keys. Then click on "Open" or press the "Enter" key, and the macro will begin.

    I should warn you, as I've performed this dozens of times at work: The macro will result in the changes being made only to the *body* of the Word document; headers, footers, and title text/alt-text will be excluded. If you have text in the aforementioned portions that needs replacing, you will have to perform a standard find/replace across individual documents.