Copy text and image from Excel sheet as mail body to Outlook - excel

This is the sample email which is saved in Excel worksheet.
Hi All,
This is the test email
Regards,
Xyz
I want to copy this email as it is & paste it to Outlook.
With the help of online forums I have written a code but the output is not the same as the input.
Global Email_Subject, Email_Send_From, Email_Send_To, _
Email_Cc, Email_Bcc, Email_Body As String
Global Mail_Object, Mail_Single As Variant
Global wb As Workbook
Sub India_BB()
Dim i As Integer
Dim ShtToSend As Worksheet
Dim strSendTo, strbody As String
Dim strSheetName As String
Dim strSubject As String
Dim rng As Range
Set Mail_Object = CreateObject("Outlook.Application")
Set Mail_Single = Mail_Object.CreateItem(0)
For i = 1 To ThisWorkbook.Sheets.Count
If Sheets(i).Name = "India_BB" Then
Sheets(i).Select
Set rng = Nothing
strSheetName = Sheets(i).Name
strSendTo = Sheet1.Range("A1").Text
strSubject = Sheet1.Range("B1").Text
Set rng = Sheets(strSheetName).Range("body").SpecialCells(xlCellTypeVisible)
With Mail_Single
.To = strSendTo
.CC = ""
.BCC = ""
.Subject = strSubject
.HTMLBody = RangetoHTML(rng)
.Display
End With
End If
Next i
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 xlPasteAll, , 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
Below is the Output I am getting with above code.
Link for excel file : https://drive.google.com/open?id=0Byy709uTvWRoTnRYaVJQNWNNR1E

Use GetInspector.WordEditor
See Example...
Sub India_BB()
Dim i As Integer
Dim ShtToSend As Worksheet
Dim strSendTo, strbody As String
Dim strSheetName As String
Dim strSubject As String
Dim rng As Range
' add ref - tool -> references - > Microsoft Word XX.X Object Library
Dim wdDoc As Word.Document '<=========
Set Mail_Object = CreateObject("Outlook.Application")
Set Mail_Single = Mail_Object.CreateItem(0)
Set wdDoc = Mail_Single.GetInspector.WordEditor '<========
For i = 1 To ThisWorkbook.Sheets.Count
If Sheets(i).Name = "India_BB" Then
Sheets(i).Select
Set rng = Nothing
strSheetName = Sheets(i).Name
strSendTo = Sheet1.Range("A1").Text
strSubject = Sheet1.Range("B1").Text
Set rng = Sheets(strSheetName).Range("body").SpecialCells(xlCellTypeVisible)
rng.Copy
With Mail_Single
.To = strSendTo
.CC = ""
.BCC = ""
.Subject = strSubject
' .HTMLBody = RangetoHTML(rng)
.Display
wdDoc.Range.PasteAndFormat wdChartPicture & .HTMLBody = " " '<=======
End With
End If
Next i
End Sub

Related

Unable to search archived outlook email from Enterprise Vault in excel vba

