Using Dim'ed Range In Email Body - vba

Trying to reference a dynamic range in the body of an email (this will change based on the user's input into the sheet). The email outputs just fine, but there is nothing in the email where "AFund" is supposed to be. Code is below, any help is appreciated!
Dim BlasEmail As Workbook
Dim OutApp As Object
Dim OutMail As Object
Dim FundAdd, FundRem, Broker As Range
Dim AFund As String
Set BlastEmail = ActiveWorkbook
Set Cover = ThisWorkbook.Sheets("Cover")
Set CDEA = ThisWorkbook.Sheets("CDEA")
LastRow = Cells(Rows.Count, 5).End(xlUp).Row
LRow = Cells(Rows.Count, 7).End(xlUp).Row
LasRow = Cells(Rows.Count, 2).End(xlUp).Row
FundAdd = AFund
Set FundAdd = Range("E2:E" & LastRow)
Set FundRem = Range("G2:G" & LRow)
Set Broker = Range("C6:C" & LasRow)
If Range("ISDAMRA") = "ISDA" And Range("G2") = "" Then
Application.ReferenceStyle = xlA1
SigString = Environ("appdata") & _
"\Microsoft\Signatures\My Signature.htm"
If Dir(SigString) <> "" Then
Signature = GetBoiler(SigString)
Else
Signature = ""
End If
Set OutApp = CreateObject("Outlook.Application")
Dim EmBody As String
EmBody = "Hello," & "<br><br>" & _
"Body goes here " & "<br>" & "<br>" & AFund
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = "myemail"
.CC = ""
.BCC = ""
.Subject = "Here is the subject " & Range("B6") & " "
.HTMLBody = EmBody & Signature
'You can add files like this
'.Attachments.Add ("C:\test.txt")
'.Send
.Display 'This will display the emails for the user to review CXH
End With
On Error GoTo 0
Set OutMail = Nothing
End If
'
End Sub

From:
Sending a range of cells...
2 Methods to Quickly Send Selected Cells in an Excel Worksheet as an Outlook Email
Option Explicit ' Consider this mandatory
' Tools | Options | Editor tab
' Require Variable Declaration
' If desperate declare as Variant
Sub SendRange()
' https://www.datanumen.com/blogs/2-methods-quickly-send-selected-cells-excel-worksheet-outlook-email/
' https://stackoverflow.com/questions/73136067
Application.Calculation = xlCalculationManual
' Application is Excel. No influence in Outlook.
Application.ScreenUpdating = False
' Reference Microsoft Outlook nn.n Object Library
Dim olApp As Outlook.Application
Dim olEmail As Outlook.MailItem
Dim olInsp As Outlook.Inspector
' Reference Microsoft Word nn.n Object Library
Dim wdDoc As Word.Document
Dim strGreeting As String
Dim lastRow As Long
lastRow = Cells(Rows.Count, 5).End(xlUp).Row
Debug.Print lastRow
Dim fundAdd As Range
Dim objSelection As Range
Set fundAdd = Range("E2:E" & lastRow)
fundAdd.Select
Set objSelection = Selection
objSelection.Copy
Dim objTempWorkbook As Workbook
Set objTempWorkbook = Workbooks.Add(1)
Dim objTempWorksheet As Worksheet
Set objTempWorksheet = objTempWorkbook.Sheets(1)
Dim strTempHTMLFile As String, Strbody As String
Dim objTempHTMLFile As Object, objTextStream As Object
Dim objFileSystem As Object
Set objFileSystem = CreateObject("Scripting.FileSystemObject")
'Pasting into a Temp Worksheet
With objTempWorksheet.Cells(1)
.PasteSpecial xlPasteColumnWidths
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
'Save the Temp Worksheet as a HTML File
strTempHTMLFile = objFileSystem.GetSpecialFolder(2).Path & _
"\Temp for Excel" & Format(Now, "YYYY-MM-DD hh-mm-ss") & ".htm"
Set objTempHTMLFile = objTempWorkbook.PublishObjects.Add(xlSourceRange, _
strTempHTMLFile, objTempWorksheet.Name, objTempWorksheet.UsedRange.Address)
objTempHTMLFile.Publish (True)
strGreeting = "Hello," & vbNewLine & vbNewLine & _
"Body goes here " & vbNewLine & vbNewLine
Set olApp = New Outlook.Application
Set olEmail = olApp.CreateItem(olMailItem)
With olEmail
Set olInsp = .GetInspector ' A side effect is to get the signature
Set wdDoc = olInsp.WordEditor
wdDoc.Range.InsertBefore strGreeting
wdDoc.Paragraphs(5).Range.Paste
'Insert the Temp Worksheet into the Email Body
Dim wb1 As Workbook
Set wb1 = ActiveWorkbook
Dim TempFilePath As String
TempFilePath = Environ$("temp") & "\"
Dim TempFileName As String
TempFileName = "Output Data"
Dim FileExtStr As String
FileExtStr = ".xlsx"
Debug.Print TempFilePath & TempFileName
wb1.SaveAs TempFilePath & TempFileName, FileFormat:=xlOpenXMLWorkbook
.Display
End With
objTempWorkbook.Close (False)
objFileSystem.DeleteFile (strTempHTMLFile)
Kill TempFilePath & TempFileName & FileExtStr 'Delete the temp Excel File
Set olApp = Nothing
Set olEmail = Nothing
Set olInsp = Nothing
Set wdDoc = Nothing
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub

Related

How can I set the alignment of HTML table in mail Body in VBA [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
How can I set the alignment of my HTML table in outlook mail Body.Please find my below code and guide the same.
Sub Mailing()
DefPath = "mypath"
strDate = Format(Now, " dd-mm-yy")
FileNameFolder = DefPath & "CRM-Report" & strDate & "\"
fname = Dir(FileNameFolder & "\*.xlsx")
Path = FileNameFolder
Worksheets("Email").Select
lr = Cells(Rows.Count, 1).End(xlUp).Row
Set mail_array = Range(Cells(2, 1), Cells(lr, 2))
mail_array.Select
Do While fname <> ""
fullsheet = (Path & fname)
file_no = Split(fname, "-")
mail_ID = Application.VLookup(CDbl(file_no(0)), mail_array, 2, 0)
CC = Application.VLookup(CDbl(file_no(0)), mail_array, 2, 0)
Workbooks.Open (fullsheet)
'Call Mail_Sheet_Outlook_Body'''''''''''''''''''''''''''''''''''''''''''
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
strDate = Format(Now, " dd-mmm-yyyy")
With OutMail
.display
End With
Signature = OutMail.HTMLBody
On Error Resume Next
With OutMail
.To = mail_ID
.CC = CC
.BCC = ""
.Subject = file_no(1) & "CRM Meeting report for the Month of "
.HTMLBody = "<p align=""left"">" & RangetoHTML(rng) & "</p>" & "<br>" & Signature
'I have tried the above code but its not working.
.Attachments.Add (fullsheet)
.display
'.Send 'or use .Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
fname = Dir()
Loop
End Sub
With the below function I will get the RangetoHTML(rng) Please guide ho to set the alignment.
Function RangetoHTML(rng As Range)
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
'TempFile = ThisWorkbook.Path & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
TempFile = Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
Set x = ActiveWorkbook
Set TempWB = x
Set rng = Nothing
Set rng = ActiveSheet.UsedRange
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(2).Name, _
Source:=TempWB.Sheets(2).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
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function

Get data from multiple cells

I'm using VBA code from Ron de Bruin that sends every sheet with an email address to the address in a specified cell. It's meant to send the sheet as an attachment.
I want to get data from multiple cells, to put in the body of the email.
I commented out the parts that send the attachment and sent an email that contained data from one cell in the body of the email.
I cannot get data from multiple cells. The email arrives blank.
Sub Mail_Every_Worksheet()
'Working in Excel 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
Dim sh As Worksheet
Dim wb As Workbook
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim TempFilePath As String
Dim TempFileName As String
Dim OutApp As Object
Dim OutMail As Object
TempFilePath = Environ$("temp") & "\"
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007-2016
FileExtStr = ".xlsm": FileFormatNum = 52
End If
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Set OutApp = CreateObject("Outlook.Application")
For Each sh In ThisWorkbook.Worksheets
If sh.Range("B1").Value Like "?*#?*.?*" Then
sh.Copy
Set wb = ActiveWorkbook
TempFileName = "Sheet " & sh.Name & " of " _
& ThisWorkbook.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")
Set OutMail = OutApp.CreateItem(0)
With wb
.SaveAs TempFilePath & TempFileName & FileExtStr, FileFormat:=FileFormatNum
On Error Resume Next
With OutMail
.To = sh.Range("B1").Value
.CC = ""
.BCC = ""
.Subject = "Monthly Shirt Sales"
Dim cell As Range
Dim strbody As String
For Each cell In
ThisWorkbook.Sheets("Sheet1").Range("A4:A36")
strbody = strbody & cell.Value & vbNewLine
Next
'.Attachments.Add wb.FullName
'You can add other files also like this
'.Attachments.Add ("C:\test.txt")
.Send 'or use .Display
End With
On Error GoTo 0
.Close savechanges:=False
End With
Set OutMail = Nothing
Kill TempFilePath & TempFileName & FileExtStr
End If
Next sh
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
It works to send the data from one cell when I replace
Dim cell As Range
Dim strbody As String
For Each cell In ThisWorkbook.Sheets("Sheet1").Range("A4:A36")
strbody = strbody & cell.Value & vbNewLine
Next
with this:
.Body = sh.Range("A4").Value
so I thought that using this would work:
.Body = sh.Range("A4:B36").Value
but it also does not get data and sends a blank email.
How do I get data from multiple cells?
You need to loop through the range and combine the values in the range like in the following example;
Dim strbody As String
For Each cell In sh.Range("A1:B2")
strbody = strbody & cell.Value & vbNewLine
Next cell
Then include the strbody in you outlook with statement
With OutMail
.To = sh.Range("B1").Value
.CC = ""
.BCC = ""
.Subject = "Monthly Shirt Sales"
.Body = strbody
.send 'or use .Display
End With

Difficulties sending worksheet through email via SendWorksheet button

I have an Excel 2016 worksheet with a "Send Worksheet" button purposed to email the worksheet to all the designated recipients. When I run the following code (most of which came from another program and tweaked), I receive the following errors:
Runtime Error 429: ActiveX component can't create object.
at Set OutlookApp = CreateObject("Outlook.Application")
as well as
Runtime Error 91: Object variable or With block variable not set.
in the With block at .To = "email address".
Option Explicit
Private Sub cmdSendWorksheet_Click()
Dim xFile As String
Dim xFormat As Long
Dim Wb As Workbook
Dim Wb2 As Workbook
Dim FilePath As String
Dim FileName As String
Dim OutlookApp As Object
Dim OutlookMail As Object
'On Error Resume Next
Application.ScreenUpdating = False
Set Wb = Application.ActiveWorkbook
ActiveSheet.Copy
Set Wb2 = Application.ActiveWorkbook
Select Case Wb.FileFormat
Case xlOpenXMLWorkbook:
xFile = ".xlsx"
xFormat = xlOpenXMLWorkbook
Case xlOpenXMLWorkbookMacroEnabled:
If Wb2.HasVBProject Then
xFile = ".xlsm"
xFormat = xlOpenXMLWorkbookMacroEnabled
Else
xFile = ".xlsm"
xFormat = xlOpenXMLWorkbook
End If
End Select
FilePath = Environ$("temp") & "\"
FileName = Wb.Name & Format(Now, "dd-mmm-yy h-mm-ss")
Set OutlookApp = CreateObject("Outlook.Application")
Set OutlookMail = OutlookApp.CreateItem(0)
Wb2.SaveAs FilePath & FileName & xFile, FileFormat:=xFormat
With OutlookMail
.To = "email address"
.CC = ""
.BCC = ""
.Subject = "Worksheet Attached"
.Body = "Please see attached worksheet"
.cmdSendWorksheet.Enabled = True
.Attachments.Add Wb2.FullName
.Send
End With
Wb2.Close
Kill FilePath & FileName & xFile
Set OutlookMail = Nothing
Set OutlookApp = Nothing
Application.ScreenUpdating = True
End Sub
this code should do the job you need. But you need to go in Tools / References and check the following reference :
Microsoft Scripting Runtime
Microsoft Outlook 14.0 Object Library
Private Sub cmdSendWorksheet_Click()
Dim Wb As Workbook
Dim FilePath As String
Dim FileName As String
Dim FileExtensionName As String
Dim FileFullPath As String
Dim OutlookApp As New Outlook.Application
Dim OutlookMail As Outlook.MailItem
Dim fso As New FileSystemObject
'On Error Resume Next
Application.ScreenUpdating = False
Set Wb = ThisWorkbook
FilePath = Environ$("temp") & "\"
FileName = fso.GetBaseName(Wb.Path & "\" & Wb.Name) & Format(Now, "dd-mmm-yy h-mm-ss")
FileExtensionName = fso.GetExtensionName(Wb.Path & "\" & Wb.Name)
FileFullPath = FilePath & FileName & "." & FileExtensionName
fso.CopyFile Wb.Path & "\" & Wb.Name, FileFullPath
'Sending the email
Set OutlookMail = OutlookApp.CreateItem(olMailItem)
With OutlookMail
.To = "email address"
.CC = ""
.BCC = ""
.Subject = "Worksheet Attached"
.Body = "Please see attached worksheet"
.Attachments.Add FileFullPath
.Display
'.Send You can chose .Send or .Display, as you wish
End With
Kill FileFullPath
'Free the memory
Set OutlookMail = Nothing
Set OutlookApp = Nothing
Set fso = Nothing
Application.ScreenUpdating = True
Application.Quit
End Sub

Range in Middle of the email body

I am working on a Code which can get the range/selection in the middle of the email body. The below code works a bit fine for me it does not captures the desired range in the middle of the email body. This will save my time to work manually.
Sub Selection_email()
Dim bStarted As Boolean
Dim olApp As Object: Set olApp = CreateObject("Outlook.Application")
Dim olMailItm As Object: Set olMailItm = olApp.CreateItem(0)
Dim rngTo As Range
Dim rngSubject As Range
Set oOutlookApp = GetObject(, "Outlook.Application")
If Err <> 0 Then
Set oOutlookApp = CreateObject("Outlook.Application")
bStarted = True
End If
Set oItem = oOutlookApp.CreateItem(olMailItem)
With Active Sheet
Set rngTo = .Rng("E3")
Last = ActiveSheet.Cells(2, 4).Value
End With
With oItem
.SentOnBehalfOfName = ""
.To = rngTo.Value
.Cc = ""
.Subject = "" & Last & ""
.body = "Hello," & vbNewLine & vbNewLine & _
"Welcome to My World"& vbNewLine & vbNewLine & _
**HERE I NEED THE CODE TO PASTE THE RANGE FROM THE EXCEL FILE IT SHOULD BE FROM "A1:D6"**
"Thank you for your cooperation."
.Display.
If bStarted Then
oOutlookApp.Quit
End If
Set oOutlookApp = Nothing
End Sub
Option Explicit
Sub Selection_email()
Dim bStarted As Boolean
Dim olApp As Object
Dim oItem As Outlook.MailItem
Dim olMailItm As Object
Dim rngTo As Range
Dim rngSubject As Range
Dim Last As Variant
Dim htmlString As String
Dim beginBody, endBody As String
Dim oOutlookApp As Outlook.Application
Set olApp = CreateObject("Outlook.Application")
Set olMailItm = olApp.CreateItem(0)
Set oOutlookApp = GetObject(, "Outlook.Application")
If Err <> 0 Then
Set oOutlookApp = CreateObject("Outlook.Application")
bStarted = True
End If
Set oItem = oOutlookApp.CreateItem(olMailItem)
With ActiveSheet
Set rngTo = .Range("E3")
Last = ActiveSheet.Cells(2, 4).Value
End With
'create the HTML table first --
' this builds a string with proper HTML header info
htmlString = RangetoHTML(ActiveSheet.Range("A1:D6"))
'now add the email greeting to the body information
beginBody = Left(htmlString, InStr(1, htmlString, "<body>", vbTextCompare) + 6)
endBody = Right(htmlString, Len(htmlString) - InStr(1, htmlString, "<body>", vbTextCompare) + 5)
htmlString = beginBody & _
"Hello,<br><br>Welcome to My World<br><br>" & _
endBody
'now find the end of the table and add the signoff message
beginBody = Left(htmlString, InStr(1, htmlString, "</div>", vbTextCompare) + 6)
endBody = Right(htmlString, Len(htmlString) - InStr(1, htmlString, "</div>", vbTextCompare) + 5)
htmlString = beginBody & _
"<br><br>Thank you for your cooperation." & _
endBody
With oItem
.SentOnBehalfOfName = ""
.To = rngTo.Value
.CC = ""
.Subject = "" & Last & ""
.HTMLBody = htmlString
.Display
End With
If bStarted Then
oOutlookApp.Quit
End If
Set oOutlookApp = Nothing
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
I'm assuming "A1:D6" is one merged ranged. You only want the top left cell in that case. If I've made an incorrect assumption let me know.
.body = "Hello," & vbNewLine & vbNewLine & _
"Welcome to My World"& vbNewLine & vbNewLine & _
Activesheet.range("A1").value & _
"Thank you for your cooperation."Replacing Activesheet with something more specific would also be a good idea but depends on your worksheets.
Edit
Using the RangeToHTML function found here: Paste specific excel range in outlook
Then change
.body = "Hello," & vbNewLine & vbNewLine & _
"Welcome to My World"& vbNewLine & vbNewLine & _
**HERE I NEED THE CODE TO PASTE THE RANGE FROM THE EXCEL FILE IT SHOULD BE FROM "A1:D6"**
"Thank you for your cooperation."
to
.HTMLBody = "Hello," & vbNewLine & vbNewLine & _
"Welcome to My World"& vbNewLine & vbNewLine & _
RangeToHTML(activesheet.range("A1:D6")) & _
"Thank you for your cooperation."

Export from Excel to Outlook

My workbook has 5 different sheets and I need to copy the five sheets and paste it into 5 different mails. Preferably as HTML.
The below written code only attaches the different sheets to outlook. I need the HTML below the body of the email. Please note that my range in the sheets varies from workbook to workbook but the sheet names remain the same.
Function BrowseForFolder(Optional OpenAt As Variant) As Variant
'Function purpose: To Browser for a user selected folder.
'If the "OpenAt" path is provided, open the browser at that directory
'NOTE: If invalid, it will open at the Desktop level
'BrowseForFolder was a code originally written by Ron De Bruin, I love this function!
Dim ShellApp As Object
'Create a file browser window at the default folder
Set ShellApp = CreateObject("Shell.Application"). _
BrowseForFolder(0, "Please choose a folder", 0, OpenAt)
'Set the folder to that selected. (On error in case cancelled)
On Error Resume Next
BrowseForFolder = ShellApp.self.Path
On Error GoTo 0
'Destroy the Shell Application
Set ShellApp = Nothing
'Check for invalid or non-entries and send to the Invalid error
'handler if found
'Valid selections can begin L: (where L is a letter) or
'\\ (as in \\servername\sharename. All others are invalid
Select Case Mid(BrowseForFolder, 2, 1)
Case Is = ":"
If Left(BrowseForFolder, 1) = ":" Then GoTo Invalid
Case Is = "\"
If Not Left(BrowseForFolder, 1) = "\" Then GoTo Invalid
Case Else
GoTo Invalid
End Select
Exit Function
Invalid:
'If it was determined that the selection was invalid, set to False
BrowseForFolder = False
End Function
Sub SaveWorksheets()
'saves each worksheet as a separate file in a specific folder.
Dim ThisFolder As String
Dim NameOfFile As String
Dim Period As String
Dim RecipName As String
ThisFolder = BrowseForFolder()
Application.ScreenUpdating = False
Dim ws As Worksheet
Dim wsName As String
For Each ws In ActiveWorkbook.Worksheets
wsName = ws.Name
If wsName <> "Data" Then
Period = ws.Cells(4, 1).Value 'put the row and column numbers of the report date here.
RecipName = ws.Cells(1, 29).Value 'put the row and column numbers of the email address here
NameOfFile = ThisFolder & "\" & "Termination Report " & wsName & " " & Period & ".xlsx"
ws.Select
ws.Copy
ActiveWorkbook.SaveAs Filename:= _
NameOfFile, FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
ActiveWindow.Close
Call EmailWorkbooks(RecipName, NameOfFile)
End If
Next ws
End Sub
Sub EmailWorkbooks(RecipName, NameOfFile)
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.createItem(0)
Msg = "Attached is the xyz report for your review. Please let me know if you have any questions" & vbCrLf & vbCrLf _
& "Thanks," & vbCrLf & vbCrLf _
& "Your Name Here" & vbCrLf _
& "Your Title" & vbCrLf _
& "Your contact info"
Subj = "XYZ Report" & " " & Period
On Error Resume Next
With OutMail
.To = RecipName
'.CC =
.Subject = Subj
.Body = Msg
.Attachments.Add (NameOfFile)
.Save
End With
On Error GoTo 0
End Sub
U can use Add method of PublishObjects collection, short example:
Sub InsertSheetContent()
Dim onePublishObject As PublishObject
Dim oneSheet As Worksheet
Dim scriptingObject As Object
Dim outlookApplication As Object
Dim outlookMail As Object
Dim htmlBody As String
Dim htmlFile As String
Dim textStream
Set scriptingObject = CreateObject("Scripting.FileSystemObject")
Set outlookApplication = CreateObject("Outlook.Application")
For Each oneSheet In ThisWorkbook.Worksheets
htmlFile = ThisWorkbook.Path & "\" & ThisWorkbook.Name & "_" & oneSheet.Name & ".html"
Set onePublishObject = ThisWorkbook.PublishObjects.Add(SourceType:=xlSourceRange, _
Filename:=htmlFile, _
Sheet:=oneSheet.Name, _
Source:=oneSheet.UsedRange.Address, _
HtmlType:=xlHtmlStatic, _
DivID:=oneSheet.Name)
onePublishObject.Publish Create:=True
Set textStream = scriptingObject.OpenTextFile(htmlFile)
htmlBody = textStream.ReadAll
Set outlookMail = outlookApplication.CreateItem(0)
With outlookMail
.htmlBody = htmlBody
.Display
End With
Next oneSheet
End Sub