Search code examples
vbareplaceoutlookms-wordcopy-paste

Replace Keyword in a new mail with copied content from a word document


I've browse a lot of subject on this site but can't find a solution for my issue.

Here the context :

I'm trying to generate an email with a body from a word document => no issue here.

In this document there is keywords that I want replace with content that I copied from another word.

I konw how to paste at the end of the document but not replace the keyword with a copied content.

Here my code :

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

Solution

  • In order to replace text using the content of the clipboard use the search code: ^c

    For example (from the code posted in the question):

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

    You can find a list of such special search codes by displaying the "Replace" dialog box (press Ctrl+H), clicking "More" then clicking "Special". There are lists for "Find" as well as for "Replace" - click in the corresponding box at the top of the dialog to get the list for that box.