I'm trying to retrieve data from archieved outlook emails from Enterprise Vault using excel vba. but it searching through only 1005 mail. but actually mail should be more than 10000. but actually looping through only 1005 mail. but should go to more than 10000 mail. I think problem happening due Enterprise Vault archived mail. because this emails are not showing in outlook but showing while going through below wesite
http://arlev4cls.india.eclerx.com/EnterpriseVault/search/shell.aspx?server=ARLMSEXCH07&mbx=SMTP:Pravin.Angane#eclerx.com#
Sub OnlineJapan_Email()
Dim outlookApp
Dim olNs As Outlook.Namespace
Dim Fldr As Outlook.MAPIFolder
Dim olMail As Variant 'Outlook.MailItem
Dim olFMail As Outlook.MailItem
Dim myTasks
Dim sir() As String
Dim rng As Range
'Set outlookApp = New Outlook.Application
Set outlookApp = CreateObject("Outlook.Application")
Set olNs = outlookApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderInbox)
Set myTasks = Fldr.Items
Dim wb As Workbook
Dim obwb As Workbook
For Each wb In Workbooks
If wb.Name Like "Consolidated observation file*.xlsb" Then
Set obwb = wb
obwb.Activate
Exit For
End If
Next
lastrow = obwb.Sheets("Daily Observation").Range("bm50000").End(xlUp).Row
Set rng = obwb.Sheets("Daily Observation").Range(Cells(8, 60), Cells(lastrow, 65)).SpecialCells(xlCellTypeVisible)
'
'Set olMail = myTasks.Find("[Subject] = ""123456""")
'
For Each olMail In myTasks
'
If TypeName(olMail) = "MailItem" Then
If (InStr(1, olMail.Subject, "Japan Observations for ", vbTextCompare) > 0) Then
Set olFMail = olMail.Forward
With olFMail
.To = "Pravin.Angane#eclerx.com;Jaysing.Pardeshi#eclerx.com;Suhas.Bhange#eclerx.com;Dadasaheb.Kamble#eclerx.com"
.CC = "Jaysing.Pardeshi#eclerx.com;Suhas.Bhange#eclerx.com"
.HTMLBody = "<HTML><BODY>" & obwb.Sheets("AutoMail").Range("a40") & "<br><br>" & obwb.Sheets("AutoMail").Range("a41") & "</BODY></HTML>" & RangetoHTML(rng) & olFMail.HTMLBody
.Subject = obwb.Sheets("AutoMail").Range("i42")
End With
Set Myattachments = olFMail.Attachments
While Myattachments.Count > 0
Myattachments.Remove 1
Wend
olFMail.Attachments.Add "\\IPSAABACUS\CM_Shared$\SalesForce\Jyoti Sahay\VA-Training\Scrubbing feedback\Observations\Consolidated observation file - Dec-2022.rar"
olFMail.Display
Exit For
End If
End If
Next
'Dim outForward As Outlook.MailItem
'Set outForward = ActiveExplorer.Selection.Item(1).Forward
'outForward.Recipients.Add "pravin.angane#eclerx.com"
'outForward.Save
End Sub
Function RangetoHTML(rng As Range)
Dim obj As Object
Dim txtstr As Object
Dim File As String
Dim wb As Workbook
File = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
rng.Copy
Set wb = Workbooks.Add(1)
With wb.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
.Cells.EntireColumn.AutoFit
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
With wb.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=File, _
Sheet:=wb.Sheets(1).Name, _
Source:=wb.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
Set obj = CreateObject("Scripting.FileSystemObject")
Set txtstr = obj.GetFile(File).OpenAsTextStream(1, -2)
RangetoHTML = txtstr.readall
txtstr.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
wb.Close savechanges:=False
Kill File
Set txtstr = Nothing
Set obj = Nothing
Set wb = Nothing
End Function
Sub OnlineJapan_Email()
Dim outlookApp
Dim olNs As Outlook.Namespace
Dim Fldr As Outlook.MAPIFolder
Dim olMail As Variant 'Outlook.MailItem
Dim olFMail As Outlook.MailItem
Dim myTasks
Dim sir() As String
Dim rng As Range
'Set outlookApp = New Outlook.Application
Set outlookApp = CreateObject("Outlook.Application")
Set olNs = outlookApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderInbox)
Set myTasks = Fldr.Items
Dim wb As Workbook
Dim obwb As Workbook
For Each wb In Workbooks
If wb.Name Like "Consolidated observation file*.xlsb" Then
Set obwb = wb
obwb.Activate
Exit For
End If
Next
lastrow = obwb.Sheets("Daily Observation").Range("bm50000").End(xlUp).Row
Set rng = obwb.Sheets("Daily Observation").Range(Cells(8, 60), Cells(lastrow, 65)).SpecialCells(xlCellTypeVisible)
'
'Set olMail = myTasks.Find("[Subject] = ""123456""")
'
For Each olMail In myTasks
'
If TypeName(olMail) = "MailItem" Then
If (InStr(1, olMail.Subject, "Japan Observations for ", vbTextCompare) > 0) Then
Set olFMail = olMail.Forward
With olFMail
.To = "Pravin.Angane#eclerx.com;Jaysing.Pardeshi#eclerx.com;Suhas.Bhange#eclerx.com;Dadasaheb.Kamble#eclerx.com"
.CC = "Jaysing.Pardeshi#eclerx.com;Suhas.Bhange#eclerx.com"
.HTMLBody = "<HTML><BODY>" & obwb.Sheets("AutoMail").Range("a40") & "<br><br>" & obwb.Sheets("AutoMail").Range("a41") & "</BODY></HTML>" & RangetoHTML(rng) & olFMail.HTMLBody
.Subject = obwb.Sheets("AutoMail").Range("i42")
End With
Set Myattachments = olFMail.Attachments
While Myattachments.Count > 0
Myattachments.Remove 1
Wend
olFMail.Attachments.Add "\\IPSAABACUS\CM_Shared$\SalesForce\Jyoti Sahay\VA-Training\Scrubbing feedback\Observations\Consolidated observation file - Dec-2022.rar"
olFMail.Display
Exit For
End If
End If
Next
'Dim outForward As Outlook.MailItem
'Set outForward = ActiveExplorer.Selection.Item(1).Forward
'outForward.Recipients.Add "pravin.angane#eclerx.com"
'outForward.Save
End Sub
Function RangetoHTML(rng As Range)
Dim obj As Object
Dim txtstr As Object
Dim File As String
Dim wb As Workbook
File = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
rng.Copy
Set wb = Workbooks.Add(1)
With wb.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
.Cells.EntireColumn.AutoFit
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
With wb.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=File, _
Sheet:=wb.Sheets(1).Name, _
Source:=wb.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
Set obj = CreateObject("Scripting.FileSystemObject")
Set txtstr = obj.GetFile(File).OpenAsTextStream(1, -2)
RangetoHTML = txtstr.readall
txtstr.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
wb.Close savechanges:=False
Kill File
Set txtstr = Nothing
Set obj = Nothing
Set wb = Nothing
End Function

