Search code examples
excelvbaemailoutlook

Add cell value and a selection to mail


I am looking to add a cell value and a selection of a pivot table to my generated email body.

I have an Excel workbook with cells allowing me to fill in certain values ​​from my email (example: .To, .CC, Subject and the body).

In my .Body, I want two things.
The first is a value from a cell containing text. This text is generated thanks to the selection of values ​​in the sheet (example: If I put YES in front of cell A1, then I have A1 in my cell E19.) As a result, I generate the result of several cases in a single cell). Related to this generation, my Range value in oObjetWord.Range(0) cannot be defined, because it varies.
Secondly, I have a pivot table that displays the detailed values ​​of a sheet. I want the text generated in cell E19 and the pivot table to appear in the following order: Text then table.

Sub MailSoir()
Dim OutApp As Object
Set OutApp = CreateObject("Outlook.Application")

Dim OutMail As Object
Set OutMail = OutApp.CreateItem(0)

With OutMail
    Dim oObjetWord As Object 
    Set oObjetWord = .GetInspector.WordEditor 
    Selection.Copy
    .To = Worksheets("Soir").Range("E10") 
    .CC = Worksheets("Soir").Range("E13") 
    .Subject = Worksheets("Soir").Range("E16")

    .Body = Worksheets("Soir").Range("E19")
    oObjetWord.Range(0).Paste

    .Display
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub

I tried to increase the range, but since it varies depending on the text selection, this is not possible.

The result I currently have is that my table is displayed over the text and I cannot get the two to coexist in my email.
I would like to have my cell value then my selection afterwards.


Solution

  • Try this part of code instead of oObjetWord.Range(0).Paste

        With oObjetWord
            .Content.Paragraphs.Add
            .Paragraphs.Last.Range.Paste
        End With
    

    It adds a new paragraph at the end of the document/mail - and then pastes to this last para.