Pasting to Outlook from Excel - Outlook Screen Updating - excel

I have found the code to paste a chart from excel to outlook here on stack over flow.
This works fine but The issue is the outlook creating new email and pasting procedure is getting displayed on the screen. Is there any way to disable or make this to background?
Sub Mail_Range()
Dim Sht As Excel.Worksheet
Set Sht = ThisWorkbook.ActiveSheet
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Dim rng As Range
Set rng = Sht.Range("A5:W20")
rng.Copy
Dim OutApp As Object
Set OutApp = CreateObject("Outlook.Application")
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Dim OutMail As Object
Set OutMail = OutApp.CreateItem(0)
Dim vInspector As Object
Set vInspector = OutMail.GetInspector
Dim wEditor As Object
Set wEditor = vInspector.WordEditor
With OutMail
.TO = "xxx.xxx.com"
.CC = ""
.Subject = Sht.Range("A5").Value
.GetInspector
wEditor.Paragraphs(1).Range.Text = "This is an auto generated e-mail" & vbCr
wEditor.Paragraphs(2).Range.Paste
.send
End With
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Application.CutCopyMode = False
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
When I'm using
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
after outlook application creation my pasting code doesn't work. Im getting an email with no content.

Dim OutApp As Object
Set OutApp = CreateObject("Outlook.Application")
With Application <<<---- change to OutApp
.ScreenUpdating = False
.EnableEvents = False
End With

If your problem is that you don't want to see the whole procedure of the mail, but turning the ScreenUpdating to false shows you a blank image, here is my code for dealing this:
Call AhorroMemoria(False)
Imagen.CopyPicture xlScreen, xlBitmap
With wsM.ChartObjects.Add(Imagen.Left - Imagen.Left * 0.15, Imagen.Top - Imagen.Top * 0.15, _
Imagen.Width - Imagen.Width * 0.15, Imagen.Height - Imagen.Height * 0.15)
.Activate
wsM.Shapes("Gráfico 1").Line.Visible = msoFalse
.Chart.Paste
.Chart.Export wb.Path & "\" & Servicio & Contador & ".jpg", "JPG"
End With
Call AhorroMemoria(True)
Call AhorroMemoria(False) turns on everything, screenupdating, enablevents and so... I do that just when copying the image as you can see on the code, then I turn it all off again on the Call AhorroMemoria(True).
Hope it helps.

Thanks all for helping me out. All your codes helped in some way. But i have found more simpler code from Microsoft here. I'm not sure which versions will support this and it has any other challenges. For now this works for me in Office 2016.
I'm getting an email envelope for brief amount of time in excel but no issues as the accidental edit can't be done in this method. In the original method accidental edit was possible during the paste function is running.
Also this code seamlessly emailing charts on the excel sheet.
Option Explicit
Sub Send_Range()
' Select the range of cells on the active worksheet.
ActiveSheet.Range("A1:B5").Select
' Show the envelope on the ActiveWorkbook.
ActiveWorkbook.EnvelopeVisible = True
' Set the optional introduction field thats adds
' some header text to the email body. It also sets
' the To and Subject lines. Finally the message
' is sent.
With ActiveSheet.MailEnvelope
.Introduction = "This is a sample worksheet."
.Item.To = "E-Mail_Address_Here"
.Item.Subject = "My subject"
.Item.Send
End With
End Sub

I think you can not suppress display of e-mail creation screen display by invoking Word Editor approach. If you go through previous SO Posts and comments of experienced experts it gets amply clear that you can not suppress display of e-mail creation screen display.
In order to totally disable e-mail creation screen display please take reference from programs at roundebruin which covers all types of possibilities of sending emails without displaying email creation screen. Here is a slight variation to your code which works for me and posted, if someone finds it useful for similar situation.
Public Sub Emails()
Dim str As String
Dim outlook As Object
Dim newEmail As Object
Dim xInspect As Object
Dim pageEditor As Object
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set outlook = CreateObject("Outlook.Application")
Set newEmail = outlook.CreateItem(0)
Set ws1 = ThisWorkbook.Worksheets("Sheet1")
str = ws1.Range("A5").Value
With newEmail
.To = "xxx.xxx.com"
.CC = ""
.BCC = ""
.Subject = str
.body = ""
.display
Set xInspect = newEmail.GetInspector
Set pageEditor = xInspect.WordEditor
'Set ws1 = ThisWorkbook.Worksheets("Sheet1")
ws1.Range("A5").Copy
pageEditor.Application.Selection.Paste xlValues
ws1.Range("A5:W20").Copy
pageEditor.Application.Selection.Paste xlValues
.send
Set pageEditor = Nothing
Set xInspect = Nothing
End With
Set newEmail = Nothing
Set outlook = Nothing
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub

Related

Paste text and multiple Excel ranges as images in Outlook using wordeditor

I am trying to paste multiple Excel ranges as images in Outlook mail using VBA. I am using the answer to this question (Pasting an Excel range into an email as a picture) to paste a range of excel as image in mail but as soon as I paste another range, it overwrites the previous image. Is there anyway to change the cursor position in Outlook mail using wordeditor. I tried using collapse before pasting the image but it did not help. Also how do I add the text to it as using Outmail.body to edit anything gets overwritten too by the image pasted afterwards.
This is the code I am using:
Sub Sendmail()
Dim r as range
Set r = Range("C2:O13)
r.copy
dim outlookapp as Outlook.Application
set outlookapp = CreateObject("Outlook.Application")
dim outMail As Outlook.Mailitem
Set outMail = outlookApp.CreateItem(olMailItem)
With outMail
.Display
.CC = "xyz#abc.com"
.Subject = "Test"
.Body = "Dear" & "Macro" & vbnewline
end with
outmail.Display
'Opening wordeditor
dim worddoc as Word.Document
Set worddoc = Outmail.GetInspector.WordEditor
worddoc.range.PasteandFormat wdChartPicture
'Adding new line after pasting image
worddoc.range.Insertafter vbNewline
' Adding second image
dim s as range
set s= Range(P2:Z30)
s.copy
worddoc.range.PasteandFormat wdChartPicture
You could refer to the below code:
Option Explicit
Public Sub Example()
Dim rng As Range
Dim olApp As Object
Dim Email As Object
Dim Sht As Excel.Worksheet
Dim wdDoc As Word.Document
Set Sht = ActiveWorkbook.Sheets("Dashboard")
Set rng = Sht.Range("B4:L17")
rng.CopyPicture Appearance:=xlScreen, Format:=xlPicture
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set olApp = CreateObject("Outlook.Application")
Set Email = olApp.CreateItem(0)
Set wdDoc = Email.GetInspector.WordEditor
With Email
.To = ""
.CC = ""
.BCC = ""
.Subject = ""
.Attachments.Add ActiveWorkbook.FullName
wdDoc.Range.PasteAndFormat Type:=wdChartPicture
' if need setup inlineshapes hight & width
With wdDoc
.InlineShapes(1).Height = 130
End With
.Display
End With
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set Email = Nothing
Set olApp = Nothing
End Sub
For more information, please refer to these links:
Copy Excel range as Picture to Outlook
Copy range of cells from Excel as picture and add text in the email body

Copy a report from Excel to Outlook as a BMP and the sparklines do not copy over

I am copying a report dashboard from Excel into Outlook and the sparkline charts in column J do not copy over. When I step through the code it appears that they are being copied and pasted as an image.
When I export the same report to SharePoint as a BMP the sparklines do appear.
I cannot figure out what the issue is. Any help trouble shooting would be appreciated.
*** Edit: The issue appears to be with this line wordDoc.Range.PasteSpecial , , , , wdPasteBitmap
What would be a better paste method that appears clear and not blurry?
The code is shown below:
Sub Mail()
Dim OutApp As Object
Dim OutMail As Object
'Unprotect Scorecard
Worksheets("Scorecard").Unprotect
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 = "email#email.com>"
.CC = ""
.BCC = ""
.Subject = "Report"
'.HTMLBody =
.Display 'or use .Send
Dim wordDoc As Object
Set wordDoc = OutMail.GetInspector.WordEditor
Worksheets("Scorecard").Activate
Set Plage = ThisWorkbook.Worksheets("Scorecard").Range("B1:M62")
Plage.CopyPicture
With ThisWorkbook.Worksheets("Scorecard").ChartObjects.Add(Plage.Left, Plage.Top, Plage.Width, Plage.Height)
.Activate
.Chart.Paste
.Chart.ChartArea.Border.LineStyle = xlNone
End With
Worksheets("Scorecard").ChartObjects(Worksheets("Scorecard").ChartObjects.Count).Copy
wordDoc.Range.PasteSpecial , , wdInline, , wdPasteBitmap
Worksheets("Scorecard").ChartObjects(Worksheets("Scorecard").ChartObjects.Count).Delete
Application.CutCopyMode = False
wordDoc.Range.InsertBefore vbLf
wordDoc.Range.InsertBefore vbLf
wordDoc.Hyperlinks.Add Anchor:=wordDoc.Range(0, 0), Address:="http://sharepoint.com", TextToDisplay:="archive"
wordDoc.Range.InsertBefore vbLf
wordDoc.Hyperlinks.Add Anchor:=wordDoc.Range(0, 0), Address:="http://sharepoint.com", TextToDisplay:="web version"
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
'Protect
Worksheets("Scorecard").Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
End Sub
This is the work around I came up with but I am not stoked. Would prefer to use wdPasteBitmap as the formatting is a little cleaner but I cannot figure out why it is dropping the sparklines.
wordDoc.Range.PasteAndFormat wdChartPicture
wordDoc.Application.ActiveDocument.InlineShapes(1).Width = 850
wordDoc.Application.ActiveDocument.InlineShapes(1).Height = 950

Send mail through Outlook - Error 287

I am trying to loop through a set of worksheets, save each of them as a separate workbook, and then send them as attachment by mail.
However when running the below code, I end up with error 287 triggered by .Send. I have outlook open, so that is not the problem. If I change .Send to .Display, the mails are generated as drafts as displayed properly with the correct sheet attached.
Sub SendWorksheetsByMail()
Dim wb As Workbook
Dim destinationWb As Workbook
Dim OutApp As Outlook.Application
Dim OutMail As Outlook.MailItem
Set wb = Workbooks("Test.xlsm")
Application.EnableEvents = False
Application.ScreenUpdating = False
For Each ws In wb.Worksheets
'Ignore Summary and Config
If ws.Name <> "Summary" And ws.Name <> "Config" Then
'On Error Resume Next
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(olMailItem)
ws.Copy
Set destinationWb = ActiveWorkbook
destinationWb.SaveAs "C:\****************\" & ws.Name & ".xlsx", FileFormat:=51
With OutMail
.To = "*******************"
.Subject = "Test"
.Body = "Test"
.Attachments.Add destinationWb.FullName
.Send
End With
Set OutMail = Nothing
Set OutApp = Nothing
End If
Next ws
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Edit: "It also fails even without an attachment. Essentially generating a message containing only the subject and text "test"."
Any suggestions for how to solve this? It would save a lot of time to not have to click Send for each individual mail, as the number of mails to send could potentially become quite large.
This is what I used to send a mail with attachment to multiple addresses, listed in column H while the name of the receiver is listed in another column
Sub Mail()
'####################################
'### Save the file as pdf ######
'####################################
Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String
Set FSO = CreateObject("Scripting.FileSystemObject")
s(0) = ThisWorkbook.FullName
If FSO.FileExists(s(0)) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Replace(s(0), s(1), ".pdf")
'//Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=sNewFilePath, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
'##########################################
'### Attach the file and mail it ######
'##########################################
Dim OutApp As Object
Dim OutMail As Object
Dim sh As Worksheet
Dim cell As Range
Dim FileCell As Range
Dim rng As Range
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set sh = Sheets("sheet")
Set OutApp = CreateObject("Outlook.Application")
For Each cell In sh.Columns("H").Cells.SpecialCells(xlCellTypeConstants)
If cell.Value Like "?*#?*.?*" Then
Set OutMail = OutApp.CreateItem(0)
With OutMail
.to = cell.Value
.Subject = "file delivery "
.Body = "Hi " & cell.Offset(0, -3).Value & " here is my file"
.Attachments.Add sNewFilePath
.Send 'Or use .Display
End With
Set OutMail = Nothing
End If
Next cell
Set OutApp = Nothing
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
Try .GetInspector before .Send. It would be like .Display without displaying.
I found a two step soultion. By changing .Send to .Display in the code above, the messages will be created as drafts in outlook and Displayed. If you do not want an extra window per e-mail, changing .Display to .Save will just put them in the draft folder.
Then I can use a macro written in Outlook to send all drafts. Code based on solution found at the mrexcel forums.
I also discovered after reading this answer on SO that the drafts folder can not be selected when running the macro.
Hope this helps others running into the same problem.
Public Sub SendDrafts()
Dim lDraftItem As Long
Dim myOutlook As Outlook.Application
Dim myNameSpace As Outlook.NameSpace
Dim myFolders As Outlook.Folders
Dim myDraftsFolder As Outlook.MAPIFolder
'Send all items in the "Drafts" folder that have a "To" address filled in.
'Setup Outlook
Set myOutlook = Outlook.Application
Set myNameSpace = myOutlook.GetNamespace("MAPI")
Set myFolders = myNameSpace.Folders
'Set Draft Folder.
Set myDraftsFolder = myFolders("*******#****.com").Folders("Drafts")
'Loop through all Draft Items
For lDraftItem = myDraftsFolder.Items.Count To 1 Step -1
'Check for "To" address and only send if "To" is filled in.
If Len(Trim(myDraftsFolder.Items.Item(lDraftItem).To)) > 0 Then
'Send Item
myDraftsFolder.Items.Item(lDraftItem).Send
End If
Next lDraftItem
'Clean-up
Set myDraftsFolder = Nothing
Set myNameSpace = Nothing
Set myOutlook = Nothing
End Sub
Might be a good idea to add code that differntiates the messages you are trying to send from other drafts that may already be in the folder.
Would still prefere a one step solution, so I will wait with marking this as a solution.
I finally found the answer googling a lot.
The problem is not with the .send method, but rather the session object.
Replace Set myOutlook = Outlook.Application with
Set objOutlook = ThisOutlookSession
This ensures that your macro is using the same outlook session that is open. Atleast it did the trick for me

Copy All Visible(Formatted Text) from Excel to Outlook using VBA?

Copy All Visible(Formatted Text) from Excel to Outlook using VBA?
Please find below code to send email through outlook. However, I want to send the email with a selection that I have copied below using code.
I do not wish to create a Table as HTML but instead just copy all visible?
Sub EmailRep()
Dim Mailbody As Range
Application.DisplayAlerts = False
Dim Outlook As Outlook.Application
Set Outlook = CreateObject("Outlook.Application")
Dim outmail As MailItem
Set outmail = Outlook.CreateItem(0)
Set Mailbody = ActiveWorkbook.Worksheets("Dashboard").Range("A1:F30")
Mailbody.Copy
With outmail
.To = "abc#xyz.com"
.Subject = "All Open"
.Body = "This is Test Email"
.Display
.Send
End With
Set Outlook = Nothing
Set outmail = Nothing
Set Mailbody = Nothing
End Sub
If I understand correct change your line of :
Set Mailbody = ActiveWorkbook.Worksheets("Dashboard").Range("A1:F30")
To
Set Mailbody = ActiveWorkbook.Worksheets("Dashboard").Range("A1:F30").SpecialCells(xlCellTypeVisible)
Although in your code you are not putting the range into the body of the email. At first thought you pasted the range by hand but then I noticed you have .Send in code which would send the email before you got a chance to paste.
Either way the above will copy only the visible range.
If you are interested in a quick way to send your range in an email without the need to copy the below is pretty short and sweet:
Sub EmailRep()
With Application
.DisplayAlerts = False
.ScreenUpdating = False
End With
Range("A1:F30").SpecialCells(xlCellTypeVisible).Select
ActiveWorkbook.EnvelopeVisible = True
With ActiveSheet.MailEnvelope
.Introduction = "This is Test Email"
.Item.To = "abc#xyz.com"
.Item.Subject = "All Open"
.Item.Send
End With
ActiveWorkbook.EnvelopeVisible = False
With Application
.DisplayAlerts = True
.ScreenUpdating = True
End With
End Sub

Direct VBA to save a copy of a spread sheet in a designated folder in outlook

I have code to take a copy of a select worksheet but am haveing difficulties directing which draft folder in outlook to send the draft email to. The name of the folder I want to send the draft email to is "Draft NDIC". Here is the code:
Sub Mail_Body_NDIC()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set rng = Nothing
Set rng = Sheets("NDIC Renewals").UsedRange
'You can also use a sheet name
'Set rng = Sheets("YourSheet").UsedRange
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = "dvandervieren#enerplus.com"
.CC = ""
.BCC = ""
.Subject = "NDIC Renewals for the Next 90 Days"
.Body = ""
.HTMLBody = RangetoHTML(rng)
.Save 'or use .Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
"You need to use the .Move method, with the olDestFolder as the argument." David Van der Vieren
http://blog.saieva.com/2010/03/27/move-messages-to-folders-with-outlook-vba/

Resources