Email table range to same addresses

So currently my code works almost to what I like it too.
It currently groups the same emails together and emails that range to the person.
But in the email I'm trying to not include column A which is their email.
For Each cell In WS.Columns("A").Cells.SpecialCells(xlCellTypeConstants)
If cell.Value Like "?*#?*.?*" Then
'check if this email address has been used to generate an outlook email or not
If dict.exists(cell.Value) = False Then
dict.Add cell.Value, "" 'add the new email address
Set OutMail = OutApp.CreateItem(0)
Set rng = WS.UsedRange.Rows(1)
'find all of the rows with the same email and add it to the range
For Each cell2 In WS.UsedRange.Columns(1).Cells
If cell2.Value = cell.Value Then
Set rng = Application.Union(rng, WS.UsedRange.Rows(cell2.Row))
End If
Next cell2
I tried modifying the above code but can't seem to work it out.. Can anyone help me out?
full code:
Option Explicit
Sub Test1()
Dim OutApp As Object
Dim OutMail As Object
Dim dict As Object 'keep the unique list of emails
Dim cell As Range
Dim cell2 As Range
Dim rng As Range
Dim i As Long
Dim WS As Worksheet
Dim Signature As String
Application.ScreenUpdating = False
Set OutApp = CreateObject("Outlook.Application")
Set dict = CreateObject("scripting.dictionary")
Set WS = ThisWorkbook.Sheets("Sheet1") 'Current worksheet name
On Error GoTo cleanup
For Each cell In WS.Columns("A").Cells.SpecialCells(xlCellTypeConstants)
If cell.Value Like "?*#?*.?*" Then
'check if this email address has been used to generate an outlook email or not
If dict.exists(cell.Value) = False Then
dict.Add cell.Value, "" 'add the new email address
Set OutMail = OutApp.CreateItem(0)
Set rng = WS.UsedRange.Rows(1)
'find all of the rows with the same email and add it to the range
For Each cell2 In WS.UsedRange.Columns(1).Cells
If cell2.Value = cell.Value Then
Set rng = Application.Union(rng, WS.UsedRange.Rows(cell2.Row))
End If
Next cell2
On Error Resume Next
With OutMail
.SentOnBehalfOfName = ""
.GetInspector ' ## This inserts default signature
Signature = .HTMLBody ' ## Capture the signature HTML
.To = cell.Value
.CC = ""
.Subject = "Reminder"
.HTMLBody = "<BODY style=font-size:12pt;font-family:Calibri><font color=#000000>Hi " & WorksheetFunction.Proper(RemoveNumbers(Left((cell.Value), InStr((cell.Value), ".") - 1))) & ", " & "<br><br>" & "Please see your trip numbers and estimated cost below:" & vbNewLine & vbNewLine & RangetoHTML(rng) & Signature & "</font></BODY>"
.Display
End With
On Error GoTo 0
Set OutMail = Nothing
End If
End If
Next cell
cleanup:
Set OutApp = Nothing
Application.ScreenUpdating = True
End Sub
Function RemoveNumbers(Txt As String) As String
With CreateObject("VBScript.RegExp")
.Global = True
.Pattern = "[0-9]"
RemoveNumbers = .Replace(Txt, "")
End With
End Function
Function RangetoHTML(rng As Range)
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
One option is to use Intersect and Resize.
After the loop that creates rng but before passing rng to RangetoHTML:
With WS.UsedRange
Set rng = Intersect(rng, .Columns(2).Resize(,.Columns.Count - 1))
End With

RangeToHTML & Image in Cell

Im trying to generate an email using Ron de Bruin's RangeToHTML and its working perfectly so far however one of my cells ("B26") contains an image and this wont copy into the email.
I've tried and succeded in adding in the image before or after the range but I need this image to appear in this specific cell. Any Ideas how I can get this to work if its at all possible?
Sub SendEmail()
Dim OutlookApp As Outlook.Application
Dim MItem As Outlook.MailItem
Dim cell As Range
Dim Subj As String
Dim EmailAddr As String
Dim Recipient As String
Dim rng As Range
Dim rng2 As Range
Dim StrBody As String
Set rng = Sheets("Email Templates").Range("A1:D29")
'Set rng2 = Sheets("Email Templates").Range("A6:D32").SpecialCells(xlCellTypeVisible)
'Create Outlook object
Set OutlookApp = New Outlook.Application
'Operations Contacts
For Each cell In Sheets("Contacts").Columns("A").Cells.SpecialCells(xlCellTypeVisible)
If cell.Value Like "*#*" Then
EmailAddr = EmailAddr & ";" & cell.Value
End If
Next
'Systems Contacts
For Each cell In Sheets("Contacts").Columns("B").Cells.SpecialCells(xlCellTypeVisible)
If cell.Value Like "*#*" Then
EmailAddr = EmailAddr & ";" & cell.Value
End If
Next
Subj = "Systems Notification | System Outage | " & Sheets("Email Templates").Range("C6") & " " & Sheets("Email Templates").Range("C4") & " " & Sheets("Email Templates").Range("C6")
'Create Mail Item and view before sending
Set MItem = OutlookApp.CreateItem(olMailItem)
With MItem
.To = EmailAddr
.Subject = Subj
.HTMLBody = RangetoHTML(rng)
.Display
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
Dim r As Long
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).PasteSpecial xlPasteAllUsingSourceTheme, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
For r = 1 To rng.Rows.Count
.Rows(r).RowHeight = rng.Rows(r).RowHeight
Next r
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=")
RangetoHTML = Replace(RangetoHTML, "<!--[if !excel]> <![endif]-->", "")
'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
You can achieve it by taking a screenshot(using VBA Code) of the relevant range (Has to be visible in the screen) and then save and import that image in Outlook..
This will get you started. I have added the comments so you should not have a problem understanding it. If you still do then simply ask.
Option Explicit
Sub SaveRngAsImage()
Dim flName As String
Dim ws As Worksheet
Dim shp As Shape
Dim objChart As ChartObject
Dim chrt As Chart
Set ws = ActiveSheet
'~~> Change as applicable
flName = "C:\Users\routs\Desktop\MyRng.jpg"
'~~> Delete the above image
If Dir(flName) <> "" Then Kill flName
'~~> Check if what the user selected is a valid range
If TypeName(Selection) <> "Range" Then
MsgBox "Select a range first."
Exit Sub
End If
'~~> Take a screenshot of the range
Selection.CopyPicture xlScreen, xlBitmap
DoEvents
'~~> Paste the screenshot in the worksheet and assign it to
'~~> a shape object so that we can use it's approx width and
'~~> Height to create the chart object
With ws
.Paste
DoEvents
Set shp = .Shapes(.Shapes.Count)
Set objChart = ActiveSheet.ChartObjects.Add(0, 0, shp.Width, shp.Height)
Set chrt = objChart.Chart
With chrt
shp.Copy '~~> Copy the shape (in case the clipboard is cleared)
.ChartArea.Select
.Paste
'~~> Save the image
.Export ("C:\Users\routs\Desktop\MyRng.jpg")
End With
shp.Delete
objChart.Delete
End With
'~~> Attaching the above image to outlook email body
'https://stackoverflow.com/questions/44869790/embed-picture-in-outlook-mail-body-excel-vba
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = "SomeEmail#SomeServer.com"
.Subject = "Attaching an image"
.Attachments.Add flName, 1, 0
.HtmlBody = "<html><p>Dear XYZ</p>" & _
"<img src=""cid:MyRng.jpg"">"
.Display
End With
End Sub
Screenshot

Send Email With A Filter Range Pasted Into Email Body using Excel VBA

