VBA Find & Replace

2019-07-14 04:46发布

I'm using Excel VBA to generate word documents from a spreadsheet. I want to find and replace all double paragraphs with single paragraphs as part of the last step.

Base code:

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

Finding and replacing basic text works:

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

Finding and replacing paragraphs does NOT work:

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

1条回答
Fickle 薄情
2楼-- · 2019-07-14 04:59

Change

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

to

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

查看更多
登录 后发表回答