VBA Find and Replace in word based on Database in Excel

 ̄綄美尐妖づ 提交于 2019-12-04 21:06:41

The following code needs the reference to the MS Word 14.0 Object Library or whatever is the equivalent on your end. If you don't want early binding, it's up to you to convert it to late binding.

Sub FindReplaceInWord()

    Dim Wbk As Workbook: Set Wbk = ThisWorkbook
    Dim Wrd As New Word.Application
    Dim Dict As Object
    Dim RefList As Range, RefElem As Range

    Wrd.Visible = True
    Dim WDoc As Document
    Set WDoc = Wrd.Documents.Open("C:\xxx\Doc1.docx") 'Modify as necessary.

    Set Dict = CreateObject("Scripting.Dictionary")
    Set RefList = Wbk.Sheets("Sheet1").Range("A1:A3") 'Modify as necessary.

    With Dict
        For Each RefElem In RefList
            If Not .Exists(RefElem) And Not IsEmpty(RefElem) Then
                .Add RefElem.Value, RefElem.Offset(0, 1).Value
            End If
        Next RefElem
    End With

    For Each Key In Dict
        With WDoc.Content.Find
            .Execute FindText:=Key, ReplaceWith:=Dict(Key)
        End With
    Next Key

    'Enable the following three if you want.
    'WDoc.Save
    'WDoc.Close
    'Wrd.Quit

End Sub

Screenshots:

Word Document (before running code)

Reference List in Excel

Word Document (after running code)

Let us know if this helps.

EDIT:

For reference, the code doesn't have problems with your list. I think it's something else altogether. See my screenshot.

As you can see, using Debug.Print Key, Dict(Key) shows it's safe. I have modified the code above to change something that might be causing this. :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!