1

Excel(2003)用の単純なVBAマクロがあります。セルA$NとB$Nを調べ、Word文書のテキストをB$Nから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

問題:Word文書では、このスクリプトはテキストのみを選択し、置換は行いません。いや提案?

4

2 に答える 2

2

まず、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
于 2012-12-11T09:53:49.390 に答える
0

Excel VBA 7.0 および Word 14.0 オブジェクトライブラリを使用 して、With .Selection ブロックを少し変更する必要があります。

            With .Selection.find
            .ClearFormatting
            .Execute FindText:=from_text, ReplaceWith:to_text, replace:=wdReplaceAll
        End With
于 2016-06-23T03:50:47.660 に答える