简体   繁体   中英

Multiple find and replace in MS Word from a list in MS Excel

Hi I really hope you can help me as I've been trying to do this for a while with not a lot of luck.

I have a list in Excel, say, file 1 (say, A1 - B10, 2 columns of words - the words in column A are the ones to be replaced by the ones in column B).

I have a document in word, say, file 2, which I want to run the words in the excel file so that every appearance of any words which are in column A of the excel file is replaced by the corresponding words in column B.

I would really appreciate any help you could give me, thank you so much.

If I understood you right, you want to replace Words in your Word Document with Words listed in your Excel File. If so, this macro should do the trick(Macro for MS Word):

Function findAndReplace()
Dim xlApp As Object
Dim xlWB As Object
Dim xlWS As Object

Dim i As Integer, j As Integer
Dim lastRow As Integer

'Set Objects
Set xlApp = CreateObject("Excel.Application")
Set xlWB = xlApp.Workbooks.Open("PATH TO EXCEL FILE") 'Replace String with path to Excel File
Set xlWS = xlWB.Worksheets("Name of Worksheet") 'Replace String with your Worksheet Name

'get last row of excel file
lastRow = xlWS.UsedRange.SpecialCells(xlCellTypeLastCell).Row

'loop through all words in Word Document
For i = 1 To ThisDocument.Words.Count - 1 Step 1

    'Loop through cells in Excel File
    For j = 1 To lastRow Step 1

        'Replace Word value in Column B of Excel File
        ThisDocument.Words(i) = Replace(ThisDocument.Words(i), xlWS.Cells(j, 1).Value, xlWS.Cells(j, 2).Value)
    Next j
Next i

'Close Excel and Cleanup
Set xlWS = Nothing
xlWB.Close True
Set xlWB = Nothing
xlApp.Quit
Set xlApp = Nothing
End Function

If I understood you wrong, please give us more detail on what you are trying to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM