Hi, I am trying to create an email in outlook using VBA.
In the email i want to include text and a formatted table from the spreadhseet.
In addition i want to add an image/shape to the BOTTOM of the email, but I can't seem to get it to land there.
Here is the code i have managed to put together.
Any help much appreciated. I have spent many hours trying to figure it with no luck.
THANKS
In the email i want to include text and a formatted table from the spreadhseet.
In addition i want to add an image/shape to the BOTTOM of the email, but I can't seem to get it to land there.
Here is the code i have managed to put together.
Any help much appreciated. I have spent many hours trying to figure it with no luck.
THANKS
VBA Code:
Sub emailer()
Set oOlApp = CreateObject("Outlook.Application")
Set oOlMItem = oOlApp.CreateItem(olMailItem)
Set oWB = ActiveWorkbook
Set oWS = ActiveWorkbook.Worksheets("notes")
With oOlMItem
.Display
.To = "email@email.com"
.Subject = "Subject"
.HTMLBody = "<H3><B>Dear Customer </B></H3>" & RangetoHTML(Sheets("Sheet1").Range("A1:C3").SpecialCells(xlCellTypeVisible))
Set oOlInsp = .GetInspector
Set oWdDoc = oOlInsp.WordEditor ' get Word Document from the MailBody
Set oWdContent = oWdDoc.Content
oWdContent.InsertParagraphBefore
Set oWdRng = oWdDoc.Paragraphs(1).Range
'oWdRng.InsertBefore "This is a test <"
oWdRng.InsertParagraphAfter
oWdRng.InsertParagraphAfter
Set oPic = oWS.Shapes("Picture 3")
oPic.CopyPicture ' oPic is now in Clipboard
Set oWdRng = oWdDoc.Paragraphs(3).Range
oWdRng.Paste ' paste from oPic Clipboard
olFormatHTML = 2
.BodyFormat = olFormatHTML ' change to HTML
End With
End Sub
Function RangetoHTML(rng As Range)
' By Ron de Bruin.
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function