VBA宏:Excel到Word文本替换 [英] VBA macros: Excel to Word text replacement

查看:997
本文介绍了VBA宏:Excel到Word文本替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有简单的VBA宏(Excel)(2003)。它查找单元格A $ N和B $ N,并将Word文档文本从B $ N替换为A $ N。

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

问题:在Word文档中,这个脚本只选择文本,但不要做替代EMENT。不要建议?

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

推荐答案

首先,我希望您对Word对象库的引用有效:

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

脚本实际上可以工作,我做了一些小的修改,并且这个工作包括替换:

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

这篇关于VBA宏:Excel到Word文本替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