1
votes

There is simple VBA macros for Excel (2003). It look to cell A$N and B$N, and replace in Word document text from B$N to A$N.

Sub Макрос1()

Dim pathh As String, i As Integer
pathh = "c:\1.doc"
Dim pathhi As String
Dim from_text As String, to_text As String
Dim WA As Object, WD As Object
Set WA = CreateObject("Word.Application")
WA.Documents.Open (pathh)
WA.Visible = True

For oCell = 1 To 150
    from_text = Range("B" + CStr(oCell)).Value
    to_text = Range("A" + CStr(oCell)).Value
    With WA
        .Activate
        With .Selection.Find
          .ClearFormatting
          .Replacement.ClearFormatting

          .Text = from_text
          .Replacement.Text = to_text
          .Execute Replace:=wdReplaceAll
        End With
    End With
Next
End Sub

Problem: in Word document this script only select text, but don't make replacement. Nay suggestion?

2
you have I dimensioned and use oCell insteadK_B

2 Answers

2
votes

First I expect you to have the reference to the Word object library active: Reference to Word

The the script whould actually work, I made some minor modifications and have this working including replace:

Sub test1()

    Dim pathh As String
    Dim pathhi As String
    Dim oCell  As Integer
    Dim from_text As String, to_text As String
    Dim WA As Object

    pathh = "C:\1.doc"

    Set WA = CreateObject("Word.Application")
    WA.Documents.Open (pathh)
    WA.Visible = True

    For oCell = 1 To 2
        from_text = Sheet2.Range("B" & oCell).Value
        to_text = Sheet2.Range("A" & oCell).Value
        With WA
            .Activate
            With .Selection.Find
              .ClearFormatting
              .Replacement.ClearFormatting

              .Text = from_text
              .Replacement.Text = to_text
              .Execute Replace:=wdReplaceAll
            End With
        End With
    Next
End Sub
0
votes

Using Excel VBA 7.0 and Word 14.0 object library the With .Selection block needs to be modified slightly

            With .Selection.find
            .ClearFormatting
            .Execute FindText:=from_text, ReplaceWith:to_text, replace:=wdReplaceAll
        End With