I have to send an email that includes a table, in the body, that was copied from a filter table.
The filter table's name is "ds" in this code.
I use function RangetoHTML (code below) but it only copies the format, not the contents of the table:
Sub Email_Syndicate()
Dim OutApp As Object
Dim OutMail As Object
Dim EmailSubject As String
Dim EmailSendTo As String
Dim MailBody As String
Dim cell As Range
Dim Signature As String
Dim ds As Range
Set rng = Range(Range("B2"), Range("B" & Rows.Count).End(xlUp))
For Each cell In rng
rw = cell.Row
If cell.Value <> "" Then
EmailSendTo = cell.Value
Nme = cell.Offset(0, 3).SpecialCells(xlCellTypeVisible)
xCC = cell.Offset(0, 1)
att = cell.Offset(0, 4).Value
EmailSubject = cell.Offset(0, 2)
lr1 = Sheet3.Cells(Rows.Count, 1).End(xlUp).Row
Sheet3.Range("A1:N" & lr1).AutoFilter field:=6, Criteria1:=Sheet4.Range("F2").Value
lr = Sheet3.Cells(Sheet3.Rows.Count, 1).End(xlUp).Row
Set ds = Sheet3.Range("A1:N" & lr).SpecialCells(xlCellTypeVisible)
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(o)
With OutMail
.Display
End With
Signature = OutMail.HTMLBody
'On Error Resume Next
With OutMail
.Subject = EmailSubject
.To = EmailSendTo
.CC = xCC
'.Body = MailBody
.HTMLBody = RangetoHTML(ds)
.Display
.send
End With
Set OutMail = Nothing
Set OutApp = Nothing
MailBody = ""
End If
With Application
.EnableEvents = 1
.Calculation = xlCalculationAutomatic
End With
Set OutMail = Nothing: Set OutApp = Nothing
Next
End Sub
Function RangetoHTML(rng As Range)
Dim fso As Object, ts As Object, TempWB As Workbook, TempFile As String
TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=xlPasteAll
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteColumnWidths, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
End With
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
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=")
TempWB.Close 0
Kill TempFile
Set ts = Nothing: Set fso = Nothing: Set TempWB = Nothing
End Function
How can I copy a filter table containing full content to the email body?
Sub SendEmail_1()
Dim outlook As Object
Dim newEmail As Object
Dim xInp As Object
Dim pgEdit As Object
Dim pos As Integer
Set outlook = CreateObject("Outlook.Application")
Set newEmail= outlook.Createitem(o)
'construction email
With newEmail
.Recipients.Add ("person#email.com")
.Subject = "Subject goes here"
Set xInp = newEmail.GetInspector 'gets you into the test editor
Set pgEdit = xInp.WordEditor 'returns a word document object you can edit
'selects data we want to copy into email
Sheets("your Sheet").Range("your Range").Copy
'pastes the excel range over the indicator
pgEdit.Range(Start:=0, End:=1).PasteSpecial Placement:=wdInLine
Application.CutCopyMode = True
.display
.send
End With
End Sub

Excel macro to populate table in the email body

I am a beginner in coding and trying to create a macro to send emails to the credit analysts in my team. I am using a sample Excel sheet for the data.
How do I add a 4x2 table in the email body for each credit analyst listed in the sample data? Below is a very basic code which I could create after spending hours.
Sub Credit_Auto()
Dim objOutlook As Object
Dim objMail As Object
Dim Ws As Worksheet
Dim strbody As String
Set objOutlook = CreateObject("Outlook.Application")
Set Ws = ActiveSheet
Dim rCell As Range
For Each rCell In Ws.Range("G2", Ws.Range("G1000").End(xlUp))
Debug.Print rCell.Address
Set objMail = objOutlook.CreateItem(0)
strbody = "Dear " & rCell.Offset(0, -1).Value & "," & "<br>" & "<br>" & _
"Please allocate the below account to it's appropriate parent account." & "<br>" & "<br>" & _
"Regards" & "<br>" & "<br>" & _
"Ankit"
With objMail
.To = rCell.Value
.Subject = "Unalloctaed Credit Profiles"
.HTMLBody = strbody
.Send
End With
Next rCell
Set objMail = Nothing
Set Ws = Nothing
Set objOutlook = Nothing
End Sub
I need the table with just after the second line in strbody (the table should contain data from A to D with headers and the corresponding row of the analyst in column F.)
Here is the sample data Click Here
And the final email should look like below for the first email and so on..
enter image description here
Thanks in advance.
Try the script below. It will let you choose a range to attach to the body of an Outlook email.
Sub Mail_Selection_Range_Outlook_Body()
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Don't forget to copy the function RangetoHTML in the module.
'Working in Excel 2000-2016
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
On Error Resume Next
'Only the visible cells in the selection
Set rng = Selection.SpecialCells(xlCellTypeVisible)
'You can also use a fixed range if you want
'Set rng = Sheets("YourSheet").Range("D4:D12").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 = "ron#debruin.nl"
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.HTMLBody = RangetoHTML(rng)
.Send '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
Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2016
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
Notice this: Function RangetoHTML(rng As Range)

Resources