Vai al contenuto principale

Come trovare e sostituire il testo nel documento di Word da Excel?

Nel documento di Word, possiamo applicare la funzione Trova e sostituisci per trovare e sostituire rapidamente un testo. Tuttavia, se è necessario trovare e sostituire più testi, inserire il testo uno per uno nella funzione Trova e sostituisci richiederà molto tempo. In questo caso, puoi inserire i testi di ricerca e sostituzione nell'elenco delle celle e con l'aiuto del codice VBA in Excel per eseguire facilmente questo lavoro. In questo articolo, introdurrò anche un'utile funzionalità per trovare e sostituire in batch i testi in più documenti Word.

Trova e sostituisci più testi in un documento Word da Excel con codice VBA

Trova e sostituisci più testi in più documenti Word da Excel con codice VBA

Trova e sostituisci più testi in più documenti Word con una potente funzionalità


Trova e sostituisci più testi in un documento Word da Excel con codice VBA

Se vuoi trovare e sostituire alcuni testi in un solo file Word, il seguente codice VBA può farti un favore.

1. Nel foglio di lavoro di Excel, crea una colonna contenente i testi che desideri trovare e sostituire e un'altra colonna con i testi da sostituire come mostrato nell'immagine sottostante. E poi premere Alt + F11 tasti contemporaneamente per aprire il file Microsoft Visual Basic, Applications Edition finestra.

2. Quindi, fare clic inserire > Moduli, copia e incolla il codice VBA sottostante nella finestra.

Codice VBA: trova e sostituisci più testi in un file Word

Sub replace_texts_range_of_cells()
'Updateby ExtendOffice
Dim xWordApp As Word.Application
Dim xDoc As Word.Document
Dim xRng As Range
Dim I As Integer
Dim xFileDlg As FileDialog
On Error GoTo ExitSub
Set xFileDlg = Application.FileDialog(msoFileDialogFilePicker)
xFileDlg.AllowMultiSelect = False
xFileDlg.Filters.Add "Word Document", "*.docx; *.doc; *.docm"
xFileDlg.FilterIndex = 2
If xFileDlg.Show <> -1 Then GoTo ExitSub
Set xRng = Application.InputBox("Please select the lists of find and replace texts (Press Ctrl key to select two same size ranges):", "Kutools for Excel", , , , , , 8)
If xRng.Areas.Count <> 2 Then
  MsgBox "Please select two columns (press Ctrl key), the two ranges have the same size.", vbInformation + vbOKOnly, "Kutools for Excel"
  GoTo ExitSub
End If
If (xRng.Areas.Item(1).Rows.Count <> xRng.Areas.Item(2).Rows.Count) Or _
  (xRng.Areas.Item(1).Columns.Count <> xRng.Areas.Item(2).Columns.Count) Then
  MsgBox "Please select two columns (press Ctrl key), the two ranges have the same size.", vbInformation + vbOKOnly, "Kutools for Excel"
  GoTo ExitSub
End If
Set xWordApp = CreateObject("Word.application")
xWordApp.Visible = True
Set xDoc = xWordApp.Documents.Open(xFileDlg.SelectedItems.Item(1))
For I = 1 To xRng.Areas.Item(1).Cells.Count
  With xDoc.Application.Selection.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = xRng.Areas.Item(1).Cells.Item(I).Value
    .Replacement.Text = xRng.Areas.Item(2).Cells.Item(I).Value
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchByte = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
  End With
  xDoc.Application.Selection.Find.Execute Replace:=wdReplaceAll
Next
ExitSub:
  Set xRng = Nothing
  Set xFileDlg = Nothing
  Set xWordApp = Nothing
  Set xDoc = Nothing
End Sub

3. Dopo aver incollato il codice, ancora nel file Microsoft Visual Basic, Applications Edition finestra, fare clic Strumenti > Riferimenti, vedi screenshot:

4. Nel saltato fuori Riferimenti - VBAProject finestra di dialogo, selezionare il Libreria di oggetti di Microsoft Word 16.0 dalla casella di riepilogo, vedi screenshot:

5. Clic OK per chiudere la finestra di dialogo e ora premere F5 chiave per eseguire questo codice, nella finestra a comparsa Sfoglia, selezionare il file di Word che si desidera sostituire i testi, vedere screenshot:

6. Quindi, fare clic OK, nella seguente finestra di dialogo, premere Ctrl tasto per selezionare separatamente il testo originale e le nuove celle di testo che desideri utilizzare, vedi screenshot:

7. Quindi fare clic su OK pulsante, ora i testi vengono trovati e sostituiti con i nuovi testi nel documento specificato e anche il file si sta aprendo, dovresti salvarlo per mantenere le modifiche.


Trova e sostituisci più testi in più documenti Word da Excel con codice VBA

Qui creo anche un codice VBA per trovare e sostituire più testi in più documenti Word, per favore fai come segue:

1. Aprire il file Excel che contiene due colonne di valori da sostituire e sostituire come mostrato nell'immagine sottostante, quindi premere Alt + F11 tasti contemporaneamente per aprire il file Microsoft Visual Basic, Applications Edition finestra.

2. Quindi, fare clic inserire > Moduli, copia e incolla il codice VBA sottostante nella finestra.

Codice VBA: trova e sostituisci più testi in più file Word

Sub FindReplaceAcrossMultipleWordDocuments()
'Updateby ExtendOffice
Dim xWordApp As Word.Application
Dim xDoc As Word.Document
Dim xRng As Range
Dim I As Integer
Dim xFolderDlg As FileDialog
Dim xFSO As Scripting.FileSystemObject
Dim xFile As File
On Error GoTo ExitSub
Set xFolderDlg = Application.FileDialog(msoFileDialogFolderPicker)
If xFolderDlg.Show <> -1 Then GoTo ExitSub
Set xRng = Application.InputBox("Please select the lists of find and replace texts (Press Ctrl key to select two same size ranges", "Kutools for Excel", , , , , , 8)
If xRng.Areas.Count <> 2 Then
  MsgBox "Please select two columns (press Ctrl key), the two ranges have the same size", vbInformation + vbOKOnly, "Kutools for Excel"
  GoTo ExitSub
End If
If (xRng.Areas.Item(1).Rows.Count <> xRng.Areas.Item(2).Rows.Count) Or _
  (xRng.Areas.Item(1).Columns.Count <> xRng.Areas.Item(2).Columns.Count) Then
  MsgBox "Please select two columns (press Ctrl key), the two ranges have the same size.", vbInformation + vbOKOnly, "Kutools for Excel"
  GoTo ExitSub
End If
Set xFSO = New Scripting.FileSystemObject
Set xWordApp = CreateObject("Word.application")
xWordApp.Visible = True
For Each xFile In xFSO.GetFolder(xFolderDlg.SelectedItems(1)).Files
  If VBA.InStr(xFile.Type, "Microsoft Word") > 0 Then
    Set xDoc = xWordApp.Documents.Open(xFile.Path)
    For I = 1 To xRng.Areas.Item(1).Cells.Count
      With xDoc.Application.Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = xRng.Areas.Item(1).Cells.Item(I).Value
        .Replacement.Text = xRng.Areas.Item(2).Cells.Item(I).Value
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchByte = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
      End With
      xDoc.Application.Selection.Find.Execute Replace:=wdReplaceAll
    Next
    xDoc.Close wdSaveChanges
  End If
Next
xWordApp.Quit
MsgBox "The Find and Replace has been completed", vbInformation + vbOKOnly, "Kutools for Excel"
ExitSub:
  Set xRng = Nothing
  Set xFolderDlg = Nothing
  Set xWordApp = Nothing
  Set xDoc = Nothing
End Sub

3. Ancora in Microsoft Visual Basic, Applications Edition finestra, fare clic Strumenti > Riferimenti, Nella Riferimenti - VBAProject finestra di dialogo, selezionare il Libreria di oggetti di Microsoft Word 16.0 ed Runtime di script Microsoft opzioni dalla casella di riepilogo, vedere screenshot:

4. Dopo aver controllato le due opzioni, e fare clic OK per chiudere la finestra di dialogo, quindi continuare a premere il tasto F5 chiave per eseguire questo codice, nell'apertura Scopri la nostra gamma di prodotti finestra, scegli una cartella contenente i documenti di Word che desideri eseguire la ricerca e la sostituzione, vedi screenshot:

5. Clic OK pulsante, nella finestra di dialogo visualizzata, premere Ctrl tasto per selezionare separatamente il testo originale e le nuove colonne di testo che desideri utilizzare, vedi screenshot:

6. Infine, fai clic OKe i testi originali vengono sostituiti con quelli nuovi in ​​questi file, dopo il completamento, verrà visualizzata una finestra di dialogo come mostrato nell'immagine seguente:

7. Clic OK per chiudere la finestra di dialogo. E puoi andare ai file per controllare i risultati convertiti.


Trova e sostituisci più testi in più documenti Word con una potente funzionalità

In questa sezione parlerò di come trovare e sostituire in batch i testi in più documenti Word da Word anziché da Excel. Con un potente strumento-Kutools for Word, puoi trovare e sostituire rapidamente i testi specifici e sostituirli con nuovi testi nel file principale, intestazione, piè di pagina, commenti, ecc. ed evidenziare i risultati di cui hai bisogno.

1. Aprire un file di Word, quindi fare clic Kutools Plus > Trova e sostituisci in batch, vedi screenshot:

2. In aperto Trova e sostituisci in batch finestra di dialogo, eseguire le seguenti operazioni:

  • Clicchi Aggiungi pulsante per aggiungere i file di Word in cui si desidera trovare e sostituire i testi;
  • Nel riquadro sinistro, fare clic Aggiungi riga dal nastro superiore;
  • Nel campo inserito, inserisci il testo originale e il nuovo testo in Trovare ed sostituire colonne separatamente che si desidera trovare e sostituire. Inoltre, puoi specificare un colore per evidenziare i testi sostituiti di cui hai bisogno.

3. Dopo aver creato i criteri di ricerca, fare clic su sostituire pulsante per andare al Anteprima del risultato scheda per visualizzare i risultati di ricerca e sostituzione. Vedi screenshot:

4. Quindi, fare clic Chiudi e viene visualizzata una finestra di messaggio per ricordare all'utente se si desidera salvare questo scenario, fare clic su per salvarlo e fare clic su Non per ignorarlo, vedi screenshot:

Suggerimenti:: Questa funzione può anche aiutare a realizzare le seguenti operazioni:
  • Trova e sostituisci caratteri speciali in più documenti di Word;
  • Trova e sostituisci più stringhe con una formattazione specifica in più documenti Word;
  • Trova e sostituisci più stringhe in più file txt/htm/html.

Fare clic per conoscere informazioni più dettagliate su questa funzione...

I migliori strumenti per la produttività in ufficio

