The below code runs a macro and creates the jpeg.
How can I change the name of the sheet (ex:"Strategic") for an active sheet. When I copy a sheet the code don't work anymore, because of the reference name.
With OutMail
.SentOnBehalfOfName = "Me#Me.Com"
.Display
.Subject = "Strategic Sales"
.To = "Me#Me.Com"
> Call createJpg("Strategic", "A1:F11", "Quota") '
It's about a code to create an outlook mail objectand embed images
Sub sendMail()
Application.Calculation = xlManual
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Dim TempFilePath As String
'Create a new Microsoft Outlook session
Set appOutlook = CreateObject("outlook.application")
'create a new message
Set Message = appOutlook.CreateItem(olMailItem)
With Message
.Subject = "My mail auto Object"
.HTMLBody = "<span LANG=EN>" _
& "<p class=style2><span LANG=EN><font FACE=Calibri SIZE=3>" _
& "Hello,<br ><br >The weekly dashboard is available " _
& "<br>Find below an overview :<BR>"
'first we create the image as a JPG file
**Call createJpg("Dashboard", "B8:H9", "DashboardFile")**
'we attached the embedded image with a Position at 0 (makes the attachment hidden)
TempFilePath = Environ$("temp") & "\"
.Attachments.Add TempFilePath & "DashboardFile.jpg", olByValue, 0
'Then we add an html <img src=''> link to this image
'Note than you can customize width and height - not mandatory
.HTMLBody = .HTMLBody & "<br><B>WEEKLY REPPORT:</B><br>" _
& "<img src='cid:DashboardFile.jpg'" & "width='814' height='33'><br>" _
& "<br>Best Regards,<br>Ed</font></span>"
.To = "contact1#email.com; contact2#email.com"
.Cc = "contact3#email.com"
.Display
'.Send
End With
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Application.Calculation = xlCalculationAutomatic
End Sub
You need to create createJpg function which transform a range into a jpg file.
Sub createJpg(Namesheet As String, nameRange As String, nameFile As String)
ThisWorkbook.Activate
Worksheets(Namesheet).Activate
Set Plage = ThisWorkbook.Worksheets(Namesheet).Range(nameRange)
Plage.CopyPicture
With ThisWorkbook.Worksheets(Namesheet).ChartObjects.Add(Plage.Left,
Plage.Top, Plage.Width, Plage.Height)
.Activate
.Chart.Paste
.Chart.Export Environ$("temp") & "\" & nameFile & ".jpg", "JPG"
End With
Worksheets(Namesheet).ChartObjects(Worksheets(Namesheet).ChartObjects.Count).Delete
Set Plage = Nothing
End Sub
Related
I have this code that emails a range as a picture via outlook. The problem is that the recipients are getting the outlook error "The linked image cannot be displayed. The file may have been moved, renamed, or deleted. Verify that the link points to the correct file and location."
Anyone know how I can fix this?
Sub RectangleRoundedCorners1_Click()
ActiveSheet.Unprotect Password:="Mortgage1"
Dim TempFilePath As String
Dim xOutApp As Object
Dim xOutMail As Object
Dim xHTMLBody As String
Dim xRg As Range
On Error Resume Next
Set xRg = ActiveSheet.Range("C5:F17")
If xRg Is Nothing Then Exit Sub
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
ActiveSheet.Shapes("Rectangle: Rounded Corners 13").Visible = False
Set xOutApp = CreateObject("outlook.application")
Set xOutMail = xOutApp.CreateItem(olMailItem)
Call createJpg(ActiveSheet.Name, xRg.Address, "DashboardFile")
TempFilePath = Environ$("temp") & "\"
xHTMLBody = "<span LANG=EN>" _
& "<p class=style2><span LANG=EN><font FACE=Calibri SIZE=3>" _
& "<img src='cid:DashboardFile.jpg'>" _
'& "<br> "
StrBody = "<br />" & "<b><FONT SIZE = 5><font color=red>Rates are subject to change
without notice</b></FONT SIZE = 5></font color=red>"
With xOutMail
.Subject = "Bench Mark Rates" & " " & Date
.HTMLBody = xHTMLBody & StrBody
.Attachments.Add TempFilePath & "DashboardFile.jpg", olByValue
.To = "mcerrato#hotmail.com
.cc = "mcerrato#loandepot.com"
.Display
End With
ActiveSheet.Shapes("Rectangle: Rounded Corners 13").Visible = True
ActiveSheet.Protect Password:="Mortgage1"
End Sub
Just try so switch this two lines
As is
.HTMLBody = xHTMLBody & StrBody
.Attachments.Add TempFilePath & "DashboardFile.jpg", olByValue
To be
.Attachments.Add TempFilePath & "DashboardFile.jpg", olByValue
.HTMLBody = xHTMLBody & StrBody
I have been trying to automate an excel daily report including tables and chart into an email body.
I manually select and copy the range and special paste it as a picture into the email body.
I have been trying to automate this part and here's my code:
MailSender = DashboardSheet.Range("S16")
MailDistribution = DashboardSheet.Range("S17")
MailSubject = DashboardSheet.Range("S18")
Set objOutlook = CreateObject("Outlook.Application")
Set objOutlookMsg = objOutlook.CreateItem(0)
MakeJPG = CopyRangeToJPG("Dashboard", "A1:O8")
If MakeJPG = "" Then
MsgBox "Something go wrong, we can't create the mail"
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Exit Sub
End If
On Error Resume Next
With objOutlookMsg
.SentOnBehalfOfName = MailSender
.To = MailDistribution
.CC = MailSender
.Subject = MailSubject
.Attachments.Add (SentFiles_Pathname & TodaySentReport_Name), 1, 0
.HTMLBody = .HTMLBody & "<p>" & MakeJPG & "</p>" _
& "<img src='" & MakeJPG & "'width='750' height='520'>"
.Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set objOutlookMsg = Nothing
Set objOutlook = Nothing
MacroBook.Activate
End Sub
Function CopyRangeToJPG(NameWorksheet As String, RangeAddress As String) As String
Dim PictureRange As Range
With ActiveWorkbook
On Error Resume Next
.Worksheets(NameWorksheet).Activate
Set PictureRange = .Worksheets(NameWorksheet).Range(RangeAddress)
If PictureRange Is Nothing Then
MsgBox "Sorry this is not a correct range"
On Error GoTo 0
Exit Function
End If
PictureRange.CopyPicture xlScreen, xlPicture
With .Worksheets(NameWorksheet).ChartObjects.Add(PictureRange.Left, PictureRange.Top, PictureRange.Width, PictureRange.Height)
.Activate
.Chart.Paste
.Chart.Export FileName:="\\server01\DATA\Data Reporting and Dashboard\Dashboard\Daily\" & "NamePicture.jpg", FilterName:="JPG"
End With
.Worksheets(NameWorksheet).ChartObjects(.Worksheets(NameWorksheet).ChartObjects.Count).Delete
End With
CopyRangeToJPG = "\\server01\DATA\Data Reporting and Dashboard\Dashboard\Daily\" & "NamePicture.jpg"
Set PictureRange = Nothing
End Function
I end up having no picture in the body, just an error message saying:
The linked image cannot be displayed. The file may have been moved, renamed, or deleted. Verify that the link points to the correct file and location.
I then realized that I see no file called NamePicture.jpg in the picture folder. I can't find where the problem comes from.
I am able to add the picture manually to the email body with a copy/special paste but it doesn't work with vba. I tried the solutions I have seen on other related topics, but none works. Has anybody encountered that issue?
See: Embed picture in outlook mail body excel vba
So if you can fix your picture export problem:
'...
.Attachments.Add (SentFiles_Pathname & TodaySentReport_Name), 1, 0
.Attachments.Add MakeJPG, 1, 0 '<#####
.HTMLBody = .HTMLBody & "<p>" & MakeJPG & "</p>" _
& "<img src='cid:NamePicture.jpg' width='750' height='520'>"
'...
I used the code below to copy a range from a file and paste it as a picture on emails, but there's a catch: if you donĀ“t use .display before .send, the picture will not be displayed to the receiver.
Does anyone know a way around this? Just to avoid the outlook window flashing on the screen.
Sub sendMail()
Dim olApp As Object
Dim NewMail As Object
Dim ChartName As String
Dim imgPath As String
Set olApp = CreateObject("Outlook.Application")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
tmpImageName = VBA.Environ$("temp") & "\tempo.jpg"
Workbooks.Open "C:\FilePath\File.xlsm"
Set RangeToSend = Workbooks("File.xlsm").Sheets(Name).Range(" ")
RangeToSend.CopyPicture Appearance:=xlScreen, Format:=xlPicture
Set sht = Sheets.Add
sht.Shapes.AddChart
sht.Shapes.Item(1).Select
Set objChart = ActiveChart
With objChart
.ChartArea.Height = RangeToSend.Height
.ChartArea.Width = RangeToSend.Width
.ChartArea.Fill.Visible = msoFalse
.ChartArea.Border.LineStyle = xlLineStyleNone
.Paste
.Export Filename:=tmpImageName, FilterName:="JPG"
End With
sht.Delete
Workbooks("File.xlsm").Close
Set NewMail = olApp.CreateItem(0)
With NewMail
.Subject = "Latest performance report" ' Replace this with your Subject
.To = "email#email.com" ' Replace it with your actual email
.HTMLBody = "<span LANG=EN>" _
& "<p class=style2><span LANG=EN><font FACE=Calibri SIZE=3>" _
& "Hello, this is the data range that you want:<br> " _
& "<br>" _
& "<img src=" & "'" & tmpImageName & "'/>" _
& "<br>" _
& "<img src=" & "'" & tmpImageName2 & "'/>" _
& "<br>" _
& "<br>Best Regards!</font></span>"
.Display
.Send
Set olApp = Nothing
Set NewMail = Nothing
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End With
End Sub
Looks like you are saving the picture captured in Excel to a disk. And then you are referring to the image in a newly created item body. But the image source still points to the file on your disk. So, the recipient will never get it shown correctly.
Instead, you need to attach a file and then add a reference in the message body.
Const PR_ATTACH_CONTENT_ID = "http://schemas.microsoft.com/mapi/proptag/0x3712001E"
Const PR_ATTACHMENT_HIDDEN = "http://schemas.microsoft.com/mapi/proptag/0x7FFE000B"
...
Set colAttach = mail.Attachments
Set l_Attach = colAttach.Add(path_to_the_file)
Set oPA = l_Attach.PropertyAccessor
oPA.SetProperty PR_ATTACH_CONTENT_ID, "itemID"
oPA.SetProperty PR_ATTACHMENT_HIDDEN, True
Then you can modify the message body in the following way:
.HTMLBody = "<span LANG=EN>" _
& "<p class=style2><span LANG=EN><font FACE=Calibri SIZE=3>" _
& "Hello, this is the data range that you want:<br> " _
& "<br>" _
& "<img src='cid:itemID'/>" _
& "<br>" _
& "<br>Best Regards!</font></span>"
.Send
might be you are able to help me with VBA code.
I got a code that send as PDF part of excel sheet.
Problem is that email is used by many people and sometimes text is confidential. Is there an option to delete email (sent items and deleted items) after email is sent?
Using office 2000
Here is my existing code.
Sub SendDDocs()
Dim IsCreated As Boolean
Dim PdfFile As String, Title As String
Dim OutlApp As Object
Dim rng As Range
Set rng = Range("A1:J103")
Title = Range("o1")
Title = Range("o1").Value & " Confidetial"
PdfFile = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\" & Title & ".pdf"
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
On Error Resume Next
Set OutlApp = GetObject(, "Outlook.Application")
If Err Then
Set OutlApp = CreateObject("Outlook.Application")
IsCreated = True
End If
OutlApp.Visible = True
On Error GoTo 0
With OutlApp.CreateItem(0)
.Subject = Title
.To = "email#email.com"
.CC = "email#email.com"
.Body = "" & vbLf & vbLf _
& "a" & vbLf & vbLf _
& "" & vbLf _
& Application.UserName & vbLf & vbLf
.Attachments.Add PdfFile
Application.Visible = True
.Display
End With
Kill PdfFile
If IsCreated Then OutlApp.Quit
Set OutlApp = Nothing
End Sub
Instead of .Display use
.DeleteAfterSubmit = True
.Send
to not save a copy in sent items.
See MailItem.DeleteAfterSubmit Property (Outlook).
I have a table in Excel that I want to send to a distribution list in Outlook with the table in the email body.
Using MVP Ron de Bruin's examples and a few others on here I've got code that keeps some of the table formatting but doesn't copy the cells colour if it is a gradient (please use the images as reference).
Sub DisplayEmailButton_Click()
Mail_Selection_Range_Outlook_Body
End Sub
Sub Mail_Selection_Range_Outlook_Body()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
On Error Resume Next
Set rng = Sheets("Sheet1").Range("C2:Q18").SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected" & _
vbNewLine & "please correct and try again.", vbOKOnly
Exit Sub
End If
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = "Team01"
.CC = ""
.BCC = ""
.Subject = "Daily Statistics"
.HTMLBody = "Please see attached daily statistics." & vbCrLf &
RangetoHTML(rng)
.Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
Dim TempFile As String, ddo As Long
TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
' Temporary publish the rng range to a htm file
ddo = ActiveWorkbook.DisplayDrawingObjects
ActiveWorkbook.DisplayDrawingObjects = xlHide
With ActiveWorkbook.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=ActiveSheet.Name, _
Source:=Union(rng, rng).Address, _
HtmlType:=xlHtmlStatic)
.Publish True
.Delete
End With
ActiveWorkbook.DisplayDrawingObjects = ddo
'Read all data from the htm file into RangetoHTML
With
CreateObject("Scripting.FileSystemObject").GetFile(TempFile)
.OpenAsTextStream(1, -2)
RangetoHTML = Replace(.ReadAll, "align=center x:publishsource=", "align=left
x:publishsource=")
.Close
End With
'Delete the htm file we used in this function
Kill TempFile
End Function
As Tim suggested I was expecting way too much from that procedure (Thank you, Tim, for the advice!) so I looked into a workaround. If the range is saved as a picture then it keeps all the formatting and the picture can then easily be attached to an email or displayed in the body of the email.
To save as a picture:
Dim Wb As ThisWorkbook
Dim Ws As Worksheet
Dim Ch As Chart
Set Rng = Ws.Range("A1:G18")
Set Ch = Charts.Add
Ch.Location xlLocationAsObject, "Sheet2"
Set Ch = ActiveChart
ActiveChart.Parent.Name = "StatsTemp"
ActiveSheet.ChartObjects("StatsTemp").Height = Rng.Height
ActiveSheet.ChartObjects("StatsTemp").Width = Rng.Width
Rng.CopyPicture xlScreen, xlBitmap
Ch.Paste
Ch.Export Environ("UserProfile") & "\Desktop" & "\" & Format("TempImage") & ".jpg"
Worksheets("Sheet2").ChartObjects("StatsTemp").Delete
Worksheets("Sheet1").Activate
The above code saves the range as an image "TempImage.JPG" to the users desktop by creating a new chart on sheet 2, pasting the range to the chart then saves the chart as an image and deletes the chart.
To attach the picture to an email in the email body:
Dim StrBody As String
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
StrBody = "Some text here." & "<br>"
On Error Resume Next
With OutMail
.to = "email address"
.CC = ""
.BCC = ""
.Subject = "Email Subject"
.HTMLBody = StrBody & "<img src = '" & Environ("userProfile") &
"\desktop\TempImage.jpg'>"
.Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
The above code creates an email using Microsoft Outlook which contains the saved image file in the email body and displays the email.
The image can be deleted after using:
Kill Environ("UserProfile") & "\Desktop" & "\TempImage.jpg"
Hopefully, this will be of some use to someone!
Credit to Ron de Bruin Microsoft Office MVP for his WinTips!