VBA Find&更换

时间:2018-04-25 15:07:17

标签: excel vba excel-vba ms-word

我正在使用Excel VBA从电子表格生成word文档。我希望找到并用单个段落替换所有双段落,作为最后一步的一部分。

基本代码:

Dim objWord
Dim objDoc
Dim objSelection

Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
Set objSelection = objWord.Selection

objSelection.TypeText "Test"
objSelection.TypeText (vbCr)
objSelection.TypeText (vbCr)
objWord.Visible = True

查找和替换基本文本作品:

With objWord.ActiveDocument
    Set myRange = .Content
    With myRange.Find
        .Execute FindText:="test", ReplaceWith:="apple", Replace:=2
    End With
End With

查找和替换段落不起作用:

With objWord.ActiveDocument
    Set myRange = .Content
    With myRange.Find
        .Execute FindText:="^^p", ReplaceWith:="^p", Replace:=2
    End With
End With

1 个答案:

答案 0 :(得分:6)

更改

.Execute FindText:="^^p", ReplaceWith:="^p", Replace:=2

.Execute FindText:="^p^p", ReplaceWith:="^p", Replace:=2