🤖 Assistente AI di Kutools: Rivoluziona l'analisi dei dati basandosi su: Esecuzione intelligente   |  Genera codice  |  Crea formule personalizzate  |  Analizzare i dati e generare grafici  |  Richiama le funzioni di Kutools...
Funzioni popolari: Trova, evidenzia o identifica i duplicati   |  Elimina righe vuote   |  Combina colonne o celle senza perdere dati   |   Round senza formula ...
Super ricerca: VLookup a criteri multipli    VLookup a valori multipli  |   VLookup su più fogli   |   Ricerca fuzzy ....
Elenco a discesa avanzato: Crea rapidamente un elenco a discesa   |  Elenco a discesa dipendente   |  Elenco a discesa a selezione multipla ....
Gestore di colonna: Aggiungi un numero specifico di colonne  |  Sposta colonne  |  Attiva/disattiva lo stato di visibilità delle colonne nascoste  |  Confronta intervalli e colonne ...
Funzionalità in primo piano: Messa a fuoco della griglia   |  Vista di progettazione   |   Grande barra delle formule    Gestore di cartelle di lavoro e fogli   |  Resource Library (Testo automatico)   |  Date picker   |  Combina fogli di lavoro   |  Crittografa/decrittografa le celle    Invia e-mail per elenco   |  Super filtro   |   Filtro speciale (filtro grassetto/corsivo/barrato...) ...
I 15 migliori set di strumenti12 Testo Strumenti (aggiungi testo, Rimuovi personaggi, ...)   |   50+ Grafico Tipi (Diagramma di Gantt, ...)   |   40+ Pratico Formule (Calcola l'età in base al compleanno, ...)   |   19 Inserimento Strumenti (Inserisci il codice QR, Inserisci immagine dal percorso, ...)   |   12 Conversione Strumenti (Numeri in parole, Conversione di valuta, ...)   |   7 Unisci e dividi Strumenti (Combina righe avanzate, Celle divise, ...)   |   ... e altro ancora

Potenzia le tue competenze di Excel con Kutools per Excel e sperimenta l'efficienza come mai prima d'ora. Kutools per Excel offre oltre 300 funzionalità avanzate per aumentare la produttività e risparmiare tempo.  Fai clic qui per ottenere la funzionalità di cui hai più bisogno...

Descrizione


Office Tab porta l'interfaccia a schede in Office e semplifica notevolmente il tuo lavoro

  • Abilita la modifica e la lettura a schede in Word, Excel, PowerPoint, Publisher, Access, Visio e Project.
  • Apri e crea più documenti in nuove schede della stessa finestra, piuttosto che in nuove finestre.
  • Aumenta la produttività del 50% e riduce ogni giorno centinaia di clic del mouse!
Comments (10)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
This works great, thank you! Is there a way to make the replacement text carry hyperlinks over? ie - if you have a hyperlinked replacement in the excel sheet, it is still hyperlinked in the Word doc?

Thanks!
This comment was minimized by the moderator on the site
Is there a way too modify this too find text and create hyperlink on the text from another column where i have the links already created? It worked correctly as a find and replace for me. Thanks
This comment was minimized by the moderator on the site
Hi,

I am wondering how this can be modified to also find and replace text in footnotes?

Thanks!
This comment was minimized by the moderator on the site
Hello, Nate,
If you want to find and replace the text in footnotes at the same time, maybe the Kutools for Word's Batch Find and Replace feature can help you.
You just need to check Main document and Footnotes from the Find in section, see below image:
https://www.extendoffice.com/images/stories/comments/comment-skyyang/2023-comment/doc-find-replace-word.png
This comment was minimized by the moderator on the site
It doesn't work.

Compile error: User-defined type not defined
This comment was minimized by the moderator on the site
Hello, Param
The code works well.
Maybe, you didn't check Microsoft Word 16.0 Object Library from the References – VBAProject dialog box.
It means that you may miss the Step 3 and Step 4 of this article.
Please try again, if you still have any other problem, please comment here.
https://www.extendoffice.com/images/stories/comments/comment-skyyang/2023-comment/doc-find-replace-word-file-excel.png
This comment was minimized by the moderator on the site
Sorry for the overdue reply. I have replied before, but my reply dissapeared somehow. You're right, the code does work well. But it replaced nothing when I tried it on a file with more than 80,000 lines.
This comment was minimized by the moderator on the site
Hello, Param
I have tested the code, it works well in my Word docuent which contains 140,000 lines.
Do you mind to upload your attachment here for testing?
Or you can apply our Kutools for Word's Batch Find and Replace feature, it can help you with ease.
Thank you!
This comment was minimized by the moderator on the site
Greetings,
the first code :
VBA code: Find and replace multiple texts in one Word file

thows error : compile error user defined type not defined
https://i.imgur.com/FZPBy4I.png
This comment was minimized by the moderator on the site
Hello, Erik
The code works well.
Maybe, you didn't check Microsoft Word 16.0 Object Library from the References – VBAProject dialog box.
It means that you may miss the Step 3 and Step 4 of this article.
Please try again, if you still have any other problem, please comment here.

https://www.extendoffice.com/images/stories/comments/comment-skyyang/2023-comment/doc-find-replace-word-file-excel.png
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations