[英]VBA Excel/Word Find and Replace
我正在開發一個 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
我怎樣才能讓它做我想做的事?
你做后期綁定,所以 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
問候
阿克塞爾
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.