【问题标题】:VBA macros: Excel to Word text replacementVBA 宏:Excel 到 Word 文本替换
【发布时间】:2016-06-23 11:50:47
【问题描述】:

有用于 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 文档中此脚本仅选择文本,但不进行替换。没有建议吗?

【问题讨论】:

  • 你已经确定尺寸并改用 oCell

标签: excel vba ms-word


【解决方案1】:

首先,我希望您能够激活对 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

【讨论】:

  • 很好的建议! MS Excel 和 MS Office 库已链接到项目,但 MS Word - 没有。
【解决方案2】:

使用 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

【讨论】:

    猜你喜欢
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多