使用 Excel VBA 在 Word 文档中替换和插入文本

问题描述 投票:0回答:1

我想在同一个打开的 Word 文档中替换文本并添加一行。

我尝试了这段代码,但它不起作用。

Sub open_word_replace_text()

Dim book1 As Word.Application
Dim sheet1 As Word.Document

Set book1 = CreateObject("word.application")
book1.Visible = True

Set sheet1 = book1.Documents.Open("Template.docx")

With sheet1.Content.Find
    .Text = "prova"
    .Replacement.ClearFormatting
    .Replacement.Text = (Sheets("Sheet2").Range("A2").Value) & " " &      (Sheets("Sheet2").Range("B2").Value)
    .Wrap = wdFindContinue
    .Execute Replace:=wdReplaceAll
    .Forward = True
End With

'the following part must be write after the replace as new line on the      word document and same paragraph
 
sheet1.Content.Text = (Sheets("Sheet2").Range("C2").Value)

end sub
excel vba
1个回答
0
投票

微软文档:

Selection.TypeText 方法(Word)

Selection.EndKey 方法(Word)

Option Explicit
Sub open_word_replace_text()
    Dim wdApp As Word.Application
    Dim wdDoc As Word.Document
    Dim Sht As Worksheet
    Set Sht = Sheets("Sheet2")
    Set wdApp = CreateObject("word.application")
    wdApp.Visible = True
'    Set wdDoc = wdApp.Documents.Open("Template.docx")
    ' The more reliable way to open file
    Set wdDoc = wdApp.Documents.Open(ThisWorkbook.Path & "\Template.docx")
    With wdDoc.Content.Find
        .ClearFormatting
        .MatchCase = False
        .Forward = True
        .Wrap = wdFindContinue
        .Text = "prova"
        .Replacement.ClearFormatting
        .Replacement.Text = Sht.Range("A2").Value & " " & Sht.Range("B2").Value
        .Execute Replace:=wdReplaceAll
    End With
    'the following part must be write after the replace as new line on the word document and same paragraph
    With wdApp.Selection
        .EndKey Word.wdStory
        .TypeParagraph ' Inserts a new blank paragraph
        .TypeText Sht.Range("C2").Value
    End With
'    wdDoc.Save
'    wdDoc.Close
'    wdApp.Quit
End Sub


更新:

Option Explicit
Sub open_word_replace_text()
    Dim wdApp As Word.Application
    Dim wdDoc As Word.Document
    Dim Sht As Worksheet
    Set Sht = Sheets("Sheet2")
    Set wdApp = CreateObject("word.application")
    wdApp.Visible = True
'    Set wdDoc = wdApp.Documents.Open("Template.docx")
    ' The more reliable way to open file
    Set wdDoc = wdApp.Documents.Open(ThisWorkbook.Path & "\Template.docx")
    With wdDoc.Content.Find
        .ClearFormatting
        .MatchCase = False
        .Forward = True
        .Wrap = wdFindContinue
        .Text = "prova"
        .Replacement.ClearFormatting
        .Replacement.Text = Sht.Range("A2").Value & " " _
            & Sht.Range("B2").Value & _
            Chr(13) & Sht.Range("C2").Value
        .Execute Replace:=wdReplaceAll
    End With
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.