I\'m trying to use VBA to search a folder in my Outlook inbox and have it reply to the most recent email with the given subject. So far I\'ve got the following code:
<
This works, if Word is used in as email editor. Please try following code in the middle part. I assume you copied the specified range before into clipboard.
Inner part:
' needs a reference to the Microsoft Word x.x Object Library
With olReply
.Display
Dim wdDoc As Word.Document
Set wdDoc = .GetInspector.WordEditor
If Not wdDoc Is Nothing Then
With wdDoc.Range
.Collapse wdCollapseStart
.InsertBefore "Hi," & vbCrLf & vbCrLf & _
"here comes my inserted table:" & vbCrLf
.Collapse wdCollapseEnd
.InsertAfter "Best wishes," & vbCrLf & _
"..." & vbCrLf
.Collapse wdCollapseStart
.Paste
'.PasteAndFormat wdChartPicture
'.PasteAndFormat wdFormatPlainText
End With
End If
Set wdDoc = Nothing
End With
If you wonder about the order of inserting text before and after the pasted part: If you paste plain text by .PasteAndFormat wdFormatPlainText
the cursor is not moved after the text. So the a. m. order works fine for me in any paste variant.
If you need to debug the cursor position, just add some .Select
within the With wdDoc.Range
area (for debugging purposes only).
"Full" example for future readers:
Public Sub PasteExcelRangeToEmail()
Dim objOL As Outlook.Application
Dim NewEmail As Outlook.MailItem
Dim wdDoc As Word.Document
Dim wdRange As Word.Range
' get your Outlook object
On Error Resume Next
If objOL Is Nothing Then
Set objOL = GetObject(, "Outlook.Application")
If objOL Is Nothing Then
Set objOL = New Outlook.Application
End If
End If
On Error GoTo 0
Set NewEmail = objOL.CreateItem(olMailItem)
With NewEmail
.To = "info@world"
.Subject = "Concerning ..."
.Display
Set wdDoc = .GetInspector.WordEditor
If Not wdDoc Is Nothing Then
With wdDoc.Range
.Collapse wdCollapseStart
.InsertBefore "Hi there," & vbCrLf & "here's my table:" & vbCrLf
.Collapse wdCollapseEnd
.InsertAfter "Best wishes," & vbCrLf
.Collapse wdCollapseStart
ActiveSheet.Range("A1:C3").Copy
.Paste
'.PasteAndFormat wdChartPicture
'.PasteAndFormat wdFormatPlainText
End With
Set wdDoc = Nothing
End If
'.Send
End With
Set NewEmail = Nothing
Set objOL = Nothing
Application.CutCopyMode = False
End Sub