VBA Excel/Word 查找和替换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25380975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 04:17:29  来源:igfitidea点击:

VBA Excel/Word Find and Replace

excelvbams-word

提问by user3890641

I'm developing an Excel sheet to search in a Word document for a specific instance (Column A) and replace them by the instance in cell B.

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

I want to change only the first instance that matches the search criteria, and keep looping trough the column to the next instances.

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

I've written the code below.

我已经写了下面的代码。

If I use "wdReplaceAll" it replaces all the specific instance in the Word document. If I use wdReplaceOne" the code will break after the first change.

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

VBA Code:

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

How can I do make it do what I want?

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

回答by Axel Richter

You do late binding, so wdReplaceAll and wdReplaceOne will not be what you expect. Look in Word VBA help for the WdReplace Enumeration and its values.

您进行后期绑定,因此 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

Greetings

你好

Axel

阿克塞尔