【问题标题】:VBA Excel/Word Find and ReplaceVBA Excel/Word 查找和替换
【发布时间】:2014-10-12 09:49:40
【问题描述】:

我正在开发一个 Excel 工作表,用于在 Word 文档中搜索特定实例(A 列)并将其替换为单元格 B 中的实例。

我只想更改与搜索条件匹配的第一个实例,并继续通过列循环到下一个实例。

我已经写了下面的代码。

如果我使用“wdReplaceAll”,它将替换 Word 文档中的所有特定实例。 如果我使用 wdReplaceOne”,代码将在第一次更改后中断。

VBA 代码:

Sub Replace()

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:\Users\Rui.Fernandes\Arquivo Rui Fernandes\On.me Documentação\Construção\Documentos Obra Tipo\PGC.10.Ed.1 - Auditorias Internas.doc"

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

For oCell = 1 To 10
    from_text = Sheets("PTAct").Range("A" & oCell).Value
    to_text = Sheets("PTAct").Range("B" & 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 oCell

End sub

我怎样才能让它做我想做的事?

【问题讨论】:

    标签: excel vba ms-word


    【解决方案1】:

    您执行后期绑定,因此 wdReplaceAll 和 wdReplaceOne 不会是您所期望的。在 Word VBA 帮助中查找 WdReplace 枚举及其值。

    Sub Replace()
    
    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:\Users\axel\Documents\replacetest.docx"
    
    Set WA = CreateObject("Word.Application")
    WA.Documents.Open (pathh)
    WA.Visible = True
    
    For oCell = 1 To 10
        from_text = Sheets("PTAct").Range("A" & oCell).Value
        to_text = Sheets("PTAct").Range("B" & oCell).Value
        With WA.ActiveDocument
            Set myRange = .Content
            With myRange.Find
                .Execute FindText:=from_text, ReplaceWith:=to_text, Replace:=1
            End With
        End With
    Next oCell
    
    End Sub
    

    问候

    阿克塞尔

    【讨论】:

      猜你喜欢
      • 2018-01-18
      • 2012-03-08
      • 1970-01-01
      • 2013-07-15
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 2018-11-11
      • 2014-04-06
      相关资源
      最近更新 更多