跳到主要內容

如何從 Excel 中查找和替換 Word 文檔中的文本?

在 Word 文檔中,我們可以應用查找和替換功能快速查找和替換一個文本。 但是,如果需要查找和替換多個文本,將文本逐個輸入到查找和替換功能中會很耗時。 在這種情況下,您可以將查找和替換文本輸入到單元格列表中,並在 Excel 中的 VBA 代碼的幫助下輕鬆完成這項工作。 在本文中,我還將介紹一個有用的功能,可以批量查找和替換多個 Word 文檔中的文本。

使用 VBA 代碼從 Excel 中查找和替換一個 Word 文檔中的多個文本

使用 VBA 代碼從 Excel 中查找和替換多個 Word 文檔中的多個文本

使用強大的功能查找和替換多個 Word 文檔中的多個文本


使用 VBA 代碼從 Excel 中查找和替換一個 Word 文檔中的多個文本

如果您只想在一個 Word 文件中查找和替換某些文本,下面的 VBA 代碼可以幫到您。

1. 在 Excel 工作表中,創建一個包含要查找和替換的文本的列,以及另一個包含要替換的文本的列,如下圖所示。 然後按 Alt + F11 同時打開 Microsoft Visual Basic for Applications 窗口。

2。 然後,點擊 插入 > 模塊,將以下 VBA 代碼複製並粘貼到窗口中。

VBA 代碼:在一個 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. 粘貼代碼後,仍然在 Microsoft Visual Basic for Applications 窗口中,單擊 工具 > 參考,請參見屏幕截圖:

4。 在彈出的 參考– VBAProject 對話框中,選擇 Microsoft Word 16.0對像庫 從列錶框中,看截圖:

5。 點擊 OK 按鈕關閉對話框,現在,按 F5 鍵運行此代碼,在彈出的瀏覽窗口中,選擇要替換文本的 Word 文件,看截圖:

6。 然後,點擊 OK, 在以下對話框中,按 按Ctrl 鍵分別選擇要使用的原始文本和新文本單元格,請參見屏幕截圖:

7。 然後,單擊 OK 按鈕,現在,文本被找到並替換為您指定文檔中的新文本,並且文件也正在打開,您應該保存它以保留更改。


使用 VBA 代碼從 Excel 中查找和替換多個 Word 文檔中的多個文本

在這裡,我還創建了一個 VBA 代碼,用於在多個 Word 文檔中查找和替換多個文本,請這樣做:

1. 打開包含兩列要替換和替換的值的 Excel 文件,如下圖所示,然後按 Alt + F11 同時打開 Microsoft Visual Basic for Applications 窗口。

2。 然後,點擊 插入 > 模塊,將以下 VBA 代碼複製並粘貼到窗口中。

VBA 代碼:在多個 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。 仍在 Microsoft Visual Basic for Applications 窗口中,單擊 工具 > 參考參考– VBAProject 對話框中,選擇 Microsoft Word 16.0對像庫Microsoft腳本運行時 列錶框中的選項,請參見屏幕截圖:

4. 勾選兩個選項後,點擊 OK 關閉對話框,然後繼續按 F5 執行此代碼的關鍵,在開頭 瀏覽 窗口,選擇一個文件夾,其中包含要執行查找和替換的 Word 文檔,看截圖:

5。 點擊 OK 按鈕,在彈出的對話框中,按 按Ctrl 鍵分別選擇要使用的原始文本和新文本列,請參見屏幕截圖:

6。 最後點擊 OK, 並將這些文件中的原始文本替換為新文本,完成後會彈出一個對話框,如下圖所示:

7。 點擊 OK 關閉對話框。 您可以轉到文件來檢查轉換後的結果。


使用強大的功能查找和替換多個 Word 文檔中的多個文本

本節,我將討論如何從 Word 而不是 Excel 中批量查找和替換多個 Word 文檔中的文本。 借助強大的工具——Kutools for Word,您可以快速查找和替換特定文本,並將其替換為主文件、頁眉、頁腳、註釋等中的新文本,並根據需要突出顯示結果。

1. 打開一個 Word 文件,然後單擊 Kutools 加 > 批量查找和替換,請參見屏幕截圖:

2。 在開 批量查找和替換 對話框,請執行以下操作:

  • 點擊 加入 按鈕添加要查找和替換文本的 Word 文件;
  • 在左側窗格中,單擊 添加行 從頂部功能區;
  • 在插入的字段中,將原始文本和新文本輸入到 發現更換 要查找和替換的單獨列。 同樣,您可以根據需要指定一種顏色來突出顯示替換的文本。

3. 創建搜索條件後,單擊 更換 按鈕去 預覽結果 選項卡以查看查找和替換結果。 看截圖:

4。 然後,點擊 關閉 按鈕,會彈出提示框提醒您是否要保存該場景,點擊 保存它,然後單擊 沒有 要忽略它,請參見屏幕截圖:

保養竅門:此功能還可以幫助實現以下操作:
  • 查找和替換多個Word文檔中的特殊字符;
  • 在多個 Word 文檔中查找並替換具有特定格式的多個字符串;
  • 在多個 txt/htm/html 文件中查找和替換多個字符串。

單擊以了解此功能的更多詳細信息...

最佳辦公生產力工具

🤖 Kutools 人工智慧助手:基於以下內容徹底改變數據分析: 智慧執行   |  生成代碼  |  建立自訂公式  |  分析數據並產生圖表  |  呼叫 Kutools 函數...
熱門特色: 尋找、突出顯示或識別重複項   |  刪除空白行   |  合併列或儲存格而不遺失數據   |   沒有公式的回合 ...
超級查詢: 多條件VLookup    多值VLookup  |   跨多個工作表的 VLookup   |   模糊查詢 ....
高級下拉列表: 快速建立下拉列表   |  依賴下拉列表   |  多選下拉列表 ....
欄目經理: 新增特定數量的列  |  移動列  |  切換隱藏列的可見性狀態  |  比較範圍和列 ...
特色功能: 網格焦點   |  設計圖   |   大方程式酒吧    工作簿和工作表管理器   |  資源庫 (自動文字)   |  日期選擇器   |  合併工作表   |  加密/解密單元格    按清單發送電子郵件   |  超級濾鏡   |   特殊過濾器 (過濾粗體/斜體/刪除線...)...
前 15 個工具集12 文本 工具 (添加文本, 刪除字符,...)   |   50+ 圖表 類型 (甘特圖,...)   |   40+ 實用 公式 (根據生日計算年齡,...)   |   19 插入 工具 (插入二維碼, 從路徑插入圖片,...)   |   12 轉化 工具 (數字到單詞, 貨幣兌換,...)   |   7 合併與拆分 工具 (高級合併行, 分裂細胞,...)   |   ... 和更多

使用 Kutools for Excel 增強您的 Excel 技能,體驗前所未有的效率。 Kutools for Excel 提供了 300 多種進階功能來提高生產力並節省時間。  點擊此處獲取您最需要的功能...

產品描述


Office選項卡為Office帶來了選項卡式界面,使您的工作更加輕鬆

  • 在Word,Excel,PowerPoint中啟用選項卡式編輯和閱讀,發布者,Access,Visio和Project。
  • 在同一窗口的新選項卡中而不是在新窗口中打開並創建多個文檔。
  • 將您的工作效率提高 50%,每天為您減少數百次鼠標點擊!
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