2012-12-11 143 views
1

Excel中有簡單的VBA宏(2003)。它查看單元格A $ N和B $ N,並將Word文檔文本從B $ N替換爲A $ N。VBA宏:Excel到Word文本替換

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 

問題:在Word文檔中這個腳本只能選擇文本,但不要替換。沒有建議?

+1

你有我的尺寸和使用oCell而不是 –

回答

2

首先,我希望你有參考Word對象庫活動: Reference to Word

的腳本對子級實際工作,我做了一些小的修改,並有這方面的工作,包括更換:

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

優秀的建議! Ms Excel和MS Office庫鏈接到項目,但MS Word - 沒有。 – potapuff

+0

現在好了! –

0

使用Excel VBA 7.0和Word 14.0對象library With .Selection塊需要稍微修改

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