用Word文档中的复制内容替换新邮件中的关键字

时间:2018-09-20 13:13:14

标签: vba replace outlook ms-word copy-paste

我在此站点上浏览了很多主题,但是找不到解决我问题的方法。

这里是上下文:

我正在尝试从word文档生成带有正文的电子邮件=>在这里没有问题。

在本文档中,有一些关键字需要替换为我从另一个单词复制的内容。

我知道如何粘贴到文档的末尾,但不要用复制的内容替换关键字。

这是我的代码:

Sub DisplayMail()

Dim WDApp As Word.Application
Dim WDDoc As Word.Document
Dim OlApp As Outlook.Application
Dim OlItem As Outlook.MailItem

Set WDObj = ThisWorkbook.Sheets("Modèle").OLEObjects("Objet 1")

WDObj.Activate
WDObj.Object.Application.Visible = False

Set WDApp = GetObject(, "Word.Application")
Set WDDoc = WDApp.ActiveDocument
WDDoc.Content.Copy

Set OlApp = CreateObject("Outlook.application")
OlApp.GetNamespace("MAPI").Logon
Set OlItem = OlApp.CreateItem(olMailItem)
With OlItem
.To = ""
.CC = ""
.BodyFormat = olFormatHTML
.Subject = "test"

Set Editor = .GetInspector.WordEditor
Editor.Content.Select
Editor.Application.Selection.Paste
'this works fine, the email's body now looks like my first word document
  ------------
Set WDObj = ThisWorkbook.Sheets("Sheet2").OLEObjects("Objet 2")
WDObj.Activate
WDObj.Object.Application.Visible = False
Set WDDoc = WDApp.ActiveDocument
WDDoc.Content.Copy
'Copy of the content of my second word document (that's what I want to replace the keyword with)
'Editor.Characters.Last.Select
'Editor.Application.Selection.Paste
'code I use to copy at the end of the email body
------------

------------
With Editor.Content.Find
.Text = "#Keyword#"
.Replacement.Text = "text"
.Forward = True
.Execute Replace:=wdReplaceAll
End With
'with this code I can replace the keyword with Text but not with the content of my second word document
.Display
End With
End Sub

1 个答案:

答案 0 :(得分:0)

要使用剪贴板的内容替换文本,请使用搜索代码:^c

例如(根据问题中发布的代码):

With Editor.Content.Find
  .Text = "#Keyword#"
  .Replacement.Text = "^c"
  .Forward = True
  .Execute Replace:=wdReplaceAll
End With

通过显示“替换”对话框(按Ctrl + H),单击“更多”,然后单击“特殊”,可以找到此类特殊搜索代码的列表。有“查找”和“替换”的列表-在对话框顶部的相应框中单击以获取该框的列表。